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
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_5605.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()
''//Create a PDF image object from our physical image
Dim ThisImage = iTextSharp.text.Image.GetInstance(SampleImage)
''//Use standard ratio resizing algorithms to calculate new image dimensions based on the documents dimensions. This will shrink or grow documents to fit
''//Will hold our new image dimensions
''//Documents sometimes have margins (and this sample does) so subtract them so that our image in centered in the page
Dim NewW, NewH As Single
NewW = Doc.PageSize.Width - (Doc.LeftMargin + Doc.RightMargin)
NewH = Doc.PageSize.Height - (Doc.TopMargin + Doc.BottomMargin)
''//Scale the image
ThisImage.ScaleToFit(NewW, NewH)
''//Add the image to the document
Doc.Add(ThisImage)
''//Close our document
Doc.Close()
End Using
End Using
End Using
Me.Close()
End Sub
End Class