Skip to content
How to insert an image into a PDF

How to insert an image into a PDF

Load the image through the creator, size it, then draw it.

c := creator.New()

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

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

Scale before drawing. A freshly loaded image takes its page size straight from its pixel dimensions, one pixel to one point, so a 3000 by 2000 photo starts out 3000 by 2000 points on a 612 by 792 page. Nothing warns you; the image is simply mostly off the page. ScaleToWidth and ScaleToHeight keep the aspect ratio, Scale(xf, yf) does not, and SetWidth changes the drawn size without touching the pixel data.

Without SetPos, the image goes into the normal top-to-bottom flow at the current cursor. SetPos(x, y) switches it to absolute positioning, measured from the top left of the page with y growing downward.

NewImageFromData takes the encoded bytes and NewImageFromGoImage takes a Go image.Image, which is how a chart or a barcode generated in memory gets in. All three produce the same creator.Image, and one of those can be drawn any number of times: the embedded object is built on the first draw and reused, so stamping the same logo on fifty pages costs one copy of the image data.

Stamping onto a document that already exists means reading it with model.PdfReader and passing every page to c.AddPage, including the ones getting no image, since a page you skip does not reach the output.

Placement, encoders and ICC handling are covered in our user guide.

Last updated on