- Home

PDF

# PDFBox - PDF Bookmarks

- Accessing Bookmarks
- Creating Bookmarks

## Accessing Bookmarks

See package:org.pdfbox.pdmodel.interactive.documentnavigation.outline
See example:PrintBookmarks

A PDF can contain an outline of a document and jump to pages within a PDF document. An outline is a hierarchical tree structure of nodes that point to pages.

To access the root of the outline you go through the PDDocumentOutline

          PDDocument doc = PDDocument.load( ... );
          PDDocumentOutline root = doc.getDocumentCatalog().getDocumentOutline();

Now you can traverse the tree using the getFirstChild() and getNextSibling() functions.

          PDOutlineItem item = root.getFirstChild();
          while( item != null )
          {
              System.out.println( "Item:" + item.getTitle() );
              PDOutlineItem child = item.getFirstChild();
              while( child != null )
              {
                  System.out.println( "    Child:" + child.getTitle() );
                  child = child.getNextSibling();
              }
              item = item.getNextSibling();
          }

## Creating Bookmarks

See example:CreateBookmarks

Creating bookmarks is just as easy. You first need to create the PDDocumentOutline and then add some PDOutlineItem objects to it.

          //first create the document outline and add it to the page
          PDDocumentOutline outline = new PDDocumentOutline();
          doc.getDocumentCatalog().setDocumentOutline( outline );

          //Create a root element to show in the tree
          PDOutlineItem root = new PDOutlineItem();
          root.setTitle( "Root of Document" );
          outline.appendChild( root)

          //Get the page to refer to
          PDPage firstPage = (PDPage)doc.getAllPages().get( 0 );

          //Create the outline item to refer to the first page.
          PDOutlineItem firstPageItem = new PDOutlineItem();
          firstPageItem.setTitle( "First Page of document" );
          firstPageItem.setDestination( firstPage );
          root.appendChild( firstPageItem );

Note
By default all nodes in the outline tree are closed. You need to call openNode() if you want the node to be open when the document is opened.