iTextSharp - Links and Bookmarks

Interactivity within PDF documents is enabled though Anchors (links) and Bookmarks. Following earlier articles in my iTextSharp series, this particular contribution will introduce the basics of linking and bookmarking PDF documents created via iTextSharp. You may want to review earlier articles in this series, if you haven't already done so.

Create PDFs in ASP.NET - getting started with iTextSharp
iTextSharp - Working with Fonts
iTextSharp - Adding Text with Chunks, Phrases and Paragraphs
Lists with iTextSharp

Links

iTextSharp Anchor objects are very similar to their HTML counterparts, in that they permit you to create hyperlinks both externally from the document, and internally within the document. Where they diverge from the HTML <a> element is that by default, they do not adopt any special styling within a PDF. For that reason, I suggest applying underlining and a blue colour to the font, as this should help users identify an Anchor as providing some functionality:

 

string path = Server.MapPath("PDFs");

Document doc = new Document();
try

{

    PdfWriter.GetInstance(doc, new FileStream(path + "/Anchors.pdf", FileMode.Create));

    doc.Open();

    Font link = FontFactory.GetFont("Arial", 12, Font.UNDERLINE, new Color(0, 0, 255));

    Anchor anchor = new Anchor("www.mikesdotnetting.com", link);

    anchor.Reference = "http://www.mikesdotnetting.com";

    doc.Add(anchor);

}

catch (DocumentException dex)

{

    Response.Write(dex.Message);

}

catch (IOException ioex)

{

    Response.Write(ioex.Message);

}

finally

{

    doc.Close();

}

 

The code sample above creates an external link, which when clicked will open a browser at this site.

Internal links within an HTML document are specified by adding a NAME attribute to an <a> tag. iTextSharp adopts the same model:

 

Anchor click = new Anchor("Click to go to Target");

click.Reference = "#target";

Paragraph p1 = new Paragraph();

p1.Add(click);

doc.Add(p1);

 

Paragraph p2 = new Paragraph();

p2.Add(new Chunk("\n\n\n\n\n\n\n\n"));

doc.Add(p2);

 

Anchor target = new Anchor("This is the Target");

target.Name = "target";

Paragraph p3 = new Paragraph();

p3.Add(target);

doc.Add(p3);

 

The first paragraph contains the text "Click to go to Target", and its reference is set to "#target", just as with the HTML version. The second paragraph adds some empty lines and the final paragraph contains a new Anchor, with a Name attribute set to match the Reference value in the Anchor in the first paragraph. The result is that if you click on the "Click to go to the Target" text, the PDF will immediately reposition itself so that "This is the Target" will be at the top of whatever PDF viewer you are using.

An alternative to using Anchors to set internal bookmark targets is to use the SetLocalGoto(), and SetLocalDestination() methods of the Chunk class.

 

Paragraph p4 = new Paragraph();

p4.Add(new Chunk("Click "));

p4.Add(new Chunk("here", link).SetLocalGoto("GOTO"));

p4.Add(new Chunk(" to find local goto"));

p4.Add(new Chunk("\n\n\n\n\n\n\n\n\n"));

 

Paragraph p5 = new Paragraph();

p5.Add(new Chunk("Local Goto Destination").SetLocalDestination("GOTO"));

 

doc.Add(p4);

doc.Add(p5);

 

The first chunk is added using the font that's set up to convey to users that the text should act as a hyperlink. The Chunk.SetLocalGoto() method accepts a string, which acts a a label for the target. A number of empty lines are added followed by another chunk. This one has its SetLocalDestination() method invoked, again with a string defining the location of the target. It's matches the one set in the SetLocalGoto() method earlier. When rendered to the PDF, the word "here" is underlined and in blue, and clicking on it brings "Local Goto Destination" to the top of the screen.

Bookmarks

Often when you open a PDF file, your PDF Viewer application displays a tree-view of the structure of the document, with each branch or leaf acting as a link to the corresponding chapter or section. iTextSharp provides the functionality to generate this tree-view through its Chapter and Section classes.

The top-level object is a Chapter, which will always begin on a new page. Sections cannot be added alone, but must be added to Chapter objects, or parent Section objects:

 

Chapter chapter1 = new Chapter(new Paragraph("This is Chapter 1"),1);

Section section1 = chapter1.AddSection(20f, "Section 1.1", 2);

Section section2 = chapter1.AddSection(20f, "Section 1.2", 2);

Section subsection1 = section2.AddSection(20f, "Subsection 1.2.1", 3);

Section subsection2 = section2.AddSection(20f, "Subsection 1.2.2", 3);

Section subsubsection = subsection2.AddSection(20f, "Sub Subsection 1.2.2.1", 4);

Chapter chapter2 = new Chapter(new Paragraph("This is Chapter 2"), 1);

Section section3 = chapter2.AddSection("Section 2.1", 2);

Section subsection3 = section3.AddSection("Subsection 2.1.1", 3);

Section section4 = chapter2.AddSection("Section 2.2", 2);

chapter1.BookmarkTitle = "Changed Title";

chapter1.BookmarkOpen = true;

chapter2.BookmarkOpen = false;

doc.Add(chapter1);

doc.Add(chapter2);

 

The image above helps to explain the preceding code. Initially, a Chapter object is created with a Paragraph passed in as the first argument. The second argument is the number of the Chapter - in this case 1. Nest, a Section object is added to the Chapter, with 3 arguments: a float specifying the left indentation in points; the title of the Section to appear on the page and in the Bookmarks; and the indentation depth for the entry in the Bookmarks tree. In this case, Section 1.1 is set to appear as a second-level entry on the tree. Subsection1 is added to Section 2 and has been told to appear as a third-level entry in the tree. The rest of the code that adds Chapters and Sections should be straightforward.

The final lines of code show that the actual entry in the Bookmarks can be changed from the title on the page by setting the BookMarkTitle property to another string value. Then the outline view for the tree is set as open for Chapter 1, but closed for Chapter 2. Finally, both Chapters are added to the document.

Chapters and Sections are pretty memory hungry, so they should be used judiciously. If you need to create a document such as a manual on a regular basis, this might be a task best scheduled for quieter times on your web server.

 

Date Posted: Thursday, October 23, 2008 9:51 PM
Last Updated: Thursday, November 20, 2014 1:54 PM
Posted by: Mikesdotnetting
Total Views to date: 87572

12 Comments

Wednesday, August 12, 2009 3:08 PM - Neeraj Kumar

The article is good enough to create bookmark when creating new pdf.
But my problem is different from the solution. I have PDF file generated by some other tool. Now i want to automate the process to bookmark the existing pdf, do you any idea how to do this using iTextSharp library.

Pls provide me relevant solution.

Friday, February 5, 2010 1:34 AM - Carlos

First of all, great article!

I have a question, is it possible to set the Bookmark Panel to Open anytime you open the file?

Many thanks

Thursday, April 29, 2010 7:14 PM - Brian

to answer the question posted by Carlos, here is a snippet that will get the job done.

PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(path + "/YourFileName.pdf", FileMode.Create));
PdfWriter
writer.ViewerPreferences = PdfWriter.PageModeUseOutlines;

If you place this at the top of your code it will tell the pdf document to keep the bookmark pane open.

Thursday, September 16, 2010 8:34 AM - Premananda

Thanks for the information....

How to provide a link in the pdf file to open the attachment ??

Tuesday, November 2, 2010 2:55 PM - SK

Mike,

I want to add links to existing PDF which has multiple pages and multiple items. How can I add "action" (Open link/URL) by .net/asp.net? I thought I will create multiple buttons field on PDF and fetch data from database and set button's action to fetched URL data. Do you know what class from itextsharp I can use? Please let me know it is possible or not? If yes, then please let me know how?

Wednesday, March 9, 2011 6:46 PM - Michael Hallock

Thank you so much for these articles.

Do you know of a way to hide the Chapter and Section titles in the actual document, while maintaining the Bookmarks?

Friday, September 27, 2013 1:53 AM - Robert

Thank you for the article! It was very helpful for putting bookmarks into my PDFs as I was merging many into one. :)

(Thanks also to Brian for his comment for forcing the Bookmark pane open.)

Thursday, October 17, 2013 2:36 PM - Jason

Thank you so much for this article! i was googling my butt off trying to look for the terminology for "pdf Index and navigation in c# - iTextSharp" (or something to that effect) in a pdf file...just to find out it is called "Bookmarks"...who would have known...

anyway thanks for the info

Friday, September 5, 2014 9:11 PM - Herman Valente

I've created several PDF documents using iTextsharp containg ONLY internal links (anchors). However, half the time I click these links, I get a security warning that says....
"This document is trying to connect to file:///...."

Is there a workarround?

Friday, September 5, 2014 9:23 PM - Mike

@Herman

There isn't an ASP.NET solution. The warning belongs to the PDF viewer software. You should ask your question in a relevant forum.

Wednesday, November 19, 2014 4:28 PM - Rob Farquharson

How can I place text at an absolute position on the page? Also, how can I rotate text?

Thursday, November 20, 2014 1:50 PM - Mike

@Rob,

You need to use the PdfContentByte object to do that. The following snippet will set some text and then position it at x = 200, y = 300 and rotate it 90°

var path = Server.MapPath("PDFs");
var doc = new Document();
var writer = PdfWriter.GetInstance(doc, new FileStream(path + "/RotateText.pdf", FileMode.Create));
doc.Open();
var content = writer.DirectContent;
content.BeginText();
content.SetFontAndSize(BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, false), 20f);
var text = "Hello World";
content.ShowTextAligned(PdfContentByte.ALIGN_LEFT, text, 200, 300, 90);
content.EndText();
doc.Close();
Add your comment

If you have any comments to make about this article, please use this form to do so. Make sure that your comment relates specifically to the article above. More general comments can be posted through the form on the Contact page.

Please note, all comments are moderated, and some may not be published. The kind of things that will ensure your comment is deleted without ever seeing the light of day are as follows:

  • Not relevant to the article
  • Gratuitous links to your own site or product
  • Anything abusive or libellous
  • Spam
  • Anything in a language I don't understand including gibberish.

I do not pass email addresses on to spammers, so a valid one will assist me in responding to you personally if required.

Recent Comments

Allen Michaels 12/17/2014 4:37 PM
In response to Cascading DropDownLists with jQuery and ASP.NET
Fantastic thank you so much!...

Emily 12/17/2014 12:36 PM
In response to Parameterized IN clauses with ADO.NET and LINQ
Thanks, very helpful!!!! Can i use this for multiple in's ????? IN (.....) and IN(...) and IN...

sss 12/16/2014 3:06 PM
In response to Solving the Operation Must Use An Updateable Query error
good...

Gjuro 12/15/2014 10:30 PM
In response to Examining the Edit Methods and Edit View
You have one fromr (and it should be from, I suppose). :-)...

Gjuro 12/15/2014 10:27 PM
In response to Adding Search
Hi, thnx for all this C#->VB translations. Yet, the following code block is (slightly) in error it a...

Scot 12/14/2014 1:39 PM
In response to Entity Framework 6 Recipe - Alphabetical Paging In ASP.NET MVC
Thanks,Mike I found solution....

Gjuro 12/13/2014 10:52 PM
In response to Accessing Your Model's Data from a Controller
The article mentions "Creating an Entity Framework Data Model for an ASP.NET MVC Application" (at is...

Samuel 12/13/2014 8:40 AM
In response to Displaying The First n Characters Of Text
I have failed to use the extension because it throws an error that it doesn't recognise the chop be...

Ignas 12/12/2014 5:11 PM
In response to Cleaner Conditional HTML Attributes In Razor Web Pages
Any suggestions for Html Helper elements with HtmlAttributes, when you need to conditionally set it...

Gautam 12/11/2014 8:50 PM
In response to Validation In Razor Web Pages 2
Hi Mike Is this required for V3, non html helper input...