Can UniPDF compress and optimise PDF documents?
Yes. Optimization happens on the way out of the writer: build an
optimize.Options, hand it to optimize.New, attach the result with
PdfWriter.SetOptimizer.
pdfWriter, err := reader.ToWriter(nil)
if err != nil {
return err
}
pdfWriter.SetOptimizer(optimize.New(optimize.Options{
CompressStreams: true,
UseObjectStreams: true,
SubsetFonts: true,
CleanUnusedResources: true,
}))
return pdfWriter.WriteToFile("output.pdf")Every option is off by default, and each one you enable appends a pass to the
chain. Nothing runs until Write, so there is no separate optimize step and no
in-place optimizer for an open document. Creator output goes through the same
route via Creator.SetPdfWriterAccessFunc.
Nine of the eleven options are lossless. ImageQuality re-encodes images as JPEG
at the quality you give, and ImageUpperPPI downsamples images drawn above a
resolution limit; those two change pixels. CleanContentstream leaves rendering
alone but strips BDC, BMC and EMC, which breaks tagged documents and with
them PDF/UA and the A conformance levels of PDF/A.
The structural passes usually recover around a fifth of a file for almost no cost. Font subsetting often doubles that on text-heavy documents but runs text extraction over every page, making it much the slowest pass. On image-heavy files the image options are where the large reductions are.
A pass that fails does not fail the write. Chain.Optimize logs at debug level
and carries on with the objects it had, so a document that optimizes badly comes
out correct and simply larger, with nothing returned to say so. Debug logging is
the only way to see which pass gave up.
Optimization is not linearization. SetLinearized changes the order objects are
written in and adds hint tables so a viewer can render page 1 without the rest of
the file; it makes the output slightly larger, not smaller.
Option by option in Optimizer options, with font subsetting and linearization alongside it.