Add and Delete PDF Bookmarks in Java
Contents
[
Hide
]
Use the document outline collection to manage bookmarks programmatically.
Add a top-level bookmark
Use this example when the document should include a single top-level outline entry.
- Open the source PDF Document.
- Create an OutlineItemCollection and configure its title, style, and action.
- Add the bookmark to the document outlines and save the file.
public static void addBookmark(Path inputFile, Path outputFile) {
try (Document document = new Document(inputFile.toString())) {
OutlineItemCollection pdfOutline = new OutlineItemCollection(document.getOutlines());
pdfOutline.setTitle("Test Outline");
pdfOutline.setItalic(true);
pdfOutline.setBold(true);
pdfOutline.setAction(new GoToAction(document.getPages().get_Item(1)));
document.getOutlines().add(pdfOutline);
document.save(outputFile.toString());
}
}
Add a child bookmark
This example creates a parent bookmark and nests a child bookmark under it.
- Open the source PDF Document.
- Create parent and child OutlineItemCollection objects.
- Add the child to the parent, add the parent to the outline collection, and save the document.
public static void addChildBookmark(Path inputFile, Path outputFile) {
try (Document document = new Document(inputFile.toString())) {
OutlineItemCollection pdfOutline = new OutlineItemCollection(document.getOutlines());
pdfOutline.setTitle("Parent Outline");
pdfOutline.setItalic(true);
pdfOutline.setBold(true);
OutlineItemCollection pdfChildOutline = new OutlineItemCollection(document.getOutlines());
pdfChildOutline.setTitle("Child Outline");
pdfChildOutline.setItalic(true);
pdfChildOutline.setBold(true);
pdfOutline.add(pdfChildOutline);
document.getOutlines().add(pdfOutline);
document.save(outputFile.toString());
}
}
Delete all bookmarks
Use this approach when the entire outline collection should be removed from the document.
- Open the source PDF Document.
- Delete the full outlines collection.
- Save the cleaned output file.
public static void deleteBookmarks(Path inputFile, Path outputFile) {
try (Document document = new Document(inputFile.toString())) {
document.getOutlines().delete();
document.save(outputFile.toString());
}
}
Delete a specific bookmark
Use this example when one named bookmark should be removed without clearing the whole outline tree.
- Open the source PDF Document.
- Delete the bookmark by title from the outlines collection.
- Save the updated document.
public static void deleteBookmark(Path inputFile, Path outputFile) {
try (Document document = new Document(inputFile.toString())) {
document.getOutlines().delete("Child Outline");
document.save(outputFile.toString());
}
}