How to merge PDFs and add bookmarks?

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 this:

 

Group1
    doc1
    doc2
Group2
    doc3

Posted on StackOverflow on May 15, 2014 by user3642526

I've made a MergeWithOutlines example that concatenates three existing PDFs in iText 7.

While doing so, I use the PdfOutline class like this:

PdfOutline helloWorld = rootOutline.addOutline("Hello World");
helloWorld.addDestination(PdfExplicitDestination.createFit(pdfDoc.getPage(page)));
page += srcDoc1.getNumberOfPages();
PdfOutline link1 = helloWorld.addOutline("link1");
link1.addDestination(PdfExplicitDestination.createFit(pdfDoc.getPage(page)));
page += srcDoc1.getNumberOfPages();
PdfOutline link2 = rootOutline.addOutline("Link 2");
link2.addDestination(PdfExplicitDestination.createFit(pdfDoc.getPage(page)));

Where rootOutline is the following:

PdfOutline rootOutline = pdfDoc.getOutlines(false);

If you want an entry without a link, remove the line that add the destination. As you see, it’s much more easier to achieve your goal with iText 7 then iText 5.

Click this link if you want to see how to answer this question in iText 5.



Ready to use iText?

Try our iText 7 Library and add-ons FREE for 30 days. Test your proof of concept, and see if our solution is right for you.

Get my FREE trial
Contact

Still have questions? 

We're happy to answer your questions. Reach out to us and we'll get back to you shortly.

Contact us
Stay updated

Join 11,000+ subscribers and become an iText PDF expert by staying up to date with our new products, updates, tips, technical solutions and happenings.

Subscribe Now