PDF文档中的书签允许用户通过单击指定的书签标题跳转到文档的相应部分。使用Spire.PDF,程序员可以将书签添加到PDF文档或从现有PDF文档中提取书签。
关联产品
代码段:
Step 1:定义自定义函数以获取所有总书签的标题以及子书签,并在控制台上打印结果。
static void GetBookmarkTitle(PdfBookmarkCollection bookmarks) { if (bookmarks.Count > 0) { foreach (PdfBookmark parentBookmark in bookmarks) { Console.WriteLine(parentBookmark.Title); foreach (PdfBookmark childBookmark in parentBookmark) { Console.WriteLine(childBookmark.Title); GetBookmarkTitle(childBookmark); } } } }
Step 2:初始化Pdf Document类的实例,并加载具有多级书签的示例PDF文档。
PdfDocument doc = new PdfDocument(); doc.LoadFromFile(@"C:\Users\Administrator\Desktop\Bookmark.pdf");
Step 3:调用GetBookmarkTitle方法获取文档中的所有书签。
PdfBookmarkCollection bookmarks = doc.Bookmarks; GetBookmarkTitle(bookmarks);
完整代码:
[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); foreach (PdfBookmark childBookmark in parentBookmark) { Console.WriteLine(childBookmark.Title); GetBookmarkTitle(childBookmark); } } } }
[VB.NET]
Private Shared Sub Main(args As String()) Dim doc As 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(bookmarks As PdfBookmarkCollection) If bookmarks.Count > 0 Then For Each parentBookmark As PdfBookmark In bookmarks Console.WriteLine(parentBookmark.Title) For Each childBookmark As PdfBookmark In parentBookmark Console.WriteLine(childBookmark.Title) GetBookmarkTitle(childBookmark) Next Next End If End Sub