Add bookmarks to PDF

Manipulate PDF
2/14/2014

Downloads

This code sample shows how to create bookmarks in an existing PDF document.

using ( FileStream inFile = new FileStream( @"..\..\..\inputDocuments\PackingLightBrochure.pdf", FileMode.Open, FileAccess.Read ) )
{
    // open the source document
    Document document = new Document( inFile );

	// remove the current security settings
	document.Security = null;

    // assign a new empty collection of top-level bookmarks
    document.Bookmarks = new BookmarkCollection();

    // enumerate the pages in the source document
    Bookmark bookmark;
    for ( int i=0; i<document.Pages.Count; i++ )
    {
        Page page = document.Pages[i];

        bookmark = new Bookmark("Page " + ( i + 1 ));
        InternalDestination  destination = new InternalDestination( page );
        destination.PageDisplay = PageDisplay.FitEntire;
        GoToAction goToAction = new GoToAction( destination );
        bookmark.Actions.Add( goToAction );
        
        document.Bookmarks.Add( bookmark ); 
    }

    //add a bookmark which links to a website
    bookmark = new Bookmark( "http://www.tallcomponents.com" );
    UriAction uriAction = new UriAction( "http://www.tallcomponents.com" );
    bookmark.Actions.Add( uriAction );
    document.Bookmarks.Add( bookmark ); 

    // write the target document to disk
    using ( FileStream outFile = new FileStream( @"..\..\addbookmarks.pdf", FileMode.Create, FileAccess.Write ) )
    {
    document.Write( outFile );
    }
Using inFile As New FileStream("..\..\..\inputDocuments\PackingLightBrochure.pdf", FileMode.Open, FileAccess.Read)
    ' open the source document
    Dim document As New Document(inFile)

    ' remove the current security settings
    document.Security = Nothing

    ' assign a new empty collection of top-level bookmarks
    document.Bookmarks = New BookmarkCollection()

    ' enumerate the pages in the source document
    Dim bookmark As Bookmark
    For i As Integer = 0 To document.Pages.Count - 1
        Dim page As Page = document.Pages(i)

        bookmark = New Bookmark("Page " & (i + 1))
        Dim destination As New InternalDestination(page)
        destination.PageDisplay = PageDisplay.FitEntire
        Dim goToAction As New GoToAction(destination)
        bookmark.Actions.Add(goToAction)

        document.Bookmarks.Add(bookmark)
    Next

    bookmark = New Bookmark("http://www.tallcomponents.com")
    Dim uriAction As New UriAction("http://www.tallcomponents.com")
    bookmark.Actions.Add(uriAction)
    document.Bookmarks.Add(bookmark)

    ' write the target document to disk
    Using outFile As New FileStream("..\..\addbookmarks.pdf", FileMode.Create, FileAccess.Write)
        document.Write(outFile)
    End Using
End Using

See below the created bookmarks in a PDF document:

bookmarks.png