Image Extraction
ExtractPageImages returns every image drawn on a page, together with where and how
large it appears:
ex, err := extractor.New(page)
if err != nil {
return err
}
pageImages, err := ex.ExtractPageImages(nil)
if err != nil {
return err
}
for _, img := range pageImages.Images {
goImg, err := img.Image.ToGoImage()
if err != nil {
return err
}
// ... encode goImg as PNG or JPEG ...
}Passing nil uses the defaults. ToGoImage converts to a standard library
image.Image, which is what lets you hand it to png.Encode or jpeg.Encode.
Displayed size is not pixel size
Each ImageMark separates the two, and mixing them up is the usual source of
confusion:
WidthandHeightare the dimensions as displayed on the page, in PDF units.XandYare the position in PDF coordinates, measured from the image’s lower left corner.Angleis the rotation in degrees, if any.
The pixel dimensions live on img.Image instead. A small logo scaled up across half a
page has a large Width and a small pixel count, so use the pixel values when writing
files and the display values when reasoning about layout.
Inline stencil masks
Inline stencil masks are skipped by default. Pass options to include them:
pageImages, err := ex.ExtractPageImages(&extractor.ImageExtractOptions{
IncludeInlineStencilMasks: true,
})These are one-bit masks used for stencilled drawing rather than pictures, so they are usually noise when what you want is the document’s images. Turn them on when you are auditing everything a page draws.
Run the example
The example walks every page, converts each image to a Go image, and writes the lot
into a zip archive. extractImagesToArchive holds the extraction and encoding loop.
git clone https://github.com/unidoc/unipdf-examples.git
cd unipdf-examples/extract
go run pdf_extract_images.go input.pdf images.zipIf this is your first time using UniPDF, follow the getting started guide to create an API key and set up your development environment.