如何使用Apache PdfBox在PDF文件中获取书签页码?

时间:2019-06-24 12:43:13

标签: java pdfbox

我已经获得了书签,但是我需要知道这些书签在PDF中的位置。 (书签1 =第1页,...,书签54 =第72页,等等。)。有人可以帮助我吗?感谢您的支持。

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();
  }

1 个答案:

答案 0 :(得分:0)

PrintBookmarks.java示例中摘录的源代码下载:

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));
        }
    }
}