Get PDF Bookmarks in C#, VB.NET

Bookmarks in a PDF document allow users to jump to corresponding sections of the document by clicking a specified bookmark title. Using Spire.PDF, programmers can add bookmarks to PDF document or extract bookmarks from an existing PDF document. This article presents how to get PDF bookmarks using Spire.PDF in C# and VB.NET.

Code Snippet:

Step 1: Define a custom function to get the titles of all parent bookmarks as well as the child bookmarks and print the results on the console.

static void GetBookmarkTitle(PdfBookmarkCollection bookmarks)
{
    if (bookmarks.Count > 0)
    {
        foreach (PdfBookmark parentBookmark in bookmarks)
        {
            Console.WriteLine(parentBookmark.Title);
            GetBookmarkTitle(parentBookmark);
        }               
    }
}

Step 2: Initialize an instance of PdfDocument class and load a sample PDF document that has multi-level bookmarks.

PdfDocument doc = new PdfDocument();
doc.LoadFromFile(@"C:\Users\Administrator\Desktop\Bookmark.pdf");

Step 3: Invoke GetBookmarkTitle method to get all bookmarks in the document.

PdfBookmarkCollection bookmarks = doc.Bookmarks;
GetBookmarkTitle(bookmarks);

Get PDF Bookmarks in C#, VB.NET

Full Code:

[C#]
static void Main(string[] args)
{
    PdfDocument doc = new PdfDocument();
    doc.LoadFromFile(@"C:\Users\Administrator\Desktop\Bookmark.pdf");
    PdfBookmarkCollection bookmarks = doc.Bookmarks;
    GetBookmarkTitle(bookmarks);
    Console.ReadLine();
}
static void GetBookmarkTitle(PdfBookmarkCollection bookmarks)
{
    if (bookmarks.Count > 0)
    {
        foreach (PdfBookmark parentBookmark in bookmarks)
        {
            Console.WriteLine(parentBookmark.Title);
            GetBookmarkTitle(parentBookmark);
        }               
    }
}
[VB.NET]
Private Shared Sub Main(ByVal args As String())
    Dim doc As PdfDocument = New PdfDocument()
    doc.LoadFromFile("C:\Users\Administrator\Desktop\Bookmark.pdf")
    Dim bookmarks As PdfBookmarkCollection = doc.Bookmarks
    GetBookmarkTitle(bookmarks)
    Console.ReadLine()
End Sub

Private Shared Sub GetBookmarkTitle(ByVal bookmarks As PdfBookmarkCollection)
    If bookmarks.Count > 0 Then
        For Each parentBookmark As PdfBookmark In bookmarks
            Console.WriteLine(parentBookmark.Title)
            GetBookmarkTitle(parentBookmark)
        Next
    End If
End Sub