Monday 19 December 2011

Make PDF Using RichTextBox


For making PDF File, you need to add component file called itextsharp.dll to your project.
Itextsharp.dll can be downloaded from http://sourceforge.net/projects/itextsharp/.
Import below headers in your project
Imports System
Imports System.IO
Imports iTextSharp
Imports iTextSharp.text.pdf
Imports iTextSharp.text
Write the below code on the click event of SavePDF Button.
Private Sub btnSavePdf_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSavePdf.Click
        ' Create Document class object and set its size to letter and give space left, right, Top, Bottom Margin
        Dim doc As New Document(iTextSharp.text.PageSize.A4, 40, 40, 40, 10)
        ' Using Savefiledialog
        SaveFileDialog1.ShowDialog()
        If SaveFileDialog1.FileName = "" Then
MsgBox("pdf not created. Enter Filename to create pdf")
Exit Sub
        End If

        Try
            Dim wri As PdfWriter = PdfWriter.GetInstance(doc, New FileStream(SaveFileDialog1.FileName + ".pdf", FileMode.Create))
            ' Open Document to write
            doc.Open()

            ' Declaring p1 as Paragraph
            Dim p1 As New Paragraph
            ' setting line spacing between paragraph to 1.
            Dim linespacing As Single = 1.0F
            ' Setting font for Paragraph to arial
            p1.Font = FontFactory.GetFont("ARIAL", 9.0F)
            ' Adding RichTextBox to Paragraph
            p1.Add(rtb.Text)
            ' Adding Paragraph to Document
            doc.Add(p1)

            ' Document Closing
            doc.Close()

        Catch docEx As DocumentException
            MessageBox.Show(docEx.Message)
            ' handle IO exception
        Catch ioEx As IOException
            ' hahndle other exception if occurs
            MessageBox.Show(ioEx.Message)
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        Finally
            'Close document and writer
            doc.Close()
            MsgBox("pdf Created Successfully")
        End Try

    End Sub

Now Run the Program
When SavePDF Button is Clicked, Program will ask where to save the PDF File. Type Filename, Browse the location to save the file, and then  Press OK.

If the file is saved, you will get message as “pdf Created Successfully”.
If the file is cancelled, you will get message as “pdf not created. Enter Filename to create pdf

Saved PDF File is given below. 


3 comments:

  1. Thanks for that! Well done

    ReplyDelete
  2. Hi, this example worked for me to create a PDF from a RichTextBox, however the Pdf was left without the rich text format that the control had. Is there a way to make it respect the format of the RichTextBox control?

    ReplyDelete