SelectPdf for .NET - Pdf Internal and External Links - C# / ASP.NET Sample

This sample shows how to create a new PDF document using SelectPdf, how to add 2 pages to the document and several internal and external links.


Sample Code C#



using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SelectPdf;

namespace SelectPdf.Samples
{
    public partial class pdf_links : System.Web.UI.Page
    {
        protected void BtnCreatePdf_Click(object sender, EventArgs e)
        {
            // create a new pdf document
            PdfDocument doc = new PdfDocument();

            // add a new page to the document
            PdfPage page1 = doc.AddPage();

            // add a second page to the document
            PdfPage page2 = doc.AddPage();

            // define a rendering result object
            PdfRenderingResult result;

            // create a new pdf font
            PdfFont font = doc.AddFont(PdfStandardFont.Helvetica);
            font.Size = 14;
            font.IsUnderline = true;

            // create a new text element and add it to the first page
            PdfTextElement text1 = new PdfTextElement(0, 0, 
                "First page (no link on this text)", font);
            page1.Add(text1);

            // create a new text element and add it to the second page
            PdfTextElement text2 = new PdfTextElement(0, 0, 
                "Second page (no link on this text)", font);
            page2.Add(text2);

            // create external link in 2 steps
            
            // 1 - create the link text
            PdfTextElement linkText1 = new PdfTextElement(0, 50, 
                "External link (click to go to selectpdf.com)", font);
            result = page1.Add(linkText1);
            
            // 2 - add the link using the text rendering rectangle
            PdfExternalLinkElement extLink1 = new PdfExternalLinkElement(
                result.PdfPageLastRectangle, "http://selectpdf.com");
            page1.Add(extLink1);

            // create internal link in 2 steps

            // 1 - create the link text
            PdfTextElement linkText2 = new PdfTextElement(0, 100, 
                "Internal link (click to go to the second page)", font);
            result = page1.Add(linkText2);

            // 2 - add the link using the text rendering rectangle
            PdfInternalLinkElement intLink1 = new PdfInternalLinkElement(
                result.PdfPageLastRectangle, new PdfDestination(page2));
            page1.Add(intLink1);

            // save pdf document
            doc.Save(Response, false, "Sample.pdf");

            // close pdf document
            doc.Close();
        }
    }
}