How do I add bookmarks to an existing PDFs by using iText?
I am merging multiple PDFs together into one PDF and I need to build bookmarks for the final PDF. For example, I have three PDFs: doc1.pdf, doc2.pdf and doc3.pdf, doc1 and doc2 belong to Group1, doc3 belongs to Group2. I need to merge them and have to build nested bookmarks for the resulting PDFs like so:
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).
While doing so, I create an outlines
object like this:
ArrayList<HashMap<String, Object>> outlines = new ArrayList<HashMap<String, Object>>();
and I add elements to this outlines
object:
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
:
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
.
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.