How to set and get PDF document outline
PdfReader.GetOutlines reads the bookmark tree as a model.Outline, and
PdfWriter.AddOutlineTree writes one back. The type carries JSON tags, so the
usual workflow is dump, edit, apply.
outlines, err := pdfReader.GetOutlines()
if err != nil {
return err
}
data, err := json.MarshalIndent(outlines, "", " ")Going the other way:
pdfWriter, err := pdfReader.ToWriter(&model.ReaderToWriterOpts{SkipOutlines: true})
if err != nil {
return err
}
pdfWriter.AddOutlineTree(newOutlines.ToOutlineTree())
return pdfWriter.WriteToFile("output.pdf")AddOutlineTree sets the tree, it does not append to it. Adding a single
bookmark to a document means reading the existing outlines with GetOutlines,
adding to that Outline, and writing the whole thing back.
Page numbers in an OutlineDest are zero-based, so the first page is 0. That
is the usual cause of bookmarks landing one page off. Mode decides which of
X, Y and Zoom are written: XYZ uses all three, FitH and FitBH only
Y, FitV and FitBV only X, and Fit and FitB none. An unrecognized mode
is silently replaced with Fit, discarding the coordinates.
A document with no bookmarks is an error rather than an empty result.
GetOutlines returns “the specified reader does not have an outline tree” in
that case, which is an expected outcome, not a failure.
Destinations survive a JSON round trip as a page index, not a reference to the
page object, so applying a saved outline to a document whose pages are in a
different order points the bookmarks at the wrong pages. Color, bold or italic
styling and the initial open state are not part of OutlineItem and cannot be
set through it.
See get outlines and set outlines for building trees in code and for the destination modes in full.