PDFBox - how to create table of contents

北战南征 提交于 2020-01-03 16:57:28

问题


Is there a way to create a table of contents using Java PDFBox library?

The table of contents should be clickable (jump to the right page)

Thanks.


回答1:


There's no simple method for doing this, but here's an approach. I haven't figured out how to attach links directly to text, so my approach means you have to draw the annotations as rectangles and the text separately. It's a bit rough around the edges, but it works.

// there are other types of destinations, choose what is appropriate
PDPageXYZDestination dest = new PDPageXYZDestination();
// the indexing is odd here.  if you are doing this on the first page of the pdf
// that page is -1, the next is 0, the next is 1 and so on.  odd.
dest.setPageNumber(3);
dest.setLeft(0);
dest.setTop(0); // link to top of page, this is the XYZ part

PDActionGoTo action = new PDActionGoTo();
action.setDestination(dest);

PDAnnotationLink link = new PDAnnotationLink();
link.setAction(action);
link.setDestination(dest);

PDRectangle rect = new PDRectangle();
// just making these x,y coords up for sample
rect.setLowerLeftX(72);
rect.setLowerLeftY(600);
rect.setUpperRightX(144);
rect.setUpperRightY(620);

PDPage page = // however you are getting your table of contents page, eg new PDPage() or doc.getDocumentCatalog().getAllPages().get(0)

page.getAnnotations().add(link);

PDPageContentStream stream = new PDPageContentStream(doc, page, true, true);
stream.beginText();
stream.setTextTranslation(85, 600); // made these up, have to test to see if padding is correct
stream.drawString("Page 1");
stream.endText();
stream.close();

Phew! That's a lotta code. That should get you on your way. You can make the rectangle the same color as your document background if you want it to look like they are just clicking a link, but that requires more experimentation.



来源:https://stackoverflow.com/questions/23553094/pdfbox-how-to-create-table-of-contents

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!