How to create hierarchical bookmarks?

How can I create a hierarchical bookmark structure in PDF using iText?

25th October 2015

I have data in ArrayList like below :


ArrayList tree = new ArrayList();
I am able to display above data in tree structure like below :


How can I create a hierarchical bookmark structure (as shown above) in PDF using iText?


Posted on StackOverflow on Feb 26, 2015 by Butani Vijay

In PDF terminology, bookmarks are referred to as outlines. Please take a look at the CreateOutlineTree example to find out how to create an outline tree as shown in this PDF:

Outline tree shown in the bookmarks panel

Outline tree shown in the bookmarks panel

We start with the root of the tree:

PdfOutline root = writer.getRootOutline();

Then we add a branch:

PdfOutline movieBookmark = new PdfOutline(root,
    new PdfDestination(
        PdfDestination.FITH, writer.getVerticalPosition(true)),
        title, true);

To this branch, we add a leaf:

PdfOutline link = new PdfOutline(movieBookmark,
    new PdfAction(String.format(RESOURCE, movie.getImdb())),
    "link to IMDB");

And so on.

The key is to use PdfOutline and to pass the parent outline as a parameter when constructing a child outline.

Can I do this in an existing pdf? I mean without creating new PDF, I want to add bookmarks to an existing pdf.

There's also an example called BookmarkedTimeTable where we create the outline tree in a completely different way:

ArrayList> outlines =
    new ArrayList>();
HashMap map = new HashMap();

In this case, map is the root object to which we can add branches and leaves. To create a hierarchy, you just need to add kids like this:

First level:

HashMap calendar = new HashMap();
calendar.put("Title", "Calendar");

Second level:

HashMap day = new HashMap();
day.put("Title", "Monday");
ArrayList> days =
    new ArrayList>();
calendar.put("Kids", days);

Once we're finished, we add the outline tree to the PdfStamper like this:


Note that PdfStamper is the class we need when we manipulate an existing PDF (as opposed to PdfWriter which is to be used when we create a PDF from scratch).

I am unable to add third level using this. I mean suppose in your example I want to add child to the date, and have a branch like Calendar -> 2014-03-02 -> Monday

Third level:

HashMap hour = new HashMap();
hour.put("Title", "10 AM");
ArrayList> hours = new ArrayList>();
day.put("Kids", hours);

And so on...


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