Add Bookmarks to PDF in Java

This article demonstrates how to add bookmarks and child bookmarks to a PDF file using Spire.PDF for Java.

import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.actions.PdfGoToAction;
import com.spire.pdf.bookmarks.PdfBookmark;
import com.spire.pdf.bookmarks.PdfTextStyle;
import com.spire.pdf.general.PdfDestination;
import com.spire.pdf.graphics.PdfRGBColor;

import java.awt.*;
import java.awt.geom.Point2D;

public class AddBookmark {
    public static void main(String[] args) {
        //Create a PdfDocument instance
        PdfDocument pdf = new PdfDocument();
        //Load a PDF file
        pdf.loadFromFile("Test.pdf");

        //Loop through the pages in the PDF file
        for(int i = 0; i< pdf.getPages().getCount();i++) {
            PdfPageBase page = pdf.getPages().get(i);
            //Add bookmark
            PdfBookmark bookmark = pdf.getBookmarks().add(String.format("Bookmark-%s", I + 1));
            //Set destination page and location
            PdfDestination destination = new PdfDestination(page, new Point2D.Float(0, 0));
            bookmark.setAction(new PdfGoToAction(destination));
            //Set text color
            bookmark.setColor(new PdfRGBColor(new Color(139, 69, 19)));
            //Set text style
            bookmark.setDisplayStyle(PdfTextStyle.Bold);

            //Add child bookmark
            PdfBookmark childBookmark = bookmark.add(String.format("ChildBookmark-%s", i + 1));
            //Set destination page and location
            PdfDestination childDestination = new PdfDestination(page, new Point2D.Float(0, 100));
            childBookmark.setAction(new PdfGoToAction(childDestination));
            //Set text color
            childBookmark.setColor(new PdfRGBColor(new Color(255, 127, 80)));
            //Set text style
            childBookmark.setDisplayStyle(PdfTextStyle.Italic);
        }

        //Save the result file
        pdf.saveToFile("AddBookmarks.pdf");
    }
}

Output:

Add Bookmarks to PDF in Java