PDFRasterizer.NET 4.0 is now available. Supports .NET Core. Renders pixel-perfectly.

Fit image to PDF page

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.


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:

static void Main(string[] args)
    Document document = new Document();
    Page page = new Page(PageSize.Letter);

    ImageShape image = new ImageShape("../../image.png");
    image.KeepAspectRatio = true;

    center(page, image);
    using (FileStream fs = new FileStream("output.pdf", FileMode.Create, FileAccess.Write))

public static void center(Page page, ImageShape image)
    double pageRatio = page.Width / page.Height;
    double imageRatio = image.Width / image.Height;

    if (imageRatio >= pageRatio) //A fat rectangle case
        image.Width = page.Width;
        image.Transform = new TranslateTransform(0, (page.Height - image.Height) / 2);
    else // A tall rectangle case
        image.Height = page.Height;
        image.Transform = new TranslateTransform((page.Width - image.Width) / 2, 0);
Sub Main()
    Dim document As New Document()
    Dim page As New Page(PageSize.Letter)

    Dim image As New ImageShape("../../image.png")
    image.KeepAspectRatio = True

    center(page, image)
    Using fs As New FileStream("output.pdf", FileMode.Create, FileAccess.Write)
    End Using
End Sub

Public Sub center(page As Page, image As ImageShape)
    Dim pageRatio As Double = page.Width / page.Height
    Dim imageRatio As Double = image.Width / image.Height

    If imageRatio >= pageRatio Then
        'A fat rectangle case
        image.Width = page.Width
        image.Transform = New TranslateTransform(0, (page.Height - image.Height) / 2)
        ' A tall rectangle case
        image.Height = page.Height
        image.Transform = New TranslateTransform((page.Width - image.Width) / 2, 0)
    End If
End Sub
Download PDFKit.NET 4.0
We will send you a download link

  • This field is for validation purposes and should be left unchanged.
Why do we ask your email address?
We send tips that speed up your evaluation
We let you know about bug fixes
You can always unsubscribe with one click
We never share your address with a 3rd party
Thank you for your download

We have sent an email with a download link.