Link to files with relative paths using PdfLaunchAction

2017-03-07 09:37:07 Written by  support iceblue
Rate this item
(0 votes)

PDF actions can refer to external files by using either absolute or relative file paths. While using the relative path in action, the file can be moved into a different location. In Spire.PDF, we can use the PdfLaunchAction to link to files with relative paths.

Code snippet:

Step 1: Create a new PDF document and add a page to it.

PdfDocument document = new PdfDocument();
PdfPageBase page = document.Pages.Add();     

Step 2: Create a PDF launch action that refers to an external file with relative path.

PdfLaunchAction launchAction = new PdfLaunchAction(@"..\..\test.txt", PdfFilePathType.Relative);

Step 3: Create a PDF action annotation with the launch action. Add the annotation to the page.

string text = "Click here to open file with relative path";
PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial", 13f));
RectangleF rect = new RectangleF(50, 50, 230, 15);
page.Canvas.DrawString(text, font, PdfBrushes.ForestGreen, rect);
PdfActionAnnotation annotation = new PdfActionAnnotation(rect, launchAction);
(page as PdfNewPage).Annotations.Add(annotation);     

Step 4: Save the document.

document.SaveToFile("RelativeFilePath.pdf");

Screenshot:

Link to files with relative paths using PdfLaunchAction

Full code:

using System.Drawing;
using Spire.Pdf;
using Spire.Pdf.Actions;
using Spire.Pdf.Annotations;
using Spire.Pdf.Graphics;

namespace Link_to_files_with_relative_paths
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a new PDF document and add a page to it
            PdfDocument document = new PdfDocument();
            PdfPageBase page = document.Pages.Add();

            //Create a PDF Launch Action       
            PdfLaunchAction launchAction = new PdfLaunchAction(@"..\..\test.txt", PdfFilePathType.Relative);
            
            //Create a PDF Action Annotation with the PDF Launch Action
            string text = "Click here to open file with relative path";
            PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial", 13f));
            RectangleF rect = new RectangleF(50, 50, 230, 15);
            page.Canvas.DrawString(text, font, PdfBrushes.ForestGreen, rect);
            PdfActionAnnotation annotation = new PdfActionAnnotation(rect, launchAction); 
             //Add the PDF Action Annotation to page
            (page as PdfNewPage).Annotations.Add(annotation);           

            //Save and close the document
            document.SaveToFile("RelativeFilePath.pdf");
            document.Close();
        }
    }
}

Additional Info

  • tutorial_title:
Last modified on Sunday, 26 September 2021 02:19