Search This Blog

Wednesday, July 8, 2009

Create a PDF using iTextSharp in vb.net

Imports iTextSharp
Imports iTextSharp.text
Imports iTextSharp.text.pdf
Imports iTextSharp.text.xml
Imports System.Text
Imports System.IO

'Download the iTextSharp DLL in add as reference

Public Sub create_pdf()
Dim rct As New Rectangle(850, 1100)
'Create Document class obejct and set its size to letter and give space left, right, Top, Bottom Margin

'file_name_pdf variable name of the pdf set as per necessity, rct is size of pdf
Dim doc As New Document(rct, 3, 3, 3, 3)
Try
If file_name_pdf <> "" Then
Dim file As System.IO.FileInfo = New FileInfo(file_name_pdf)
Dim wri As PdfWriter = PdfWriter.GetInstance(doc, New FileStream(file.DirectoryName & "\" & file.Name & ".pdf", FileMode.Create))
Else
Dim wri As PdfWriter = PdfWriter.GetInstance(doc, New FileStream("c:\Graph.pdf", FileMode.Create))
End If

'Open Document to write
doc.Open()
'Write some content
Dim paragraph As New Paragraph("Paragraph.")
Dim pharse As New Phrase("Pharse.")
Dim chunk As New Chunk(" Chunk.")

' Dim img As iTextSharp.text.Image = Nothing
' Dim underContent As iTextSharp.text.pdf.PdfContentByte = Nothing
' Dim rect As iTextSharp.text.Rectangle = Nothing


doc.Add(paragraph)
doc.Add(pharse)
doc.Add(chunk)
Dim gif As Image

'file_name_pdf variable name of the pdf set as per necessity
If file_name_pdf <> "" Then
'MessageBox.Show(file_name_pdf)
gif = Image.GetInstance(file_name_pdf + ".jpg")
Else
gif = Image.GetInstance("c:\" + "Graph.jpg")
End If
'Adding a gif file
doc.Add(gif)
Catch dex As DocumentException
'Handle document exception
Catch ioex As IOException
'Handle IO exception
Catch ex As Exception
'Handle Other Exception
Finally
'Close document
doc.Close()
End Try
End Sub

No comments:

Post a Comment