Skip to content
Add Images to PDF

Add Images to PDF

Building a PDF from a folder of images means sizing each page to its image rather than fitting the image to a fixed page. The creator lets you change the page size between pages, so each NewPage can take the aspect ratio of the image about to be drawn on it.

Doing it

img, err := c.NewImageFromFile(imgPath)
if err != nil {
    return err
}

pageWidth := 612.0
img.ScaleToWidth(pageWidth)

pageHeight := pageWidth * img.Height() / img.Width()
c.SetPageSize(creator.PageSize{pageWidth, pageHeight})
c.NewPage()

img.SetPos(0, 0)
if err := c.Draw(img); err != nil {
    return err
}

Order matters twice here. SetPageSize only affects pages created after the call, so it has to come before NewPage. And img.Height() and img.Width() report the current drawn size, so read them after ScaleToWidth to get the scaled ratio.

SetPos(0, 0) puts the image at the top left corner with no margin, which is what you want for a full-bleed page. Without it the image is placed in relative mode and lands inside the page margins, which SetPageSize resets to ten percent of the page width, so the image would be scaled to the page but offset and clipped.

Image fidelity

A JPEG source is embedded with the default DCT encoder, which passes the original bytes through byte for byte. There is no decode and re-encode round trip, so nothing is lost, and encoder settings such as quality have no effect. To force a re-encode, install a different encoder with Image.SetEncoder, for example a Flate encoder.

An ICC color profile in the source image is preserved and attached to the embedded image as an ICCBased colorspace.

Limitations

c.NewImageFromFile handles the formats the Go image decoders cover: JPEG, PNG and GIF. Anything else has to be decoded by your own code and passed through c.NewImage from a model.Image.

Page dimensions are in points, and a page sized from a large photo’s pixel count can be enormous. The example pins the width at 612 points, letter width, and derives the height, which keeps pages within what viewers and printers handle.

Run the example

imagesToPdf loops over the input paths, sizing a page per image, and writes the result once at the end. The first command-line argument is the output file; the rest are the images.

git clone https://github.com/unidoc/unipdf-examples.git
cd unipdf-examples/image
go run pdf_images_to_pdf.go output.pdf img1.jpg img2.png

If this is your first time using UniPDF, follow the getting started guide to create an API key and set up your development environment.

View the full source
Last updated on