#2 – VB.Net iTextSharp Tutorial – Add an image to a document

This is part of a series of iTextSharp tutorials for VB 2010 Express. See this post for an overview and to answer any basic questions that you may have.

Option Explicit On
Option Strict On

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

Public Class Form1
    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        ''//The main folder that we are working in
        Dim WorkingFolder = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)

        ''//The file that we are creating
        Dim WorkingFile = Path.Combine(WorkingFolder, "Output.pdf")

        Dim SampleImage = Path.Combine(WorkingFolder, "IMG_0259.JPG")

        ''//Create our file with an exclusive writer lock
        Using FS As New FileStream(WorkingFile, FileMode.Create, FileAccess.Write, FileShare.None)
            ''//Create our PDF document
            Using Doc As New Document(PageSize.LETTER)
                ''//Bind our PDF object to the physical file using a PdfWriter
                Using Writer = PdfWriter.GetInstance(Doc, FS)
                    ''//Open our document for writing
                    Doc.Open()

                    ''//Insert a blank page
                    Doc.NewPage()

                    ''//Add an image to a document. This does not scale the image or anything so if your image is large it might go off the canvas
                    Doc.Add(iTextSharp.text.Image.GetInstance(SampleImage))

                    ''//Close our document
                    Doc.Close()
                End Using
            End Using
        End Using

        Me.Close()
    End Sub
End Class