Skip to content

Instantly share code, notes, and snippets.

@aspose-com-kb
Last active June 8, 2023 13:37
Show Gist options
  • Save aspose-com-kb/f7fc12ee7c3fda239dc51063473338be to your computer and use it in GitHub Desktop.
Save aspose-com-kb/f7fc12ee7c3fda239dc51063473338be to your computer and use it in GitHub Desktop.
This code can be used to read bookmarks in PDF using C#. For detailed guide please check https://kb.aspose.com/pdf/net/how-to-read-bookmarks-in-pdf-using-c-sharp/
using System;
// Add reference to Aspose.PDF for .NET API
// Use following namespace to read bookmarks in a PDF File
using Aspose.Pdf;
namespace ReadBookmarksInPDF
{
class Program
{
static void Main(string[] args)
{
// Set license before reading bookmarks in PDF file
Aspose.Pdf.License AsposePDFLicense = new Aspose.Pdf.License();
AsposePDFLicense.SetLicense(@"c:\asposelicense\license.lic");
// Open PDF from which you want to extract bookmarks
Document pdfwithbookmarks = new Document("ReadBookmarks.pdf");
// Retrieve PDF bookmarks by iterating through them
foreach (OutlineItemCollection bookmark in pdfwithbookmarks.Outlines)
{
Console.WriteLine(bookmark.Title);
Console.WriteLine(bookmark.Italic);
Console.WriteLine(bookmark.Bold);
Console.WriteLine(bookmark.Color);
// Check if bookmark has any children
if (bookmark.Count > 0)
{
Console.WriteLine("Reading Child bookmarks...");
// If children are present then loop through them as well to extract bookmarks
foreach (OutlineItemCollection childBookmark in bookmark)
{
Console.WriteLine(childBookmark.Title);
Console.WriteLine(childBookmark.Italic);
Console.WriteLine(childBookmark.Bold);
Console.WriteLine(childBookmark.Color);
}
}
}
Console.WriteLine("Program has finished reading PDF bookmarks in provided file.");
}
}
}
@AlexMelw
Copy link

AlexMelw commented Jun 8, 2023

foreach (OutlineItemCollection childBookmark in bookmark)
The fact that bookmark is an IEnumerable is a bit counterintuitive, even if that's the way it's internally stored in PDF.
I would prefer having a dedicated .Children property for accessing child bookmarks, regardless of whether it is a computed property or not.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment