iTextSharp Code

by Charles Cherry

I’m posting this here just for future reference.


Imports System.Drawing
Imports System.IO
Imports iTextSharp.text
Imports iTextSharp.text.pdf

Public Class PDFPrinter

Public Function ImagesToPDFByteArray(ByVal Images As List(Of Bitmap)) As Byte()

Dim myResults As Byte() = Nothing
Dim myDocument As iTextSharp.text.Document = Nothing
Dim mySize As iTextSharp.text.Rectangle = Nothing
Dim ms As IO.MemoryStream = Nothing

Try

myDocument = New iTextSharp.text.Document(PageSize.LETTER.Rotate, 0, 0, 0, 0)
mySize = myDocument.PageSize
ms = New IO.MemoryStream

pdf.PdfWriter.GetInstance(myDocument, ms)

myDocument.Open()

If Images.Count > 0 Then
For i As Integer = 0 To Images.Count - 1
Dim mySource As Drawing.Image = CType(Images(i), Bitmap)
Dim myImage As iTextSharp.text.Image = iTextSharp.text.Image.GetInstance(mySource, Drawing.Imaging.ImageFormat.Png)
myImage.ScaleAbsolute(mySize.Width, mySize.Height)
myDocument.Add(myImage)
Next
End If

myDocument.Close()

If Not ms Is Nothing AndAlso ms.GetBuffer.Length > 0 Then
myResults = ms.ToArray
End If

Finally

ms.Flush()
ms.Close()
ms = Nothing
myDocument = Nothing
mySize = Nothing

End Try

Return myResults

End Function

Public Function ImagesToPDFBase64(ByVal Images As List(Of Bitmap)) As String

Dim myResults As String = String.Empty
Dim myDocument As iTextSharp.text.Document = Nothing
Dim mySize As iTextSharp.text.Rectangle = Nothing
Dim ms As IO.MemoryStream = Nothing

Try

myDocument = New iTextSharp.text.Document(PageSize.LETTER.Rotate, 0, 0, 0, 0)
mySize = myDocument.PageSize
ms = New IO.MemoryStream

pdf.PdfWriter.GetInstance(myDocument, ms)

myDocument.Open()

If Images.Count > 0 Then
For i As Integer = 0 To Images.Count - 1
Dim mySource As Drawing.Image = CType(Images(i), Bitmap)
Dim myImage As iTextSharp.text.Image = iTextSharp.text.Image.GetInstance(mySource, Drawing.Imaging.ImageFormat.Png)
myImage.ScaleAbsolute(mySize.Width, mySize.Height)
myDocument.Add(myImage)
Next
End If

myDocument.Close()

If Not ms Is Nothing AndAlso ms.GetBuffer.Length > 0 Then
myResults = Convert.ToBase64String(ms.GetBuffer, Base64FormattingOptions.None)
End If

Finally

ms.Flush()
ms.Close()
ms = Nothing
myDocument = Nothing
mySize = Nothing

End Try

Return myResults

End Function

End Class

Advertisements