Add bookmarks to PDF

Manipulate PDF
2/14/2014

Downloads

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

C# code sample

1 using ( FileStream inFile = new FileStream( @"..\..\..\inputDocuments\PackingLightBrochure.pdf", FileMode.Open, FileAccess.Read ) ) 2 { 3 // open the source document 4 Document document = new Document( inFile ); 5 6 // remove the current security settings 7 document.Security = null; 8 9 // assign a new empty collection of top-level bookmarks 10 document.Bookmarks = new BookmarkCollection(); 11 12 // enumerate the pages in the source document 13 Bookmark bookmark; 14 for ( int i=0; i<document.Pages.Count; i++ ) 15 { 16 Page page = document.Pages[i]; 17 18 bookmark = new Bookmark("Page " + ( i + 1 )); 19 InternalDestination destination = new InternalDestination( page ); 20 destination.PageDisplay = PageDisplay.FitEntire; 21 GoToAction goToAction = new GoToAction( destination ); 22 bookmark.Actions.Add( goToAction ); 23 24 document.Bookmarks.Add( bookmark ); 25 } 26 27 //add a bookmark which links to a website 28 bookmark = new Bookmark( "http://www.tallcomponents.com" ); 29 UriAction uriAction = new UriAction( "http://www.tallcomponents.com" ); 30 bookmark.Actions.Add( uriAction ); 31 document.Bookmarks.Add( bookmark ); 32 33 // write the target document to disk 34 using ( FileStream outFile = new FileStream( @"..\..\addbookmarks.pdf", FileMode.Create, FileAccess.Write ) ) 35 { 36 document.Write( outFile ); 37 } 38 }

VB.NET code sample

1 Using inFile As New FileStream("..\..\..\inputDocuments\PackingLightBrochure.pdf", FileMode.Open, FileAccess.Read) 2 ' open the source document 3 Dim document As New Document(inFile) 4 5 ' remove the current security settings 6 document.Security = Nothing 7 8 ' assign a new empty collection of top-level bookmarks 9 document.Bookmarks = New BookmarkCollection() 10 11 ' enumerate the pages in the source document 12 Dim bookmark As Bookmark 13 For i As Integer = 0 To document.Pages.Count - 1 14 Dim page As Page = document.Pages(i) 15 16 bookmark = New Bookmark("Page " & (i + 1)) 17 Dim destination As New InternalDestination(page) 18 destination.PageDisplay = PageDisplay.FitEntire 19 Dim goToAction As New GoToAction(destination) 20 bookmark.Actions.Add(goToAction) 21 22 document.Bookmarks.Add(bookmark) 23 Next 24 25 bookmark = New Bookmark("http://www.tallcomponents.com") 26 Dim uriAction As New UriAction("http://www.tallcomponents.com") 27 bookmark.Actions.Add(uriAction) 28 document.Bookmarks.Add(bookmark) 29 30 ' write the target document to disk 31 Using outFile As New FileStream("..\..\addbookmarks.pdf", FileMode.Create, FileAccess.Write) 32 document.Write(outFile) 33 End Using 34 End Using

See below the created bookmarks in a PDF document:

bookmarks.png