C#: Create Actions in PDF Documents

Enhancing the interactivity of PDF files is a crucial aspect of document management and user engagement. Creating actions within PDFs using C# in the .NET framework allows developers to add dynamic elements such as file links, web links, and audio that can execute various functions like navigating to different pages, launching external applications, or playing background music, which improves the user experience by making PDFs more functional and engaging. This article demonstrates how to use the Spire.PDF for .NET library to create actions in PDF documents with C#.

Install Spire.PDF for .NET

To begin with, you need to add the DLL files included in the Spire.PDF for.NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.PDF

General Steps for Adding Actions to PDF with C#

Adding actions to a PDF using C# involves integrating interactive elements that enhance user experience, such as navigation buttons, file links, or sound triggers. With the Spire.PDF for .NET library, developers can create various actions by leveraging key classes and methods. Below is an introduction to the general process of adding actions in PDF with Spire.PDF for .NET.

  1. Create an instance of PdfDocument class and load a PDF document using PdfDocument.LoadFromFile() method.
  2. Get a page using PdfDocument.Pages[] property.
  3. Create an instance of the class that represents the action and set the action properties.
  4. Create an instance of PdfActionAnnotation class in a rectangular area on the page using the action.
  5. Add the cue word for the action to the page (optional).
  6. Add the action annotation to the page using PdfPageBase.Annotations.Add() method.
  7. Save the result document using PdfDocument.SaveToFile() method.

Create Navigation Actions in PDF with C#

Navigation actions can be created using the PdfGoToAction class, which defines navigation within the document to a specified destination. To achieve this, developers can create a PdfDestination object and pass it as a parameter to a PdfGoToAction instance.

The following is a code example of adding a navigation action to a PDF:

  • C#
using Spire.Pdf;
using Spire.Pdf.Actions;
using Spire.Pdf.Annotations;
using Spire.Pdf.General;
using Spire.Pdf.Graphics;
using System.Drawing;

namespace AddNavigationButtonPDF
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create an instance of PdfDocument
            PdfDocument pdf = new PdfDocument();

            // Load a PDF file
            pdf.LoadFromFile("Sample.pdf");

            // Create a PdfDestination instance and set the destination
            PdfDestination destination = new PdfDestination(pdf.Pages[1]);
            destination.Location = new PointF(0, 0);
            destination.Mode = PdfDestinationMode.Location;
            destination.Zoom = 0.8f;

            // Create a PdfGoToAction based on the destination
            PdfGoToAction action = new PdfGoToAction(destination);

            // Create a rectangle and draw it on the first page
            RectangleF rect = new RectangleF(70, pdf.PageSettings.Size.Height - 120, 140, 20);
            pdf.Pages[0].Canvas.DrawRectangle(PdfBrushes.LightGray, rect);
            // Draw cue words on the rectangle
            PdfFont font = new PdfFont(PdfFontFamily.TimesRoman, 14);
            PdfStringFormat stringFormat = new PdfStringFormat(PdfTextAlignment.Center);
            pdf.Pages[0].Canvas.DrawString("To Page 2", font, PdfBrushes.Green, rect, stringFormat);

            // Create a PdfActionAnnotation instance based on the rectangle and the action
            PdfActionAnnotation actionAnnotation = new PdfActionAnnotation(rect, action);

            // Add the action annotation to the first page
            pdf.Pages[0].Annotations.Add(actionAnnotation);

            // Save the document
            pdf.SaveToFile("output/NavigationButton.pdf");
            pdf.Close();
        }
    }
}

Result of Creating Navigation Buttons with C#

Create File Launch Actions in PDF with C#

The PdfLaunchAction class defines a file open action in a PDF that enables users to open a specific file by clicking a button embedded on a PDF page. When implementing this action, developers can set the file path (absolute or relative) and decide whether the file should open in a new window. Here is a code example for adding a file launch action in a PDF document:

  • C#
using Spire.Pdf;
using Spire.Pdf.Actions;
using Spire.Pdf.Annotations;
using Spire.Pdf.Graphics;
using System.Drawing;

namespace AddFileLaunchActionPDF
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create an instance of PdfDocument
            PdfDocument pdf = new PdfDocument();

            // Load a PDF file
            pdf.LoadFromFile("Sample.pdf");

            // Get the first page
            PdfPageBase page = pdf.Pages[0];

            // Draw a rectangle on the page
            RectangleF rect = new RectangleF(50, 50, 180, 20);
            page.Canvas.DrawRectangle(PdfBrushes.LightGray, rect);
            // Darw the cue words in the rectangle
            PdfFont font = new PdfFont(PdfFontFamily.TimesRoman, 14);
            PdfStringFormat stringFormat = new PdfStringFormat(PdfTextAlignment.Center);
            pdf.Pages[0].Canvas.DrawString("Click to launch Sample2", font, PdfBrushes.Green, rect, stringFormat);

            // Create a PdfLaunchAction instance
            PdfLaunchAction action = new PdfLaunchAction("C:/Sample2.pdf", PdfFilePathType.Absolute);
            // Set the launch mode to open in new window
            action.IsNewWindow = true;

            // Create a PdfActionAnnotation instance based on the rectangle and the launch action
            PdfActionAnnotation actionAnnotation = new PdfActionAnnotation(rect, action);

            // Add the action annotation to the first page
            page.Annotations.Add(actionAnnotation);

            // Save the document
            pdf.SaveToFile("output/LaunchAction.pdf");
            pdf.Close();
        }
    }
}

Result of Creating File Launch Actions with C#

Create Sound Actions in PDF with C#

Developers can embed audio as an action in PDF documents with the PdfSoundAction class, enabling the audio to play in response to specific triggers, such as opening the file or clicking a button. Below is a code example for creating a sound action in a PDF document:

  • C#
using Spire.Pdf;
using Spire.Pdf.Actions;
using Spire.Pdf.Annotations;
using Spire.Pdf.Graphics;
using Spire.Pdf.General;
using System.Drawing;

namespace AddSoundActionPDF
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create an instance of PdfDocument
            PdfDocument pdf = new PdfDocument();

            // Load a PDF file
            pdf.LoadFromFile("Sample.pdf");

            // Get the first page
            PdfPageBase page = pdf.Pages[0];

            // Darw the cue image on the page
            PdfImage image = PdfImage.FromFile("Sound.png");
            page.Canvas.DrawImage(image, new PointF(30, 30));

            // Create a PdfSoundAction instance and set its property
            PdfSoundAction action = new PdfSoundAction("Wave.wav");
            // Set the sound parameters
            action.Sound.Bits = 16;
            action.Sound.Channels = PdfSoundChannels.Stereo;
            action.Sound.Encoding = PdfSoundEncoding.Signed;
            action.Sound.Rate = 44100;
            // Set the play options
            action.Volume = 0;
            action.Repeat = true;
            action.Mix = true;
            action.Synchronous = true;

            // Create a PdfActionAnnotation instance using the sound action at the location of the cue image
            RectangleF rect = new RectangleF(30, 30, image.Width, image.Height);
            PdfActionAnnotation actionAnnotation = new PdfActionAnnotation(rect, action);

            // Add the action annotation to the first page
            page.Annotations.Add(actionAnnotation);

            // Set the sound action to play after the document is opened
            pdf.AfterOpenAction = action;

            // Save the document
            pdf.SaveToFile("output/SoundAction.pdf");
            pdf.Close();
        }
    }
}

Result of Creating Sound Actions with C#

Create Web Link Actions in PDF with C#

Developers can use the PdfUriAction class to create a web link action in PDF documents, allowing users to open a web link when performing specific actions, such as clicking a button. Below is a code example for creating a web link action in a PDF document:

  • C#
using Spire.Pdf;
using Spire.Pdf.Actions;
using Spire.Pdf.Annotations;
using Spire.Pdf.Graphics;
using System.Drawing;

namespace AddSoundActionPDF
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create an instance of PdfDocument
            PdfDocument pdf = new PdfDocument();

            // Load a PDF file
            pdf.LoadFromFile("Sample.pdf");

            // Get the first page
            PdfPageBase page = pdf.Pages[0];

            // Draw a rectangle on the page
            RectangleF rect = new RectangleF(30, 30, 120, 20);
            page.Canvas.DrawRectangle(PdfBrushes.LightGray, rect);
            // Draw the cue words in the rectangle
            PdfFont font = new PdfFont(PdfFontFamily.TimesRoman, 14);
            PdfStringFormat stringFormat = new PdfStringFormat(PdfTextAlignment.Center);
            page.Canvas.DrawString("Go to Google Search", font, PdfBrushes.LightSkyBlue, rect);

            // Create a PdfUriAction instance and set its property
            PdfUriAction action = new PdfUriAction();
            action.Uri = "https://www.google.com/";

            // Create a PdfActionAnnotation instance using the web link action and the rectangle
            PdfActionAnnotation actionAnnotation = new PdfActionAnnotation(rect, action);

            // Add the action annotation to the first page
            page.Annotations.Add(actionAnnotation);

            // Save the document
            pdf.SaveToFile("output/WebLinkAction.pdf");
            pdf.Close();
        }
    }
}

Result of Creating Web Link Actions with C#

Create JavaScript Actions in PDF with C#

The PdfJavaScriptAction represents a JavaScript action in PDF, which allows developers to create complex interactions such as form validations, data calculations, and custom user interfaces. Below is a code example for adding a simple JavaScript action to a PDF document with C#:

  • C#
using Spire.Pdf;
using Spire.Pdf.Actions;

namespace AddJavaScriptActionPDF
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a PdfDocument instance
            PdfDocument pdf = new PdfDocument();

            // Load a PDF file
            pdf.LoadFromFile("Sample.pdf");

            // Define JavaScript code
            var jsCode =
            "app.alert({" +
            "    cMsg: 'Welcome to the article about the Evolution and Advantages of LCD Screens!\\n\\nThis article explores the history and benefits of LCD technology, including its impact on visual experiences across various devices.', " +
            "    nIcon: 3, " +
            "    cTitle: 'Document Introduction'" +
            "});";

            // Create a PdfJavaScriptAction instance using the JavaScript code
            PdfJavaScriptAction action = new PdfJavaScriptAction(jsCode);

            // Set the action to be executed when the PDF document is launched
            pdf.AfterOpenAction = action;

            // Save the document
            pdf.SaveToFile("output/PDFJavaScriptAction.pdf");
            pdf.Close();
        }
    }
}

Result of Creating JavaScript Actions with C#

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.