PDF Toolkit

Samples

Get and Set PDF Bookamrks

This Code sample requires the PDF Toolkit and is found in: C:\Aquaforest\PDF Toolkit\samples\PDFBookmarks

    
using Aquaforest.PDF;
using System;
    
namespace PDFBookmarks
{
    internal class PDFBookmarks
    {
        private static void Main(string[] args)
        {
            //Assign Licence Key
            PDFToolkit.LicenseKey = string.Empty;
            string input = @"..\documents\source\cookbook.pdf";
            string output = @"..\documents\output\bookmark.pdf";
    
            //Insert bookmark
            PDFBookmarkItem bookmark1 = new PDFBookmarkItem(1, "Page  1");
            PDFBookmarkItem bookmark2 = new PDFBookmarkItem(4, "Page 2");
            PDFBookmarkItem bookmark3 = new PDFBookmarkItem(14, "Page 14");
            PDFBookmarkItem bookmark4 = new PDFBookmarkItem(4, "Page 2");
            PDFBookmarkItem bookmark5 = new PDFBookmarkItem(14, "Page 14 second");
            PDFBookmark bookmark = new PDFBookmark();
            bookmark.BookmarkHeader = "Exampl";
            bookmark1.BookmarkItems.Add(bookmark4);
            bookmark1.BookmarkItems.Add(bookmark5);
            bookmark2.BookmarkItems.Add(bookmark4);
            bookmark2.BookmarkItems.Add(bookmark5);
            bookmark.BookmarkItems.Add(bookmark1);
            bookmark.BookmarkItems.Add(bookmark2);
            bookmark.BookmarkItems.Add(bookmark3);
            AddBookmarks(input, output, bookmark);
    
            //retrive bookmarks
            var bookmarks = GetBookmarks(input);
            if (bookmarks.BookmarkItems.Count > 0)
            {
                foreach (var book in bookmarks.BookmarkItems)
                {
                    Console.WriteLine("Tile = " + book.BookmarkTitle + " , page number = " + book.BookmarkTitle);
                    if (book.BookmarkItems.Count > 0)
                    {
                        // you can do some thing recursive if three is a bookmark tree
                    }
                }
            }
        }
    
        public static void AddBookmarks(string input, string output, PDFBookmark bookmark)
        {
            try
            {
                PDFDocument document = new PDFDocument(input);
    
                document.AddBookmarks(bookmark);
                document.Save(output);
            }
            catch (Exception)
            {
            }
        }
    
        public static PDFBookmark GetBookmarks(string input)
        {
            PDFDocument document = new PDFDocument(input);
            return document.GetBookmarks();
        }
    }
}