helloraga98
helloraga98

Reputation: 13

How can I get bookmarks page number in a PDF file with Apache PdfBox?

I've already obtained bookmarks but I need to know where these bookmarks are located in the PDF. (Bookmark 1 = page 1,..., Bookmark 54= page 72 etc..). Anyone can help me? Thanks for the support.

PDDocument doc = PDDocument.load( ... );
PDDocumentOutline root = doc.getDocumentCatalog().getDocumentOutline();
PDOutlineItem item = root.getFirstChild();
  while( item != null )
  {
      System.out.println( "Item:" + item.getTitle() );
      item = item.getNextSibling();
  }

Upvotes: 1

Views: 765

Answers (1)

Tilman Hausherr
Tilman Hausherr

Reputation: 18861

Excerpt from the PrintBookmarks.java example from the source code download:

if (item.getDestination() instanceof PDPageDestination)
{
    PDPageDestination pd = (PDPageDestination) item.getDestination();
    System.out.println("Destination page: " + (pd.retrievePageNumber() + 1));
}
else if (item.getDestination() instanceof PDNamedDestination)
{
    PDPageDestination pd = document.getDocumentCatalog().findNamedDestinationPage((PDNamedDestination) item.getDestination());
    if (pd != null)
    {
        System.out.println("Destination page: " + (pd.retrievePageNumber() + 1));
    }
}

if (item.getAction() instanceof PDActionGoTo)
{
    PDActionGoTo gta = (PDActionGoTo) item.getAction();
    if (gta.getDestination() instanceof PDPageDestination)
    {
        PDPageDestination pd = (PDPageDestination) gta.getDestination();
        System.out.println("Destination page: " + (pd.retrievePageNumber() + 1));
    }
    else if (gta.getDestination() instanceof PDNamedDestination)
    {
        PDPageDestination pd = document.getDocumentCatalog().findNamedDestinationPage((PDNamedDestination) gta.getDestination());
        if (pd != null)
        {
            System.out.println("Destination page: " + (pd.retrievePageNumber() + 1));
        }
    }
}

Upvotes: 1

Related Questions