Fit image to PDF page

Generate PDF, Convert PDF, Images, Shapes, Manipulate PDF
9/19/2011

Downloads

This code sample shows how to stamp an image on a PDF page and have the image fit to the size of the page.

In general the image will not have the same aspect ratio as the page. This is shown in the next figure.

image

In order to keep the aspect ratio, we set the ImageShape.KeepAspectRatio to true. In the left case, we set the height of the image equal to the height of the page and center horizontally. In the right case we set the width of the image equal to the width of the page and center vertically.

Here is the code:

C# code sample

1 static void Main(string[] args) 2 { 3 Document document = new Document(); 4 Page page = new Page(PageSize.Letter); 5 document.Pages.Add(page); 6 7 ImageShape image = new ImageShape("../../image.png"); 8 image.KeepAspectRatio = true; 9 page.VisualOverlay.Add(image); 10 11 center(page, image); 12 using (FileStream fs = new FileStream("output.pdf", FileMode.Create, FileAccess.Write)) 13 { 14 document.Write(fs); 15 } 16 } 17 18 public static void center(Page page, ImageShape image) 19 { 20 double pageRatio = page.Width / page.Height; 21 double imageRatio = image.Width / image.Height; 22 23 if (imageRatio >= pageRatio) //A fat rectangle case 24 { 25 image.Width = page.Width; 26 image.Transform = new TranslateTransform(0, (page.Height - image.Height) / 2); 27 } 28 else // A tall rectangle case 29 { 30 image.Height = page.Height; 31 image.Transform = new TranslateTransform((page.Width - image.Width) / 2, 0); 32 } 33 }

VB.NET code sample

1 Sub Main() 2 Dim document As New Document() 3 Dim page As New Page(PageSize.Letter) 4 document.Pages.Add(page) 5 6 Dim image As New ImageShape("../../image.png") 7 image.KeepAspectRatio = True 8 page.VisualOverlay.Add(image) 9 10 center(page, image) 11 Using fs As New FileStream("output.pdf", FileMode.Create, FileAccess.Write) 12 document.Write(fs) 13 End Using 14 End Sub 15 16 Public Sub center(page As Page, image As ImageShape) 17 Dim pageRatio As Double = page.Width / page.Height 18 Dim imageRatio As Double = image.Width / image.Height 19 20 If imageRatio >= pageRatio Then 21 'A fat rectangle case 22 image.Width = page.Width 23 image.Transform = New TranslateTransform(0, (page.Height - image.Height) / 2) 24 Else 25 ' A tall rectangle case 26 image.Height = page.Height 27 image.Transform = New TranslateTransform((page.Width - image.Width) / 2, 0) 28 End If 29 End Sub