PDFBox - 如何创建目录

时间:2014-05-08 21:42:59

标签: java pdfbox

有没有办法使用Java PDFBox库创建目录?

目录应该是可点击的(跳转到右侧页面)

感谢。

1 个答案:

答案 0 :(得分:0)

没有简单的方法可以做到这一点,但这是一种方法。我还没弄明白如何将链接直接附加到文本,因此我的方法意味着您必须将注释分别绘制为矩形和文本。它的边缘有点粗糙,但它有效。

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

唷!这是一个很好的代码。这应该会让你在路上。如果您希望矩形看起来只是单击链接,则可以使矩形与文档背景颜色相同,但这需要更多实验。