#3 – VB.Net iTextSharp Tutorial – Add a scaled 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.

This post is a followup to the previous one, this time it scales the image based on the document’s size

<br />
Option Explicit On<br />
Option Strict On</p>
<p>Imports System.IO<br />
Imports iTextSharp.text<br />
Imports iTextSharp.text.pdf</p>
<p>Public Class Form1<br />
    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load<br />
        ''//The main folder that we are working in<br />
        Dim WorkingFolder = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)</p>
<p>        ''//The file that we are creating<br />
        Dim WorkingFile = Path.Combine(WorkingFolder, &quot;Output.pdf&quot;)</p>
<p>        Dim SampleImage = Path.Combine(WorkingFolder, &quot;IMG_5605.JPG&quot;)</p>
<p>        ''//Create our file with an exclusive writer lock<br />
        Using FS As New FileStream(WorkingFile, FileMode.Create, FileAccess.Write, FileShare.None)<br />
            ''//Create our PDF document<br />
            Using Doc As New Document(PageSize.LETTER)<br />
                ''//Bind our PDF object to the physical file using a PdfWriter<br />
                Using Writer = PdfWriter.GetInstance(Doc, FS)<br />
                    ''//Open our document for writing<br />
<p>                    ''//Insert a blank page<br />
<p>                    ''//Create a PDF image object from our physical image<br />
                    Dim ThisImage = iTextSharp.text.Image.GetInstance(SampleImage)</p>
<p>                    ''//Use standard ratio resizing algorithms to calculate new image dimensions based on the documents dimensions. This will shrink or grow documents to fit</p>
<p>                    ''//Will hold our new image dimensions<br />
                    ''//Documents sometimes have margins (and this sample does) so subtract them so that our image in centered in the page<br />
                    Dim NewW, NewH As Single</p>
<p>                    NewW = Doc.PageSize.Width - (Doc.LeftMargin + Doc.RightMargin)<br />
                    NewH = Doc.PageSize.Height - (Doc.TopMargin + Doc.BottomMargin)</p>
<p>                    ''//Scale the image<br />
                    ThisImage.ScaleToFit(NewW, NewH)</p>
<p>                    ''//Add the image to the document<br />
<p>                    ''//Close our document<br />
                    Doc.Close()<br />
                End Using<br />
            End Using<br />
        End Using</p>
<p>        Me.Close()<br />
    End Sub<br />
End Class</p>