PDF Viewers such as Adobe Acrobat and Foxit Reader display bookmarks of a PDF document as an outline tree. The user can click titles of the bookmarks in the tree to jump to corresponding sections of the document. You can create an outline entry or bookmark by creating an instance of the PdfOutline class. One constructor of the PdfOutline class that can be used to create a bookmark is shown below:
PdfOutline(PdfOutline parent, PdfAction action, String title)
-The parent--An PdfOutline object that will be the root of other newly created bookmarks. You can get the root bookmark by using the RootOutline property of an instace of PdfWriter class.
-The action--PdfAction object or a static method of the PdfAction class that allows you to specify a destination. When the user clicks a bookmark's title, it will jump to the corresponding destination.
-The title--A string that is a title of the bookmark. You can use a Paragraph for the bookmark's title. However, the style of the Paragraph object is not taken into account.
To create a named destination of a bookmark, you will create an instance of the Anchor class.
//create anchor for section 1
Anchor section1 = new Anchor("Section 1: Adding bookmark to a new PDF document");
section1.Name = "sect1";
A bookmark that you can click its title to jump to the named destination above will be written as below:
PdfOutline root = writer.RootOutline;
PdfOutline mbot = new PdfOutline(root, PdfAction.GotoLocalPage("sect1", false), "Section 1");
You can download the complete C# code to add bookmarks to a PDF document from here.
You can retrieve all bookmarks from an existing document by using the SimpleBookmark class. The example code below reads all bookmarks from the jmf_tutorial.pdf file and writes them to the bookmarks.xml file.
String pathin = "d:/jmf_tutorial.pdf";
//PdfReader object to read from the source file
PdfReader reader = new PdfReader(pathin);
//Get bookmarks from the file through the PdfReader object
IList<Dictionary<String, Object>> list = SimpleBookmark.GetBookmark(reader);
//Write the bookmarks to bookmarks.xml file
SimpleBookmark.ExportToXML(list, new FileStream("d:/bookmarks.xml", FileMode.Create), "ISO8859-1", true);
Here is the content of the bookmarks.xml file.
This website intents to provide free and high quality tutorials, examples, exercises and solutions, questions and answers of programming and scripting languages: