The monthly batch we built in lesson 04-04 brings together, in a single PDF, the cover with the index and all the month's invoices. With five invoices it's easy to handle, but a real batch can have a hundred, and then finding a particular invoice by flicking through pages is maddening. In this last lesson of the module we'll add navigation: bookmarks (the viewer's side panel) with one entry per invoice and its pages, named destinations for opening the PDF directly at an invoice, and links that turn each row of the cover's index into a button. Then we'll move on to annotations, the layer of "notes" that viewers draw on top of the page, so that InvoiceLab can mark the total it has detected on supplier invoices and leave a note for the Purchasing department. All of this reuses what we've learned in the module: the cover's index will be read with TextLocator (06-02), and text positions will tell us where to place each link and each highlight.
Contents
- Where a PDF's navigation lives
- Destinations: which page and how to display it
- Bookmarks for the monthly batch
- Reading a document's bookmarks
- Named destinations
- Internal and external links
- The complete example:
NavigateBatch - Review annotations: highlight and note
- Listing and removing annotations
Where a PDF's navigation lives
Three different structures, in three different places in the document:
flowchart TD
Cat["Catalog"] --> Out["/Outlines<br/>PDDocumentOutline"]
Out --> I1["Bookmark F-2026-0001<br/>PDOutlineItem"]
Out --> I2["Bookmark F-2026-0002"]
I2 --> H1["Page 1"]
I2 --> H2["Invoice total"]
Cat --> Names["/Names → /Dests<br/>named destinations"]
Cat --> Pages["Pages"]
Pages --> Annots["/Annots of each page<br/>links, notes, highlights, widgets"]
I1 -. "/Dest" .-> Pages
Annots -. "/A GoTo" .-> Names
| Element | Where it is | PDFBox class | Seen in |
|---|---|---|---|
| Bookmarks (outline) | Catalog, /Outlines |
PDDocumentOutline, PDOutlineItem |
The viewer's side panel |
| Named destinations | Catalog, /Names /Dests |
PDDestinationNameTreeNode |
Not visible: used from links, bookmarks or the URL |
| Links | /Annots of each page |
PDAnnotationLink |
Active areas of the page |
| Notes, highlights, stamps… | /Annots of each page |
PDAnnotationText, PDAnnotationHighlight… |
On top of the content |
The form widgets from module 5 are annotations too (/Subtype /Widget): we'll bear that in mind when removing annotations.
Destinations: which page and how to display it
A destination specifies a page and how to frame it in the window. PDFBox has one class per type:
| Class | In PDF | Effect | Parameters |
|---|---|---|---|
PDPageFitDestination |
/Fit |
Whole page in the window | — |
PDPageFitWidthDestination |
/FitH top |
Fit to width, with top at the top edge of the window |
setTop(int) |
PDPageXYZDestination |
/XYZ left top zoom |
Bring the point (left, top) to the top-left corner, with a zoom |
setLeft, setTop, setZoom (0 = keep the current one) |
PDPageFitRectangleDestination |
/FitR |
Fit a specific rectangle | setLeft, setBottom, setRight, setTop |
They all inherit from PDPageDestination and need setPage(PDPage). The coordinates (top, left) are PDF coordinates (y upwards), not reading coordinates.
For the batch we'll use two:
private static PDPageFitWidthDestination fitWidth(PDPage page) {
PDPageFitWidthDestination destination = new PDPageFitWidthDestination();
destination.setPage(page);
destination.setTop((int) page.getCropBox().getUpperRightY()); // from the top edge
return destination;
}- Fit to width from the top edge: the natural choice for "go to an invoice".
- XYZ to take the user to a specific point on a page (the invoice total), without changing their zoom.
Bookmarks for the monthly batch
We want this bookmark tree, with the invoices collapsed:
Cover and index
F-2026-0001 · Example Hardware Co. · 1.470,85 €
Page 1
Invoice total
F-2026-0002 · Fictional Construction Ltd. · 4.193,94 €
Page 1
Page 2
Invoice total
...Reading the cover's index
Where do we get each invoice's number, customer, total and page from? We could pass the InvoiceBatch object from InvoiceBatches.create, but then it would only work with freshly generated batches. It's more useful to read the cover's index, which already contains that information, with TextLocator. That way it works with any archived batch. The new BatchNavigation class in the com.invoicelab.extraction package starts like this:
/** A row in the cover's index. page = page (1-based) where the invoice starts. */
public record IndexEntry(String number, String date, String customer, String total, int page) {
}
private static final Pattern ROW = Pattern.compile(
"^(F-\\d{4}-\\d{4}) (\\d{2}/\\d{2}/\\d{4}) (.+) (\\d{1,3}(?:\\.\\d{3})*,\\d{2}\\h€) (\\d+)$");
private static final Color BLUE = new Color(0x1F, 0x3A, 0x5F); // NebulaColors.BLUE
/** Reads the cover's index (page 1) with TextLocator: one line per invoice. */
public static List<IndexEntry> readIndex(PDDocument batch) throws IOException {
List<IndexEntry> entries = new ArrayList<>();
for (Line line : TextLocator.lines(TextLocator.words(batch, 1), 2f)) {
Matcher m = ROW.matcher(line.text());
if (m.matches()) {
entries.add(new IndexEntry(m.group(1), m.group(2), m.group(3), m.group(4),
Integer.parseInt(m.group(5))));
}
}
return entries;
}Each row of the index is a line such as F-2026-0001 05/01/2026 Example Hardware Co. 1.470,85 € 3. Notice the \h€: the first version of the expression used a normal space and didn't find a single row. The amount was formatted by Formats.euros with a non-breaking space ( ) before the symbol, which neither a literal space nor \s matches; \h (any horizontal whitespace) does. It's the same problem we discussed in 06-01.
Building the tree
/** Replaces the document's bookmarks with: cover + one entry per invoice with its children. */
public static void addBookmarks(PDDocument batch, List<IndexEntry> index) throws IOException {
PDDocumentOutline root = new PDDocumentOutline();
batch.getDocumentCatalog().setDocumentOutline(root);
batch.getDocumentCatalog().setPageMode(PageMode.USE_OUTLINES); // open with the bookmarks panel
root.addLast(item("Cover and index", fitWidth(batch.getPage(0))));
List<Integer> withoutText = PdfText.pagesWithoutText(batch);
for (int i = 0; i < index.size(); i++) {
IndexEntry e = index.get(i);
int last = i + 1 < index.size() ? index.get(i + 1).page() - 1 : batch.getNumberOfPages();
PDOutlineItem invoice = item(e.number() + " · " + e.customer() + " · " + e.total(),
fitWidth(batch.getPage(e.page() - 1)));
invoice.setBold(true);
invoice.setTextColor(BLUE);
int n = 1;
for (int p = e.page(); p <= last; p++) {
if (!withoutText.contains(p)) { // duplex blank sheets are not listed
invoice.addLast(item("Page " + n++, fitWidth(batch.getPage(p - 1))));
}
}
totalDestination(batch, e.page(), last).ifPresent(d -> invoice.addLast(item("Invoice total", d)));
invoice.closeNode(); // invoices, collapsed
root.addLast(invoice);
}
root.openNode();
}
private static PDOutlineItem item(String title, PDPageDestination destination) {
PDOutlineItem item = new PDOutlineItem();
item.setTitle(title);
item.setDestination(destination);
return item;
}Step by step:
PDDocumentOutlineis the invisible root of the tree; it's assigned to the catalog withsetDocumentOutline. If the document already had bookmarks, we replace them.PageMode.USE_OUTLINESasks the viewer to open the document with the bookmarks panel visible (page modes came up in 04-06).addLast(item)adds a child at the end. APDOutlineItemcan have children too: that's how the hierarchy is built.- The last page of each invoice is the one before the start of the next. The blank sheets for duplex printing (detected with
PdfText.pagesWithoutText, 06-01) don't get a bookmark. setBold(true)andsetTextColor(...)change the entry's style; not every viewer respects it, but Acrobat and most browsers do.closeNode()leaves the entry collapsed;openNode()on the root leaves the first level visible. Internally they update each node's/Countcounter, which the viewer uses to know what to display.- Titles accept any Unicode character (
·,€, accented letters): PDFBox stores them in the appropriate encoding.
The total's destination
/** XYZ destination that puts the "INVOICE TOTAL" line at the top of the window, without changing the zoom. */
private static Optional<PDPageDestination> totalDestination(PDDocument doc, int from, int to) throws IOException {
for (int p = to; p >= from; p--) { // the total is on the last page with text
List<Line> lines = TextLocator.lines(TextLocator.words(doc, p), 2f);
Optional<List<Word>> total = TextLocator.find(lines, "INVOICE TOTAL");
if (total.isPresent()) {
PDPage page = doc.getPage(p - 1);
PDRectangle box = Annotations.toPdf(page, total.get().get(0).box());
PDPageXYZDestination destination = new PDPageXYZDestination();
destination.setPage(page);
destination.setLeft(0);
destination.setTop(Math.round(box.getUpperRightY() + 30)); // 30 pt of breathing room above
destination.setZoom(0); // 0 = keep the current zoom
return Optional.of(destination);
}
}
return Optional.empty();
}TextLocator gives us the box of INVOICE in reading coordinates, but the destination needs PDF coordinates. The conversion is done by Annotations.toPdf, which we'll see shortly.
Reading a document's bookmarks
Reading the tree means walking through it recursively with children():
/** Prints the bookmark tree with the page (1-based) each one leads to. */
public static void printBookmarks(PDDocument document) throws IOException {
PDDocumentOutline root = document.getDocumentCatalog().getDocumentOutline();
if (root == null) {
System.out.println("(no bookmarks)");
return;
}
print(document, root, "");
}
private static void print(PDDocument document, PDOutlineNode node, String indent) throws IOException {
for (PDOutlineItem item : node.children()) {
PDPage target = item.findDestinationPage(document); // resolves direct, named and GoTo destinations
int page = target == null ? -1 : document.getPages().indexOf(target) + 1;
System.out.println(indent + item.getTitle() + " -> p. " + page);
print(document, item, indent + " ");
}
}PDOutlineNodeis the common class for the root and the items;children()returns its direct children.- A bookmark can lead to its page in three ways: a direct destination (
/Destwith the page), a named destination or aGoToaction.findDestinationPageresolves all three; there's no need to tell them apart. document.getPages().indexOf(page)gives the 0-based index of a page.
Two related facts from earlier lessons: PDFMergerUtility.appendDocument (04-04) concatenates the bookmarks of the documents it merges, and PDFTextStripper can extract the text between two bookmarks with setStartBookmark and setEndBookmark (you'll see this in exercise 1).
Named destinations
A named destination is a "name → destination" entry in a document-wide dictionary. It has two advantages: a link pointing to a name keeps working even if the pages are reordered (you only have to update the dictionary), and many viewers, including those in browsers, let you open the PDF directly at it with a URL such as batch-2026-01.pdf#F-2026-0003 (or #nameddest=F-2026-0003).
/** One named destination per invoice ("F-2026-0003"): used for links and for opening batch.pdf#F-2026-0003. */
public static void addNamedDestinations(PDDocument batch, List<IndexEntry> index) {
Map<String, PDPageDestination> names = new LinkedHashMap<>();
for (IndexEntry e : index) {
names.put(e.number(), fitWidth(batch.getPage(e.page() - 1)));
}
PDDestinationNameTreeNode tree = new PDDestinationNameTreeNode();
tree.setNames(names); // sorts the keys as the name tree requires
PDDocumentCatalog catalog = batch.getDocumentCatalog();
PDDocumentNameDictionary docNames = catalog.getNames() != null ? catalog.getNames()
: new PDDocumentNameDictionary(catalog);
docNames.setDests(tree);
catalog.setNames(docNames);
}- The catalog's
/Namesdictionary groups several name trees: destinations (/Dests), attached files (/EmbeddedFiles), JavaScript… If it already exists, we reuse it so as not to lose the other trees. - A name tree requires its keys to be sorted;
setNamessorts them for us. For five or a hundred invoices a single node is enough. - To look them up,
catalog.findNamedDestinationPage(new PDNamedDestination("F-2026-0003"))returns the destination.
Internal and external links
A link is a PDAnnotationLink annotation: a rectangle on the page and an action that runs when it's clicked.
| Action | Class | What for |
|---|---|---|
GoTo |
PDActionGoTo |
Go to a destination in the same document (direct or named) |
URI |
PDActionURI |
Open a web address |
GoToR |
PDActionRemoteGoTo |
Go to another PDF |
Launch, JavaScript |
… | Avoid them: viewers block them for security reasons |
The shared method creates the link with an invisible border:
private static PDAnnotationLink link(PDRectangle area, PDAction action) {
PDAnnotationLink link = new PDAnnotationLink();
link.setRectangle(area);
link.setAction(action);
PDBorderStyleDictionary noBorder = new PDBorderStyleDictionary();
noBorder.setWidth(0); // invisible border (the default would be 1 pt)
link.setBorderStyle(noBorder);
link.setHighlightMode(PDAnnotationLink.HIGHLIGHT_MODE_INVERT);
return link;
}- Without an explicit border, according to the specification the link has a 1 pt border, and some viewers draw a black rectangle around it. A
PDBorderStyleDictionarywith width 0 removes it. setHighlightMode(INVERT)states how the area is marked when it's clicked.setRectangleexpects PDF coordinates.
The index rows as links
/** Turns each row of the index into a (borderless) link to its invoice's named destination. */
public static void linkIndex(PDDocument batch) throws IOException {
PDPage cover = batch.getPage(0);
for (Line line : TextLocator.lines(TextLocator.words(batch, 1), 2f)) {
Matcher m = ROW.matcher(line.text());
if (!m.matches()) {
continue;
}
Word first = line.words().get(0);
Word last = line.words().get(line.words().size() - 1);
PDRectangle area = Annotations.toPdf(cover, new Rectangle2D.Float(first.x(),
first.y() - first.height() - 3, last.right() - first.x(), first.height() + 6));
PDActionGoTo goTo = new PDActionGoTo();
goTo.setDestination(new PDNamedDestination(m.group(1)));
cover.getAnnotations().add(link(area, goTo));
}
}The rectangle spans the whole row, from the first word to the last, with a 3 pt margin above and below. The action points to the invoice's named destination, not to a specific page.
Link to the website
/** Links the text "www.nebula.example" on each page to the (fictional) website. */
public static int linkWeb(PDDocument batch) throws IOException {
int created = 0;
for (int p = 1; p <= batch.getNumberOfPages(); p++) {
List<Line> lines = TextLocator.lines(TextLocator.words(batch, p), 2f);
Optional<List<Word>> web = TextLocator.find(lines, "www.nebula.example");
if (web.isPresent()) {
PDActionURI uri = new PDActionURI();
uri.setURI("https://www.nebula.example/");
PDPage page = batch.getPage(p - 1);
page.getAnnotations().add(link(Annotations.toPdf(page, web.get().get(0).box()), uri));
created++;
}
}
return created;
}getAnnotations() returns a live list: whatever you add is stored in the page's /Annots. If the page had no annotations, PDFBox creates the array.
The complete example: NavigateBatch
As with any modification of an existing document, we use PdfEditor (04-01):
Path source = Path.of("output/batch-2026-01.pdf");
Path target = Path.of("output/batch-2026-01-navigable.pdf");
PdfEditor.edit(source, target, PdfEditor.Mode.FULL, batch -> {
List<IndexEntry> index = BatchNavigation.readIndex(batch);
BatchNavigation.addBookmarks(batch, index);
BatchNavigation.addNamedDestinations(batch, index);
BatchNavigation.linkIndex(batch);
System.out.println("Web links: " + BatchNavigation.linkWeb(batch));
});
try (PDDocument batch = Loader.loadPDF(target.toFile())) {
BatchNavigation.printBookmarks(batch);
}Web links: 5
Cover and index -> p. 1
F-2026-0001 · Example Hardware Co. · 1.470,85 € -> p. 3
Page 1 -> p. 3
Invoice total -> p. 3
F-2026-0002 · Fictional Construction Ltd. · 4.193,94 € -> p. 5
Page 1 -> p. 5
Page 2 -> p. 6
Invoice total -> p. 6
...
F-2026-0004 · Example Hardware Co. · 6.590,32 € -> p. 9
Page 1 -> p. 9
Page 2 -> p. 10
Page 3 -> p. 11
Invoice total -> p. 11
...The file grows from 284,284 to 285,722 bytes: the navigation takes up very little space. When it's reloaded, the five links in the index resolve their named destinations to pages 3, 5, 7, 9 and 13, and page 12 (blank) has no bookmark. If a future batch is generated already with bookmarks, the natural place to call these methods is at the end of InvoiceBatches.create, inside the same PdfEditor.edit.
Review annotations: highlight and note
Let's go back to the supplier invoices. When InvoiceLab reads the total of an invoice, we want the person reviewing it to see what it read: a yellow highlight over the total line, like a highlighter pen, and a sticky note with a comment. Annotations are perfect for this: they're drawn on top of the content without modifying it, the user can hide or delete them, and they can be added in an incremental save, which leaves the supplier's original invoice untouched (something important if it arrives signed, as we'll see in module 7).
From reading coordinates to PDF coordinates
TextLocator positions are in reading coordinates; annotations need PDF coordinates. For an unrotated page yPdf = height − yReading would be enough, but we already know there are offset CropBoxes and rotated pages. We reuse Stamper.visibleMatrix from lesson 04-02, which converts "visible" coordinates into the page's real coordinates:
/**
* Rectangle in reading coordinates (top-left, like TextLocator) -> PDF rectangle on the page.
* Takes the CropBox and /Rotate into account thanks to Stamper.visibleMatrix (04-02).
*/
public static PDRectangle toPdf(PDPage page, Rectangle2D reading) {
Point2D[] corners = pdfCorners(page, reading);
float minX = Float.MAX_VALUE, minY = Float.MAX_VALUE, maxX = -Float.MAX_VALUE, maxY = -Float.MAX_VALUE;
for (Point2D p : corners) {
minX = Math.min(minX, (float) p.getX());
minY = Math.min(minY, (float) p.getY());
maxX = Math.max(maxX, (float) p.getX());
maxY = Math.max(maxY, (float) p.getY());
}
return new PDRectangle(minX, minY, maxX - minX, maxY - minY);
}
/** Corners in the order top-left, top-right, bottom-left, bottom-right (the /QuadPoints order). */
private static Point2D[] pdfCorners(PDPage page, Rectangle2D r) {
float visibleHeight = Stamper.visible(page).getHeight();
Matrix m = Stamper.visibleMatrix(page);
float left = (float) r.getMinX(), right = (float) r.getMaxX();
float top = visibleHeight - (float) r.getMinY(); // reading (y downwards) -> visible (y upwards)
float bottom = visibleHeight - (float) r.getMaxY();
return new Point2D[] { m.transformPoint(left, top), m.transformPoint(right, top),
m.transformPoint(left, bottom), m.transformPoint(right, bottom) };
}Two steps: flip the y axis using the visible height, and apply the matrix from 04-02 to the four corners. On a rotated page, the resulting rectangle is the bounding box of the transformed corners. These methods live in the new Annotations class; we checked them by highlighting the total on the Transport invoice (/Rotate 90): the highlight lands exactly on Total amount: 89,54 €.
The highlight
/** Highlights (like a highlighter pen) one or more text boxes on the page. */
public static PDAnnotationHighlight highlight(PDDocument document, PDPage page, List<Rectangle2D> boxes,
Color color, String comment) throws IOException {
float[] quad = new float[boxes.size() * 8];
PDRectangle envelope = null;
for (int i = 0; i < boxes.size(); i++) {
Point2D[] c = pdfCorners(page, boxes.get(i));
for (int k = 0; k < 4; k++) {
quad[i * 8 + k * 2] = (float) c[k].getX();
quad[i * 8 + k * 2 + 1] = (float) c[k].getY();
}
envelope = union(envelope, toPdf(page, boxes.get(i)));
}
PDAnnotationHighlight highlight = new PDAnnotationHighlight(); // subtype /Highlight
highlight.setRectangle(envelope);
highlight.setQuadPoints(quad);
highlight.setColor(new PDColor(color.getRGBColorComponents(null), PDDeviceRGB.INSTANCE));
highlight.setContents(comment); // text the viewer shows on mouse-over
highlight.setTitlePopup(AUTHOR); // "author" (/T)
highlight.setModifiedDate(Calendar.getInstance());
highlight.setPrinted(true); // Print flag: so it also appears on paper
highlight.constructAppearances(document); // draws /AP for viewers that don't generate it
page.getAnnotations().add(highlight);
return highlight;
}/QuadPointsare the quadrilaterals to be highlighted: 8 numbers (4 corners × 2 coordinates) per box. The corner order used by Acrobat and most viewers is top-left, top-right, bottom-left, bottom-right, relative to the text direction; that's why we calculate the corners in reading coordinates and transform them one by one./Rectmust enclose all the quadrilaterals;union(a helper method that calculates the rectangle containing two others) works it out.- Change in PDFBox 3: in 2.x it was created with
new PDAnnotationTextMarkup(PDAnnotationTextMarkup.SUB_TYPE_HIGHLIGHT). In 3.0 that constructor isprotectedand the constant doesn't exist: there's one subclass per type,PDAnnotationHighlight,PDAnnotationUnderline,PDAnnotationStrikeoutandPDAnnotationSquiggly. setContentsis the comment;setTitlePopupis the author, which viewers show as the note's heading.AUTHORis the constant"InvoiceLab".setPrinted(true)sets thePrintflag: without it, the annotation is visible on screen but doesn't print.constructAppearances(document): like the widgets in module 5, an annotation is drawn using its/APappearance. Many viewers generate one if it's missing, but not all of them, and each in its own way. PDFBox has appearance generators for the most common types; this method creates the highlight's appearance and stores it in the file: a yellow rectangle painted with a graphics state in/Multiplyblend mode, so that the text can still be seen underneath. (A curiosity we checked: thePDFRendererfrom 06-04 also generates on the fly the appearance of a highlight that lacks one, but that doesn't help other viewers.)
The boxes we highlight are those of each word in the total line. In our first attempt we used Word.box(), whose height is the getHeightDir estimate (06-02), and the highlight came out as a narrow strip covering only the lower part of the letters. That's why we added the lineBox() method to Word, which uses the font size: from 0.8 times the size above the baseline to 0.2 below it.
The note
/** Sticky note (icon) at the given corner, in reading coordinates. */
public static PDAnnotationText note(PDDocument document, PDPage page, float x, float y, String text)
throws IOException {
PDAnnotationText note = new PDAnnotationText();
note.setRectangle(toPdf(page, new Rectangle2D.Float(x, y, 20, 20)));
note.setName(PDAnnotationText.NAME_COMMENT); // icon: speech bubble
note.setContents(text);
note.setTitlePopup(AUTHOR);
note.setColor(new PDColor(new float[] { 1f, 0.85f, 0.2f }, PDDeviceRGB.INSTANCE));
note.setModifiedDate(Calendar.getInstance());
note.setPrinted(true);
note.constructAppearances(document);
page.getAnnotations().add(note);
return note;
}PDAnnotationText is the "sticky note": an icon that shows the text when clicked. setName chooses the icon (NAME_COMMENT, NAME_NOTE, NAME_KEY, NAME_HELP…).
Reviewing a supplier invoice
Path source = Path.of("output/suppliers/supplies-SF-2026-0412.pdf");
Path target = Path.of("output/suppliers-reviewed/supplies-SF-2026-0412.pdf");
Files.createDirectories(target.getParent());
PdfEditor.edit(source, target, PdfEditor.Mode.INCREMENTAL, doc -> {
PDPage page = doc.getPage(0);
List<Line> lines = TextLocator.lines(TextLocator.words(doc, 1), 2f);
// The whole total line: label + amount
Line total = lines.stream().filter(l -> l.text().startsWith("INVOICE TOTAL")).findFirst()
.orElseThrow(() -> new IOException("Total not found"));
List<Rectangle2D> boxes = new ArrayList<>();
for (Word w : total.words()) {
boxes.add(w.lineBox());
}
Annotations.highlight(doc, page, boxes, Color.YELLOW,
"Total read by InvoiceLab: 1.234,56 €. Matches order PED-2026-0098.");
Word first = total.words().get(0);
Annotations.note(doc, page, first.x() - 28, first.y() - 14,
"Pending approval by Purchasing (receipt registry 2026/0153).");
});The file grows from 1,470 to 5,057 bytes: the incremental revision appends the two annotations, their appearances and the modified page, and the original invoice stays untouched in the first 1,470 bytes. When you render it with PDFRenderer (06-04) you see the yellow highlight over INVOICE TOTAL 1.234,56 € and the note icon to its left. In a real workflow, the comment text would be built from the SupplierInvoiceReader data and the order number would come from the ERP.
Listing and removing annotations
/** All the annotations in the document, with their page (1-based). */
public static List<String> list(PDDocument document) throws IOException {
List<String> lines = new ArrayList<>();
int n = 1;
for (PDPage page : document.getPages()) {
for (PDAnnotation a : page.getAnnotations()) {
lines.add("p%d %-10s %s %s".formatted(n, a.getSubtype(), a.getRectangle(),
a.getContents() == null ? "" : "«" + a.getContents() + "»"));
}
n++;
}
return lines;
}
/** Removes the annotations that meet the condition. Returns how many were removed. */
public static int remove(PDDocument document, Predicate<PDAnnotation> condition) throws IOException {
int removed = 0;
for (PDPage page : document.getPages()) {
List<PDAnnotation> annotations = page.getAnnotations();
List<PDAnnotation> keep = new ArrayList<>();
for (PDAnnotation a : annotations) {
if (condition.test(a)) {
removed++;
} else {
keep.add(a);
}
}
if (keep.isEmpty() && !annotations.isEmpty()) {
page.getCOSObject().removeItem(COSName.ANNOTS); // setAnnotations(null) throws an exception in 3.0
} else if (keep.size() != annotations.size()) {
page.setAnnotations(keep);
}
}
return removed;
}The output of list for the reviewed invoice:
p1 Highlight [376.5,519.1,550.712,538.6] «Total read by InvoiceLab: 1.234,56 €. Matches order PED-2026-0098.»
p1 Text [352.0,521.0,370.0,539.0] «Pending approval by Purchasing (receipt registry 2026/0153).»Details of remove:
- It takes a
Predicate<PDAnnotation>, so the caller decides what to delete:a -> a instanceof PDAnnotationText(the notes),a -> "Link".equals(a.getSubtype())(the links)… - In PDFBox 3,
setAnnotations(null)throwsIllegalArgumentException("List of COSObjectables cannot be null"). To leave a page without annotations we remove the/Annotskey from its dictionary. - Watch out for widgets: form fields are
/Widgetannotations. Deleting them from the page without removing them from the/AcroFormleaves the form inconsistent. If you clean up annotations in documents that may contain forms, excludePDAnnotationWidgetor flatten first (05-04). - In lesson 04-06 we mentioned cleaning up annotations and attached files before sending a document. Attachments can be in
PDAnnotationFileAttachmentannotations (removed with this same method) or in the catalog's/EmbeddedFilestree, which is removed withcatalog.getNames().setEmbeddedFiles(null)(checked: the other trees, such as/Dests, are kept). - In 04-03, when duplicating pages, we removed the annotations because each one has a
/Pentry pointing to its page. If you need to copy them, clone their dictionary (for example, withnew PDAnnotationText(new COSDictionary(original.getCOSObject()))for a shallow copy), update/Pand the rectangle, and regenerate the appearance.
Common Mistakes and Tips
- Reading coordinates in
setRectangleor in destinations: annotations and destinations use PDF coordinates. Convert withAnnotations.toPdf. - Links with a black border: set a
PDBorderStyleDictionarywith width 0. - Highlights or notes that look different (or don't show up) depending on the viewer: the appearance is missing; call
constructAppearances(document)to store it in the file. - Annotations that don't print: the
Printflag is missing (setPrinted(true)). - Looking for
PDAnnotationTextMarkup.SUB_TYPE_HIGHLIGHTin PDFBox 3: usePDAnnotationHighlightand its siblings. setAnnotations(null): throws an exception in 3.0; remove/Annotsinstead.- Deleting widgets as if they were notes: it breaks forms.
- Bookmark tree neither opened nor closed: without
openNode/closeNode, viewers may show everything expanded or everything collapsed as they see fit. - Tip: save review annotations with an incremental save. You keep the supplier's original byte for byte, and in module 7 you'll see that it's the only way to annotate a signed PDF without invalidating its signature.
Exercises
- An invoice's text via its bookmarks. Using the navigable batch, extract the full text of invoice F-2026-0004 with
PDFTextStripper'ssetStartBookmarkandsetEndBookmark. What happens if you use the invoice's bookmark as both start and end? - Clean up InvoiceLab's marks. Write the code that removes from a reviewed invoice only the annotations whose author is InvoiceLab (those from other users must be kept) and saves the result incrementally.
- Back to the index. On the first page of each invoice in the navigable batch, add an invisible link in the top-left strip (200 × 40 pt from the corner) that leads to the cover.
Solutions
Solution 1.
try (PDDocument batch = Loader.loadPDF(new File("output/batch-2026-01-navigable.pdf"))) {
for (PDOutlineItem invoice : batch.getDocumentCatalog().getDocumentOutline().children()) {
if (invoice.getTitle().startsWith("F-2026-0004")) {
PDFTextStripper stripper = PdfText.stripper();
stripper.setStartBookmark(invoice.getFirstChild()); // "Page 1"
stripper.setEndBookmark(invoice.getLastChild()); // "Invoice total"
String text = stripper.getText(batch);
System.out.println(text.contains("(continued)") + " " + text.contains("INVOICE TOTAL"));
}
}
}It prints true true: the text runs from page 9 to page 11 and includes the continuation pages and the total. The stripper takes as its range everything from the start bookmark's page to the end bookmark's page. If you use the same bookmark as start and end (setStartBookmark(invoice) and setEndBookmark(invoice)), you get only page 9: a bookmark points to a page, not to a range. That's why we use the first and last children.
Solution 2.
Path reviewed = Path.of("output/suppliers-reviewed/supplies-SF-2026-0412.pdf");
int[] removed = new int[1];
PdfEditor.edit(reviewed, Path.of("output/suppliers-reviewed/supplies-clean.pdf"),
PdfEditor.Mode.INCREMENTAL, doc -> removed[0] = Annotations.remove(doc,
a -> a instanceof PDAnnotationMarkup m && Annotations.AUTHOR.equals(m.getTitlePopup())));
System.out.println("Removed: " + removed[0]);It removes 2 annotations (the highlight and the note) and the page is left without an /Annots key. PDAnnotationMarkup is the parent class of "comment" annotations (notes, highlights, stamps…), the ones that have an author; links and widgets aren't markup annotations, so the filter never touches them. We already used the one-element array trick in 05-04: a lambda can only modify effectively final variables. Remember that an incremental save doesn't physically delete the annotations from the file: they're still in the previous revision, recoverable with tools like the ones from 01-05. To really get rid of them, save in FULL mode.
Solution 3.
PdfEditor.edit(Path.of("output/batch-2026-01-navigable.pdf"), Path.of("output/batch-2026-01-back.pdf"),
PdfEditor.Mode.INCREMENTAL, batch -> {
PDPageFitWidthDestination cover = new PDPageFitWidthDestination();
cover.setPage(batch.getPage(0));
cover.setTop((int) batch.getPage(0).getCropBox().getUpperRightY());
for (IndexEntry e : BatchNavigation.readIndex(batch)) {
PDPage page = batch.getPage(e.page() - 1);
PDAnnotationLink back = new PDAnnotationLink();
back.setRectangle(Annotations.toPdf(page, new Rectangle2D.Float(0, 0, 200, 40)));
PDActionGoTo goTo = new PDActionGoTo();
goTo.setDestination(cover);
back.setAction(goTo);
PDBorderStyleDictionary border = new PDBorderStyleDictionary();
border.setWidth(0);
back.setBorderStyle(border);
back.setContents("Back to the batch index");
page.getAnnotations().add(back);
}
});Each first page (3, 5, 7, 9 and 13) gets a link with the PDF rectangle [0, 801.89, 200, 841.89]: the top 40 pt, which toPdf has calculated from the reading box (0, 0, 200, 40). All the links share the same destination object, which is perfectly valid. setContents on a link is optional, but it improves accessibility: screen readers announce it (we'll see this in 08-02). The link goes in an incremental save on top of the navigable batch: 285,722 → 288,762 bytes.
Conclusion
With this lesson you complete module 6. In it you've learned to make a PDF navigable: destinations of different types, hierarchical bookmarks with style and collapsed state, recursive reading of bookmarks, named destinations, and borderless internal and external links. You've also worked with review annotations: you've converted reading positions into PDF coordinates (even on rotated pages), highlighted with /QuadPoints and an appearance generated by PDFBox, added notes, and learned to list and remove annotations without breaking forms.
Throughout the module you've built the com.invoicelab.extraction package: PdfText and SupplierInvoiceReader for reading text and data, SupplierTemplate and TextLocator for working with positions, ResourceInventory and ImageLocator for images and fonts, Thumbnails and VisualComparator for seeing documents as images, and BatchNavigation and Annotations for navigating and annotating them. InvoiceLab no longer just generates and modifies PDFs: it also reads them, understands them and reviews them.
So far anyone who opens one of our invoices can copy it, modify it or impersonate Nebula Distribution. In module 7 we'll deal with security: we'll encrypt documents and control their permissions, and then learn to digitally sign invoices so that any customer can check who issued them and that nobody has altered them since.
PDF Generation and Editing with Apache PDFBox
Module 1: PDF and PDFBox Fundamentals
- The PDF Format and Apache PDFBox
- Setting Up the Project with PDFBox 3
- Anatomy of a PDF: COS Objects, Pages and Resources
- Your First PDF: Creating, Saving and Loading Documents
- Debugging Tools: PDFDebugger and the Command Line
Module 2: Generating Content
- Pages and the Coordinate System
- Writing Text with PDPageContentStream and Standard Fonts
- Embedded TrueType Fonts and Unicode
- Text Layout: Measuring, Aligning and Wrapping Lines
- Vector Graphics: Lines, Shapes and Colours
- Inserting Images
Module 3: Business Documents
- Building Tables from Scratch
- Multi-Page Documents: Pagination, Headers and Footers
- Barcodes and QR Codes
- Designing a Reusable Document Generator
- Project: the Complete Invoice
Module 4: Editing Existing PDFs
- Load, Modify and Save: Full and Incremental Saves
- Adding Content to Existing Pages: Stamps and Watermarks
- Page Manipulation: Inserting, Removing, Rotating and Reordering
- Merging and Splitting Documents
- Overlays, Layers and Optional Content
- Document Metadata: Info and XMP
Module 5: AcroForm Forms
- Introduction to AcroForm Forms
- Reading and Filling In Forms
- Creating Forms Programmatically
- Form Appearances and Flattening
Module 6: Extraction and Analysis
- Extracting Text with PDFTextStripper
- Area-Based Extraction and Text Positions
- Extracting Images and Resources
- Rendering Pages to Images
- Bookmarks, Links and Annotations
Module 7: Security and Digital Signatures
- Encryption and Permissions
- Digital Signatures: Concepts and PDF Structure
- Signing Documents with PDFBox and Bouncy Castle
- Verifying Signatures and Visible Signatures
