抱歉,我是PDF框的新手,正在寻找一种解决方案,该方案如何使用书签名称获取特定的pdf页面?像下面的代码片段一样,我试图循环所有页面,但卡住了将书签与我需要的页面链接。有人可以帮忙吗?
import java.awt.print.PrinterException; import java.io.File; import java.io.IOException; import org.apache.pdfbox.cos.COSObject; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDPage; import org.apache.pdfbox.pdmodel.encryption.InvalidPasswordException; import org.apache.pdfbox.pdmodel.interactive.documentnavigation.destination.PDPageFitWidthDestination; import org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDDocumentOutline; import org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDOutlineItem; import org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.PDOutlineNode; public class PDFLoader { public static void main(String[] args) throws InvalidPasswordException, IOException, PrinterException { File file = new File("d:\\pdf\\sample.pdf"); PDDocument document = PDDocument.load(file); PDPage page01 = document.getDocumentCatalog().getPages().get(0); PDPage page02 = document.getDocumentCatalog().getPages().get(1); PDDocumentOutline outline = document.getDocumentCatalog().getDocumentOutline(); printBookmark(outline, ""); PDDocument doc = new PDDocument(); doc.addPage(page01); doc.addPage(page02); doc.save("d:\\pdf\\newSample.pdf"); doc.close(); } public static PDPage getBookmark(PDOutlineNode bookmark, String indentation) throws IOException { PDOutlineItem current = bookmark.getFirstChild(); while (current != null) { System.out.println(indentation + current.getTitle()); if (current.getAction() instanceof PDActionGoTo) { PDActionGoTo gta = (PDActionGoTo) current.getAction(); if (gta.getDestination() instanceof PDPageDestination) { if(current.getTitle().equals("MyBookMark")){ PDPageDestination pd = (PDPageDestination) current.getDestination(); System.out.println("Destination page: " + pd.retrievePageNumber()); return pd.getPage(); } } } getBookmark(current, indentation + " "); current = current.getNextSibling(); } return null; } //Stack Trace Exception in thread "main" java.lang.NullPointerException at com.mypackage.PDFLoader.getBookmark(PDFLoader.java:67) at com.mypackage.PDFLoader.main(PDFLoader.java:40)
事实证明,在PDF中,页面目标不在书签的目标条目中,而是在书签的操作项中(是的,PDF使您可以通过两种方式来执行同一操作)。将此添加到您的代码:
if (current.getDestination() instanceof PDPageDestination) { PDPageDestination pd = (PDPageDestination) current.getDestination(); System.out.println("Destination page: " + (pd.retrievePageNumber() + 1)); return pd.getPage(); } if (current.getAction() instanceof PDActionGoTo) { PDActionGoTo gta = (PDActionGoTo) current.getAction(); if (gta.getDestination() instanceof PDPageDestination) { PDPageDestination pd = (PDPageDestination) gta.getDestination(); System.out.println("Destination page: " + (pd.retrievePageNumber() + 1)); return pd.getPage(); } }