DEV Community

Cover image for How to Sign PDF File in C# (Developer Tutorial)
Tayyab Ali
Tayyab Ali

Posted on • Edited on

How to Sign PDF File in C# (Developer Tutorial)

When working with digital documents, signing PDFs is vital for confirming their authenticity and security. Whether it's for contracts, agreements, or important communications, a digital signature verifies the document's origin and integrity. Signed PDF documents are a must-have in this era. Automating this process can save a lot of time, especially when dealing with large volumes of documents.

In this article, we'll explore how to digitally sign a PDF using IronPDF in C#. This powerful tool makes it easy to add digital signatures to your PDFs programmatically. Let's dive into how you can integrate this functionality of signing a PDF document into your applications, boosting both efficiency and security.

How to Sign PDF file in C#

  1. Install PDF Library in Visual Studio
  2. Load PDF file using the PDF library
  3. Load Digital Signature (e.g. pfx file)
  4. Apply the Signature to the PDF file using the PDF Library
  5. Save the signed PDF file

Introduction of IronPDF Library

Image description
IronPDF is a comprehensive PDF generation library for the .NET platform, designed to simplify working with PDF documents in C#. Unlike traditional PDF APIs that can be time-consuming, IronPDF leverages HTML, CSS, images, and JavaScript to render high-quality PDFs efficiently. This tool is perfect for developers looking to create, edit, and manipulate PDF documents with minimal hassle.

Key features of IronPDF include generating PDFs from various sources like HTML strings, URLs, and ASPX web forms. It supports a wide range of applications, from desktop to web and console applications. The library also offers extensive functionality for editing PDFs, such as adding headers, footers, and watermarks, merging and splitting documents, and securing PDFs with passwords and digital signatures. For this article, we'll focus on IronPDF's capability to add digital signatures to PDFs. This feature allows you to programmatically sign documents.

Sign PDF Using IronPDF

With IronPDF, adding digital signatures to your PDF files is straightforward. This section will walk you through installing IronPDF, loading a PDF document, and signing it.

IronPDF provides robust features to ensure that your documents are secure and verifiable. You can easily sign PDF documents with digital certificates, set up signature fields for others, and include essential metadata. This flexibility makes IronPDF a valuable tool for industries where document integrity is critical, such as finance and healthcare. Let’s explore how to set up IronPDF and utilize its features to sign your PDF documents effectively.

Prerequisites

Before you can start signing PDFs with IronPDF, make sure you have the following prerequisites in place:

  1. Ensure you have a .NET development environment set up. This includes having Visual Studio installed on your machine. You can download Visual Studio from the official website.
  2. A running C# program (Any template)
  3. Have a sample PDF document ready for testing the signing process. This can be any PDF file you want to experiment with.
  4. To sign a PDF, you'll need a digital certificate in .pfx or .p12 format. These contain your public/private key pair and are typically issued by a certificate authority. When using X509Certificate2 for loading certificates, make sure to include X509KeyStorageFlags.Exportable. This flag is crucial; without it, IronPDF won't be able to use the private key to apply the signature, and signing will silently fail or throw errors.
  5. Familiarity with C# programming is essential, as you will be writing code to implement PDF signing functionality.

With these prerequisites in place, you'll be ready to use IronPDF to add digital signatures to your PDF documents, ensuring their authenticity and security.

Step 1: Installing the IronPDF Library

To get started, install the latest stable version of IronPDF (currently 2025.4.4) into your C# project. You can do this using NuGet Package Manager or the Package Manager Console.

Recommended Installation via NuGet Console

Install-Package IronPdf -Version 2025.4.4
Enter fullscreen mode Exit fullscreen mode

This command pulls the latest stable release (as of now) and automatically adds all necessary dependencies.

Dependencies Installed Automatically

When you install IronPDF, the following key dependencies are also included to ensure full functionality:

  • IronPdf.Native.Chrome.Windows – Chrome rendering engine for accurate PDF rendering.
  • IronPdf.Slim – Slimmed-down core library for optimized performance.
  • IronSoftware.Native.PdfModel – Core PDF model library used for internal document structuring.

You don’t need to install these separately, they’re pulled in automatically when using the standard NuGet command above.
Once installed, include these in your code file:

using IronPdf;
using IronPdf.Signing;
using System.Security.Cryptography.X509Certificates;
Enter fullscreen mode Exit fullscreen mode

Step 2: Load PDF Document

IronPDF supports multiple ways to create or load PDF documents. The most modern approach uses the ChromePdfRenderer class, which lets you render HTML directly into a PDF. This is especially useful when generating content on the fly. Here's how to use it:

var renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>Signed PDF</h1>");
Enter fullscreen mode Exit fullscreen mode

If you already have a PDF and just need to load it for signing, you can still use:

PdfDocument pdf = PdfDocument.FromFile(pdfPath);
Enter fullscreen mode Exit fullscreen mode

Choose the method that best fits your use case—whether generating new documents or signing existing ones.

Step 3: Load PDF Signature

After loading your PDF document, the next step is to load and configure the digital signature. IronPDF makes this process straightforward. You can load a signature from a PFX file, configure various properties, and apply it to your PDF.
IronPDF offers several ways to apply digital signatures depending on how your certificate is stored. The recommended approach is to use X509Certificate2, especially if you need more control over security. Here’s an example:

// Path to your PFX file and its password
string pfxPath = @"C:\path\to\Iron.pfx";
string pfxPassword = "123";
var cert = new X509Certificate2(pfxPath, pfxPassword, X509KeyStorageFlags.Exportable);
var signature = new PdfSignature(cert)
{
    SigningContact = "support@ironsoftware.com",
    SigningLocation = "New York, USA",
    SigningReason = "Security Reasons"
};
Enter fullscreen mode Exit fullscreen mode

If you want a quicker method and are okay with default values, you can directly call:

pdf.SignWithFile(pfxPath, pfxPassword);
Enter fullscreen mode Exit fullscreen mode

Or, to sign using a certificate stored in the Windows Certificate Store:

pdf.SignWithStore("‎ab12cd34ef56...");
Enter fullscreen mode Exit fullscreen mode

After loading and configuring the signature, you can proceed to apply it to your PDF document.

Advanced Signature Customization

IronPDF gives you the flexibility to add rich details to your digital signature, helping others verify its origin and purpose. You can include metadata like signing date, reason, and contact info. You can also timestamp the signature using a trusted time server:

signature.SignatureDate = DateTime.UtcNow;
signature.TimestampHashAlgorithm = TimestampHashAlgorithms.SHA256;
signature.TimeStampUrl = "http://timestamp.digicert.com";
Enter fullscreen mode Exit fullscreen mode

Adding a visual image, like a scanned signature, boosts credibility:

int imagePageIndex = 0;
int imageX = 50; // Default X coordinate on the page
int imageY = 50; // Default Y coordinate on the page
int imageWidth = 150; // Default image width
int imageHeight = 75;

Rectangle imageRect = new Rectangle(imageX, imageY, imageWidth, imageHeight);

signature.LoadSignatureImageFromFile("signature.png", imagePageIndex, imageRect);
Enter fullscreen mode Exit fullscreen mode

Or, load it from a stream:

using (FileStream imageStream = new FileStream("signature.png", FileMode.Open, FileAccess.Read))
{
    // Example using AnyBitmap to ensure stream is in a compatible format if needed,
    // though direct stream can work if it's already one of the supported formats.
    // For simplicity, we'll assume the stream from FileStream is directly usable
    // if it's a common format like PNG/JPEG.
    // AnyBitmap anyBmp = AnyBitmap.FromStream(imageStream); // If conversion/validation needed
    // signature.LoadSignatureImageFromStream(anyBmp.ToStream(), imagePageIndex, imageRect);

    signature.LoadSignatureImageFromStream(imageStream, imagePageIndex, imageRect);
    Console.WriteLine("Signature image loaded via LoadSignatureImageFromStream.");
}

Enter fullscreen mode Exit fullscreen mode

Step 4: Apply Signature To PDF Document

After loading and configuring your digital signature, the final step is to apply this signature to your PDF document using IronPDF. This step will make your PDF is digitally signed and secure. Here’s how you can do it:

// Apply the signature to the PDF
pdf.Sign(signature);
Enter fullscreen mode Exit fullscreen mode

Signature Permissions

When signing a PDF, IronPDF lets you define what changes, if any, are permitted after the document has been signed. These permissions help preserve document integrity and control what others can do, like filling in forms or adding annotations.
You apply signature permissions during the signing step by passing a SignaturePermissions value into the Sign() method:

// Sign with permission: allow future form filling and annotations
pdf.Sign(signature, SignaturePermissions.FormFillingAndAnnotationsAllowed);
Enter fullscreen mode Exit fullscreen mode

Available Signature Permissions:

Signature Permission What It Allows After Signing
NoChangesAllowed Completely locks the document.
FormFillingAllowed Only allows filling in form fields.
FormFillingAndAnnotationsAllowed Allows form filling and adding comments/annotations.
AdditionalSignaturesAndFormFillingAllowed Allows additional signatures and form filling.
AdditionalSignaturesFormFillingAndAnnotationsAllowed Allows all: new signatures, form filling, and annotations.

By setting permissions during signing, you control what future edits are valid. If someone makes a disallowed change, the signature will appear invalid.

Step 5: Save the Signed PDF File

After applying the digital signature to your PDF document, the final step is to save the signed PDF to a new file. This ensures that your document is securely stored with its new digital signature. Here’s how you can do it:

// Save the signed PDF to a new file
string signedPdfPath = @"C:\path\to\your\signed_document.pdf";
pdf.SaveAs(signedPdfPath);

// Output message to confirm the signing process
Console.WriteLine("PDF signed and saved successfully!");
Enter fullscreen mode Exit fullscreen mode

This step completes the process of digitally signing a PDF document using IronPDF in C#. Your signed PDF is now saved and ready for use, ensuring its integrity and authenticity.

Verify PDF Digital Signatures

After running the program, the PDF is signed and saved at the specified path. Below is the screenshot of the signed PDF file. You can see the signature details indicating the document has been successfully signed.

Image description
In the screenshot, you can see that the digital signature in the signature field is marked as valid, along with the signing details such as the signer's identity, the location, and the reason for signing. This confirms that the signing process was completed successfully using IronPDF.

Complete Code

Here is the complete code for loading, signing, and saving a PDF document using IronPDF in a C# console application:

using IronPdf;
using IronPdf.Signing;
using System;
using System.Drawing;
using System.IO;
using System.Security.Cryptography.X509Certificates;

class Program
{
    static void Main()
    {
        // Step 1: Load the existing PDF file
        string pdfPath = @"C:\path\to\document.pdf";
        PdfDocument pdf = PdfDocument.FromFile(pdfPath);

        // Step 2: Load the digital certificate from .pfx file
        string pfxPath = @"C:\path\to\Iron.pfx";
        string pfxPassword = "123";

        var cert = new X509Certificate2(pfxPath, pfxPassword, X509KeyStorageFlags.Exportable);

        // Step 3: Create and configure the PDF signature
        var signature = new PdfSignature(cert)
        {
            SigningContact = "support@ironsoftware.com",
            SigningLocation = "New York, USA",
            SigningReason = "Security Reasons",
            SignatureDate = DateTime.UtcNow,
            TimestampHashAlgorithm = TimestampHashAlgorithms.SHA256,
            TimeStampUrl = "http://timestamp.digicert.com"
        };

        // Optional: Add a visual signature image
        int pageIndex = 0;
        Rectangle imageRect = new Rectangle(50, 50, 150, 75); // X, Y, Width, Height
        string imagePath = @"C:\path\to\signature.png";

        if (File.Exists(imagePath))
        {
            signature.LoadSignatureImageFromFile(imagePath, pageIndex, imageRect);
            Console.WriteLine("Visual signature added.");
        }

        // Step 4: Apply the digital signature with permissions
        pdf.Sign(signature, SignaturePermissions.FormFillingAndAnnotationsAllowed);

        // Step 5: Save the signed PDF
        string signedPdfPath = @"C:\path\to\signed_document.pdf";
        pdf.SaveAs(signedPdfPath);

        Console.WriteLine("PDF signed and saved successfully!");
    }
}

Enter fullscreen mode Exit fullscreen mode

Conclusion

Image description
In this guide, we walked through the steps to load, sign, and save a PDF document using IronPDF in a C# console application. By following these steps, you can ensure the authenticity and security of your documents through digital signatures. IronPDF simplifies this process, making it accessible even for those new to handling PDF files programmatically.

IronPDF offers a free trial for developers to explore its features. For long-term use, licenses start at $749, providing access to a robust set of tools for PDF generation and manipulation. For more information and to get started with a free trial, visit the IronPDF website.

Top comments (0)