Fit image to PDF page

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.

![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:

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

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

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

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)
    document.Pages.Add(page)

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

    center(page, image)
    Using fs As New FileStream("output.pdf", FileMode.Create, FileAccess.Write)
        document.Write(fs)
    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)
    Else
        ' A tall rectangle case
        image.Height = page.Height
        image.Transform = New TranslateTransform((page.Width - image.Width) / 2, 0)
    End If
End Sub