Images
An image reaches a PDF through three objects. model.Image holds the decoded pixel
data and is what ImageHandling.Read gives you from a JPEG, PNG or GIF source.
creator.Image wraps that and carries the placement: size on the page, position,
rotation, opacity, encoder. model.XObjectImage is the embedded PDF object, built
when the image is drawn.
Most code only touches the middle one:
img, err := c.NewImageFromFile("photo.jpg")
if err != nil {
return err
}
img.ScaleToWidth(200)
img.SetPos(72, 72)
if err := c.Draw(img); err != nil {
return err
}Size is in points, not pixels
A freshly loaded image takes its page dimensions straight from its pixel dimensions, one pixel to one point. A 3000 by 2000 photo therefore starts out 3000 by 2000 points, about 41 by 28 inches, on a page that is 612 by 792. Nothing warns you; the image is simply far off the page.
So scale first. ScaleToWidth and ScaleToHeight keep the aspect ratio,
Scale(xf, yf) does not, and SetWidth / SetHeight set the drawn size without
touching the pixel data at all, leaving the resampling to the viewer.
SetFitMode(creator.FitModeFillWidth) scales the image to whatever width the
current context has, which is more robust than a hard-coded number. It only applies
in relative positioning mode, so calling SetPos disables it.
Placement
SetPos(x, y) switches the image to absolute positioning, with the origin at the
top left of the page and y growing downward. That is the opposite of PDF’s native
coordinate system, and it holds for every creator component.
Left in relative mode, the image flows like any other block: it lands at the
current context position, honors SetMargins, and pushes the context down after
itself. An image taller than the space left starts a new page rather than being
clipped.
Neither a table cell nor a grid cell shrinks an image to fit. A table sizes the row
from the image’s current width and height, so an image wider than its column
overflows into the neighbouring one. A grid cell does apply the image’s fit mode
when it measures the row, so FitModeFillWidth is the reliable way to keep an
image inside a grid column.
Encoding
By default the encoder is chosen for you, and for a JPEG source the original bytes are embedded unchanged. That means no quality loss, and also that encoder settings have no effect until you install a non-DCT encoder yourself. The add images to a PDF guide covers this and the ICC profile handling that goes with it.
Where to look
| Guide | Covers |
|---|---|
| Add an image to a page | Placing an image at a position on an existing page, and choosing an encoder. |
| Add images to a PDF | One image per page, JPEG pass-through and ICC profile preservation. |
| List images | Finding every image in a document, including inline images and images inside form XObjects. |
To place an image inside a table or grid cell, see tables and grid. To remove an image that is acting as a watermark, see remove an image watermark.