pdf links

PDF Rendering
Convert PDF to Image (.NET)
Convert PDF to image on Android (Xamarin)
Convert PDF to image on iOS (Xamarin)
Convert PDF to image in Windows Store apps (.NET)
Convert PDF to image in Windows Phone apps (.NET)
PDF to image in Universal Windows Store apps (.NET)
Free PDF Viewer control for Windows Forms (.NET)
How to integrate PDF Viewer control in WPF app (.NET)
Creating WPF PDF Viewer supporting bookmarks (.NET)
Cross-platform PDF Viewer using GTK# (MONO)
Silverlight PDF viewer control (Silverlight 5)
Multithreaded PDF rendering (.NET)
Convert pdf to image in Silverlight app (C# sample)
How to set fallback fonts for PDF rendering (C#)
Avoiding the out-of-memory exception on rendering (C#)
PDF viewer single page application (WebAPI, AngularJS)
PDF viewer control for Windows 10 universal applications
Use custom ICC profile for CMYK to RGB conversion
PDF layers - separate images, text, annotations, graphics

PDF Forms Creation PDF Security
Conversion to PDF/A
Other topics
PDF Document Manipulation PDF Content Generation
Fixed and Flow layout document API (.NET)
Creation of grids and tables in PDF (C# sample)
How to create interactive documents using Actions (C# sample)
Text flow effects in PDF (C# sample)
How to generate ordered and bulleted lists in PDF (C# sample)
Convert HTML to PDF using flow layout API (C# sample)
How to use custom fonts for PDF generation (.NET)
Create document with differently sized pages (C#)
Create PDF documents using MONO (C#/MONO/Windows/OSX)
How to use background images for content elements (C#/PDF Kit/FlowLayout)
Add transparent images to PDF document (C#)
Draw round rect borders in PDF documents(C#)
ICC color profiles and and ICC based colors in PDF (C#)
How to use bidirectional and right to left text in PDF (C#)
Create PDF documents from XML templates (C# sample)
How to resize PDF pages and use custom stamps (C#)
Add header and footer to PDF page (.NET sample)
How to use clipping mask for drawing on PDF page
Fill graphics path with gradient brushes in PDF (Shadings)
Apitron PDF Kit and Rasterizer engine settings
Add layers to PDF page (optional content, C# sample)
How to create free text annotation with custom appearance
PDF Content Extraction PDF Navigation
PDF to TIFF conversion
Contact us if you have a PDF related question and we'll cover it in our blog.

2015-05-13

How to create links and bookmarks in PDF

1.  Links and bookmarks in PDF


While these terms seem familiar, we think there still needs to be a brief intro, describing their particular properties taking into account the PDF basis. Links in PDF are made by link annotations, special kind of “annotation” objects which, in general, can be added to any page being a helpful addition to page content. There are lots of annotation types defined in PDF specification, just take a look at the section 12.5.6 Annotation Types.

Link annotations - work as “hot” area markers and navigate user to the desired location within the document, or to external destination. Seems similar to HTML, but the key difference is that link annotations are totally independent from the content of PDF document.  It’s also possible to assign “actions” to link annotations instead of pure Destination objects, e.g. JavaScriptAction, GoToAction, SoundAction etc. Section 12.6.4 Actions Types of the specification has a complete list. We will focus on simple destinations in this post, leaving the actions for near future.


Bookmarks - can be seen on the left pane of PDF reader if present, see the image below:

Pic. 1 PDF bookmarks panel

Pic. 1 Bookmarks panel

PDF bookmarks work similar to links, having the same set of features: one can be navigated using Destination objects, or the specific action can be triggered by clicking a bookmark. In addition, they can form hierarchical structures showing the outline of the document.


2. Fixed layout approach to navigation


Fixed layout API from Apitron PDF Kit for .NET provides an easy and straightforward way to create links and bookmarks in pdf documents. All necessary objects are described in the pdf specification and have very close mapping to their library counterparts, therefore, one can quickly start creating PDF documents by referring to a standard specification.

See the c# code sample below, it creates a link and bookmark pointing to the second page:

public void CreateLinksAndBookmarks()
{
    // create pdf document
    FixedDocument doc = new FixedDocument();
    // add a bookmark for second page
    doc.Bookmarks.AddFirst(new Bookmark(new Destination(1),"Go to second page"));

    // add first page with text link
    Page firstPage = new Page();
           
    // add link text
    TextObject linkTextObject = new TextObject();
    linkTextObject.AppendTextLine("Go to second page");
           
    firstPage.Content.SaveGraphicsState();
    firstPage.Content.SetDeviceNonStrokingColor(RgbColors.Blue.Components);
    firstPage.Content.Translate(10, 820);           
    firstPage.Content.AppendText(linkTextObject);
    firstPage.Content.RestoreGraphicsState();           

    // add link annotation covering the text
    LinkAnnotation link = new LinkAnnotation(new Boundary(10,815,135,835));           
    link.BorderStyle = new AnnotationBorderStyle(0);
    link.Destination = new Destination(1);
    firstPage.Annotations.Add(link);

    // add destination page
    Page secondPage = new Page();

    TextObject textObject = new TextObject();
    textObject.AppendTextLine("Second page");

    secondPage.Content.Translate(10,820);
    secondPage.Content.AppendText(textObject);

    // append pages
    doc.Pages.Add(firstPage);
    doc.Pages.Add(secondPage);           

    // save document
    using (Stream stream = File.Create("create_links_and_bookmarks_fixed_layout.pdf"))
    {
        doc.Save(stream);
    }
}

The resulting document is shown on the image below:


Pic. 2 Creating pdf link and bookmark using fixed layout API

As it can be seen from this image, the link and bookmark both navigate the user to the second page of the document. We used Destination object constructed using page index which set up the target for navigation. Note that links on page are independent from content and are simply “hot” areas which can cover any desired part of the pdf page.


3. Flow layout approach to navigation


If you were to create a flow layout document and add links or bookmarks to it, you would have to use Link or Bookmark property that each ContentElement provides.  We use a declarative approach here – each content element indicates whether it is a link, pointing to other element or external resource, or it needs a bookmark pointing to it, or both. The rest is being processed automatically.

Consider the code:

public void CreateLinksAndBookmarksFlowLayout()
{
    // create pdf document
    FlowDocument doc = new FlowDocument(){Margin = new Thickness(10)};                 

    // create first text block and make it a link
    doc.Add(new TextBlock("Go to second page"){ Color = RgbColors.Blue,
        Link = new CrossReference("page2")});        
    // force 2nd page creation
    doc.Add(new PageBreak());                       
           
    // add second text block, indicate that it needs a bookmark
    doc.Add(new TextBlock("Second page") { Id = "page2",
        Bookmark = new BookmarkEntry("Go to second page") });           

    // save document
    using (Stream stream = File.Create("create_links_and_bookmarks_flow_layout.pdf"))
    {
        doc.Write(stream, new ResourceManager());
    }
}

And the result:

Pic. 3 Create pdf links and bookmarks using flow layout API

Pic. 3 Create pdf links and bookmarks using flow layout API

It looks the same as document created using fixed layout API. Notice that it took us less than 10 lines of code to produce this PDF document.


3.1 Advanced bookmarking sample


In this example we will create a document outline using flow layout API, you can use this technique to create table of contents or similar structural descriptions. See the image below, it shows the document having a set of bookmarks and each of them corresponds to a content section on PDF page.

Pic. 4 Hierarchical bookmarks in PDF

Pic. 4 Hierarchical bookmarks

The code generating this document is provided below, it uses a style matched via the type selector for textblock elements styling; other parts are similar to the code from previous example.

Code sample:

public void CreateLinksAndBookmarksFlowLayoutAdvanced()
{
    // create pdf document
    FlowDocument doc = new FlowDocument() { Margin = new Thickness(10) };

    // create style matching each textblock, making it small article
    doc.StyleManager.RegisterStyle("Textblock", new Style(){Display = Display.Block,
        Height = 100,
        Background = RgbColors.WhiteSmoke, Margin = new Thickness(0,0,0,5)});

    // create a section with a root bookmark
    Section page1 = new Section()
        { Bookmark = new BookmarkEntry("1. Introduction"};           

    page1.Add(new TextBlock("Introduction"));
           
    // add textblocks and indicate they need a bookmark
    page1.Add(new TextBlock("Part 1.1 - place your content here")
        { Bookmark = new BookmarkEntry("1.1 First section") });
    page1.Add(new TextBlock("Part 1.2 - place your content here")
        { Bookmark = new BookmarkEntry("1.2 Second section") });           

    // add section to the document
    doc.Add(page1);

    // save document
    using (Stream stream = File.Create("create_bookmarks_flow_layout.pdf"))
    {
        doc.Write(stream, new ResourceManager(), new PageBoundary(Boundaries.A6));
    }
}

You can see that we used a Section object here to create the bookmarks hierarchy. The bookmark assigned to the section gets created as the parent bookmark for bookmarks generated for nested elements.

4. Conclusion


In this post we have shown how to create links and bookmarks in PDF documents. You can read more about PDF processing in our free book available for download here. Future posts will continue to explore various aspects of PDF and our API.

The Apiton PDF Kit for .NET is a powerful and easy to use pdf library available for all modern platforms. Develop applications for Xamarin (iOS, Android, Mac) and cross-platform MONO apps. Create Windows .NET applications targeting desktop, phone or tablet users. It doesn’t matter whether you use WinForms, WPF, or develop for Windows Store or Windows Phone Silverlight; it always provides you with an ability to create perfect PDF documents. This library can be used to create web apps or web services based on ASP.NET MVC, WebForms, Azure Web or Worker roles.

Contact us if you have any questions, we’re always open for any feedback. Downloadable version of this article can be found by the following link [PDF].

No comments:

Post a Comment