简体   繁体   English

合并PDF并在Java中使用iText添加书签

[英]Merge pdfs and add bookmark with iText in java

How do I add bookmarks to an existing PDFs by using iText? 如何使用iText将书签添加到现有的PDF?

I am merging multiple PDFs together into one PDF and I need to build bookmarks for the final PDF. 我正在将多个PDF合并为一个PDF,并且需要为最终PDF构建书签。 For example, I have three PDFs: doc1.pdf, doc2.pdf and doc3.pdf, doc1 and doc2 belong to Group1, doc3 belongs to Group2. 例如,我有三个PDF:doc1.pdf,doc2.pdf和doc3.pdf,doc1和doc2属于Group1,doc3属于Group2。 I need to merge them and have to build nested bookmarks for the resulting PDFs like so: 我需要合并它们,并且必须为生成的PDF构建嵌套书签,如下所示:

Group1 
   doc1  
   doc2  
Group2 
   doc3 

etc. 等等

I've made a MergeWithOutlines example that concatenates three existing PDFs using PdfCopy (I assume that you already know that part). 我已经制作了一个MergeWithOutlines示例,该示例使用PdfCopy连接了三个现有的PDF(我假设您已经知道那部分)。

While doing so, I create an outlines object like this: 这样做时,我创建了一个outlines对象,如下所示:

ArrayList<HashMap<String, Object>> outlines = new ArrayList<HashMap<String, Object>>();

and I add elements to this outlines object: 我将元素添加到此outlines对象:

HashMap<String, Object> helloworld = new HashMap<String, Object>();
helloworld.put("Title", "Hello World");
helloworld.put("Action", "GoTo");
helloworld.put("Page", String.format("%d Fit", page));
outlines.add(helloworld);

When I want some hierachy, I introduce kids : 当我想要层次结构时,我向kids介绍:

ArrayList<HashMap<String, Object>> kids = new ArrayList<HashMap<String, Object>>();
HashMap<String, Object> link1 = new HashMap<String, Object>();
link1.put("Title", "link1");
link1.put("Action", "GoTo");
link1.put("Page", String.format("%d Fit", page));
kids.add(link1);
helloworld.put("Kids", kids);

If you want an entry without a link, remove the lines that put an Action and a Page . 如果您想要一个没有链接的条目,请删除放置ActionPage

Once you're finished, add the outlines to the copy object: 完成后,将轮廓添加到复制对象:

copy.setOutlines(outlines);

Look at the resulting PDF and you'll see the outlines in the bookmarks panel. 查看生成的PDF ,您将在书签面板中看到轮廓。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM