且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用iText将命名目标添加到现有PDF文档

更新时间:2022-06-24 08:28:43

我之前一直对我的项目有同样的需求。必须使用acrobat.jar查看器显示和导航pdf文档。要导航我需要pdf中的指定目的地。我在网上寻找可能的解决方案,但对我来说并不幸运。然后我想到了这个想法。

I 've been in the same need for my project previously. Had to display and navigate pdf document with acrobat.jar viewer. To navigate i needed the named destinations in the pdf. I have looked around the web for a possible solution, but no fortunate for me. Then I this idea strikes my mind.

我尝试用itext重新创建现有的pdf,浏览每个页面并为每个页面添加localdestinations,我得到了我想要的东西。下面是我的代码片段

I tried to recreate the existing pdf with itext, navigating through each page and adding localdestinations to each page and i got what I wanted. below is the snip of my code

OutputStream outputStream = new FileOutputStream(new File(filename));
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, outputStream);
document.open();
PdfContentByte cb = writer.getDirectContent();
PdfOutline pol = cb.getRootOutline();
PdfOutline oline1 = null;
InputStream in1 = new FileInputStream(new File(inf1));
PdfReader reader = new PdfReader(in1);
for (int i = 1; i <= reader.getNumberOfPages(); i++)
{
    document.newPage();
    document.setMargins(0.0F, 18.0F, 18.0F, 18.0F);
    PdfImportedPage page = writer.getImportedPage(reader, i);
    document.add(new Chunk(new Integer(i).toString()).setLocalDestination(new Integer(i).toString()));
    System.out.println(i);
    cb.addTemplate(page, 0.0F, 0.0F);
}
outputStream.flush();
document.close();
outputStream.close();

以为它会对你有帮助。