SelectPdf for .NET - Pdf Internal and External Links - C# / ASP.NET MVC 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.Web.Mvc;

namespace SelectPdf.Samples.Controllers
{
    public class PdfLinksController : Controller
    {
        // GET: PdfLinks
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult SubmitAction(FormCollection collection)
        {
            // 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
            byte[] pdf = doc.Save();

            // close pdf document
            doc.Close();
           
            // return resulted pdf document
            FileResult fileResult = new FileContentResult(pdf, "application/pdf");
            fileResult.FileDownloadName = "Document.pdf";
            return fileResult;
        }
    }
}