Add a Print Button to a PDF Document in C#

Adding print button to PDF document is possible in Spire.PDF, when the button is clicked, the print dialog will be opened. In this tutorial, I'm going to show you how to add a print button to an existing pdf document using Spire.PDF.

To accomplish the task, first you need to create an instance of the PdfButtonField class. This class also allows you to define the appearance of the button. For instance, you can set text, color of text, background color, border color etc. of the button. Second you need to add the print action to the button by calling the AddPrintAction() method. At last, add the button to the document and save the document to file. The following code example explains the same.

Code snippets:

Step 1: Load the PDF document and enable form creation.

PdfDocument doc = new PdfDocument("Input.pdf");
doc.AllowCreateForm = true;

Step 2: Get the first page.

PdfPageBase page = doc.Pages[0];

Step 3: Create a PdfButtonField instance and set properties for the button.

PdfButtonField button = new PdfButtonField(page, "Print");
button.Bounds = new RectangleF(280, 600, 50, 20);
button.BorderColor = new PdfRGBColor(Color.AliceBlue);
button.BorderStyle = PdfBorderStyle.Solid;
button.ForeColor = new PdfRGBColor(Color.White);
button.BackColor = new PdfRGBColor(Color.Blue);
button.ToolTip = "Print";
button.Font = new PdfFont(PdfFontFamily.Helvetica, 9f);

Step 4: Add print action to the button.

button.AddPrintAction();

Step 5: Add the button to the document.

doc.Form.Fields.Add(button);

Step 6: Save the document.

doc.SaveToFile("Output.pdf");

The resultant document looks as follows:

Add a Print Button to a PDF Document in C#

Full code:

using System.Drawing;
using Spire.Pdf;
using Spire.Pdf.Fields;
using Spire.Pdf.Graphics;

namespace Add_print_button
{
    class Program
    {
        static void Main(string[] args)
        {
            //Load the PDF document
            PdfDocument doc = new PdfDocument("Input.pdf");
            //Enable form creation
            doc.AllowCreateForm = true;
            //Get the first page
            PdfPageBase page = doc.Pages[0];

            //Create a PdfButtonField instance
            PdfButtonField button = new PdfButtonField(page, "Print");
            //Set button properties
            button.Bounds = new RectangleF(280, 600, 50, 20);
            button.BorderColor = new PdfRGBColor(Color.AliceBlue);
            button.BorderStyle = PdfBorderStyle.Solid;
            button.ForeColor = new PdfRGBColor(Color.White);
            button.BackColor = new PdfRGBColor(Color.Blue);
            button.ToolTip = "Print";
            button.Font = new PdfFont(PdfFontFamily.Helvetica, 9f);

            //Add print action to the button
            button.AddPrintAction();

            //Add the button to document
            doc.Form.Fields.Add(button);            

            //Save the document
            doc.SaveToFile("Output.pdf");
        }
    }
}