Expand/Collapse bookmarks in PDF files in C#

PDF bookmarks are very useful to help us locate and link to points that we want to go, especially when the PDF has huge pages. Sometimes we may need to collapse and expand the bookmarks to make them clear. With the help of Spire.PDF for .NET, developers can easily add bookmarks to the PDF file, get the bookmarks in the PDF and even remove the bookmarks we want. This article will show you how to expand and collapse the bookmarks in an existing PDF file in C#.

Please note that the feature of expand and collapse bookmarks only supports in Spire.PDF for .NET V3.2.31 or above. Here comes to the codes:

Step 1: Create a new PDF document and load from the file.

PdfDocument doc = new PdfDocument();
doc.LoadFromFile("Bookmark.pdf");

Step 2: Set BookMarkExpandOrCollapse as false to collapse the bookmarks.

doc.ViewerPreferences.BookMarkExpandOrCollapse = false; //expand is true

Step 3: Save the document to file.

doc.SaveToFile("result.pdf");

Effective screenshot of the collapse the bookmarks in PDF:

Expand/Collapse bookmarks in PDF files in C#

The screenshot of Expand the bookmarks in PDF:

Expand/Collapse bookmarks in PDF files in C#

Full codes:

using Spire.Pdf;

namespace ExpandAndCollapsePDFBookmarks
{
    class Program
    {
        static void Main(string[] args)
        {
            PdfDocument doc = new PdfDocument();
            doc.LoadFromFile("Bookmark.pdf");
            doc.ViewerPreferences.BookMarkExpandOrCollapse = false;//expand is true
            doc.SaveToFile("result.pdf");
        }
    }
}