Java expand and collapse the bookmarks for PDF

This article will demonstrate how to expand or collapse the bookmarks when viewing the PDF files.

Expand all bookmarks on PDF

import com.spire.pdf.PdfDocument;

public class expandBookmarks {
    public static void main(String[] args) {

        PdfDocument doc = new PdfDocument();
        doc.loadFromFile("Sample.pdf");

        //Set true to expand all bookmarks; set false to collapse all bookmarks
        doc.getViewerPreferences().setBookMarkExpandOrCollapse(true);

        doc.saveToFile("output/expandAllBookmarks_out.pdf");
        doc.close();
    }
}

Output:

Java expand and collapse the bookmarks for PDF

Expand specific bookmarks on PDF

import com.spire.pdf.PdfDocument;
import com.spire.pdf.bookmarks.*;

public class expandSpecificBookmarks {
    public static void main(String[] args) {

        PdfDocument doc = new PdfDocument();
        doc.loadFromFile("Sample.pdf");

        //Set BookMarkExpandOrCollapse as "true" for the first bookmarks
        doc.getBookmarks().get(0).setExpandBookmark(true);

        //Set BookMarkExpandOrCollapse as "false" for the first level of the second bookmarks
        PdfBookmarkCollection pdfBookmark = doc.getBookmarks().get(1);
        pdfBookmark.get(0).setExpandBookmark(false);

        doc.saveToFile("output/expandSpecificBookmarks_out.pdf");
        doc.close();
    }
}

Only expand the first bookmarks

Java expand and collapse the bookmarks for PDF