PDF digital signatures in C# and VB.NET

A digital signature is a security mechanism that ensures the following:

  • The integrity of the document (that the document hasn’t been changed);
  • The authenticity of the document (that the author is who we think he or she is); and
  • Non-repudiation (that the author can’t deny his or her authorship).

With GemBox.Pdf, you can perform the following PDF digital signature scenarios in your C# or VB.NET application:

The following examples demonstrate each of those scenarios.

Digitally sign a PDF file

The following example shows how to add a digital signature to an existing PDF file.

Screenshot of PDF file digitally signed using GemBox.Pdf
PDF file digitally signed using GemBox.Pdf
Upload your file (Drag file here)
using GemBox.Pdf;

class Program
{
    static void Main()
    {
        // If using Professional version, put your serial key below.
        ComponentInfo.SetLicense("FREE-LIMITED-KEY");

        using (var document = PdfDocument.Load("%InputFileName%"))
        {
            // Add an invisible signature field to the PDF document.
            var signatureField = document.Form.Fields.AddSignature();

            // Initiate signing of a PDF file with the specified digital ID file and the password.
            signatureField.Sign("%#GemBoxExampleExplorer.pfx%", "GemBoxPassword");

            // Finish signing of a PDF file.
            document.Save("Digital Signature.pdf");
        }
    }
}
Imports GemBox.Pdf

Module Program

    Sub Main()

        ' If using Professional version, put your serial key below.
        ComponentInfo.SetLicense("FREE-LIMITED-KEY")

        Using document = PdfDocument.Load("%InputFileName%")

            ' Add an invisible signature field to the PDF document.
            Dim signatureField = document.Form.Fields.AddSignature()

            ' Initiate signing of a PDF file with the specified digital ID file and the password.
            signatureField.Sign("%#GemBoxExampleExplorer.pfx%", "GemBoxPassword")

            'Finish signing of a PDF file.
            document.Save("Digital Signature.pdf")
        End Using
    End Sub
End Module

Digital ID file GemBoxExampleExplorer.pfx used in the example is a self-signed digital ID created as explained on the Create a self-signed digital ID page.

To get a valid signature in your Adobe Acrobat Reader as seen in the screenshot from above, you will have to register the self-signed digital ID from the GemBoxExampleExplorer.pfx file as explained on the Register a digital ID page.

Otherwise, to get a valid signature in any Adobe Acrobat Reader, your digital ID would have to be an AATL-enabled signing credential.

The digital signature from the above example is invisible – there is no visual representation of the signature on any of the pages. The next example shows how to create a visible digital signature.

Digitally sign a PDF file with a visible signature

The following example shows how to add a visible digital signature to an existing PDF file.

Screenshot of PDF file with visible digital signature
PDF file with visible digital signature
Upload your file (Drag file here)
using GemBox.Pdf;

class Program
{
    static void Main()
    {
        // If using Professional version, put your serial key below.
        ComponentInfo.SetLicense("FREE-LIMITED-KEY");

        using (var document = PdfDocument.Load("%InputFileName%"))
        {
            // Add a visible signature field to the first page of the PDF document.
            var signatureField = document.Form.Fields.AddSignature(document.Pages[0], 300, 500, 250, 50);

            // Retrieve signature appearance settings to customize it.
            var signatureAppearance = signatureField.Appearance;

            // Show 'Reason' label and value.
            signatureAppearance.Reason = "Legal agreement";
            // Show 'Location' label and value.
            signatureAppearance.Location = "New York, USA";
            // Do not show 'Date' label nor value.
            signatureAppearance.DateFormat = string.Empty;

            // Initiate signing of a PDF file with the specified digital ID file and the password.
            signatureField.Sign("%#GemBoxExampleExplorer.pfx%", "GemBoxPassword");

            // Finish signing of a PDF file.
            document.Save("Visible Digital Signature.pdf");
        }
    }
}
Imports GemBox.Pdf

Module Program

    Sub Main()

        ' If using Professional version, put your serial key below.
        ComponentInfo.SetLicense("FREE-LIMITED-KEY")

        Using document = PdfDocument.Load("%InputFileName%")

            ' Add a visible signature field to the first page of the PDF document.
            Dim signatureField = document.Form.Fields.AddSignature(document.Pages(0), 300, 500, 250, 50)

            ' Retrieve signature appearance settings to customize it.
            Dim signatureAppearance = signatureField.Appearance

            ' Show 'Reason' label and value.
            signatureAppearance.Reason = "Legal agreement"
            ' Show 'Location' label and value.
            signatureAppearance.Location = "New York, USA"
            ' Do not show 'Date' label nor value.
            signatureAppearance.DateFormat = String.Empty

            ' Initiate signing of a PDF file with the specified digital ID file and the password.
            signatureField.Sign("%#GemBoxExampleExplorer.pfx%", "GemBoxPassword")

            'Finish signing of a PDF file.
            document.Save("Visible Digital Signature.pdf")
        End Using
    End Sub
End Module

Signature appearance settings represented by PdfSignatureAppearance class enable you to show several predefined labels related to digital signatures and their values and to localize the labels. Support for images and more complex signature appearances will be implemented in future versions of GemBox.Pdf.

Previous examples showed how to apply a single digital signature. The next example shows how to apply more than one digital signature to an existing PDF file.

Digitally sign a PDF file with multiple signatures

The following example shows how to add multiple digital signatures to an existing PDF file.

Screenshot of PDF file with multiple digital signatures
PDF file with multiple digital signatures
Upload your file (Drag file here)
using GemBox.Pdf;

class Program
{
    static void Main()
    {
        // If using Professional version, put your serial key below.
        ComponentInfo.SetLicense("FREE-LIMITED-KEY");

        using (var document = PdfDocument.Load("%InputFileName%"))
        {
            // Add a first signature field to the first page of the PDF document.
            var signatureField1 = document.Form.Fields.AddSignature(document.Pages[0], 100, 500, 200, 50);

            // Initiate first signing of a PDF file with the specified digital ID file and the password.
            signatureField1.Sign("%#JohnDoe.pfx%", "JohnDoePassword");

            // Finish first signing of a PDF file.
            document.Save("Multiple Digital Signature.pdf");

            // Add a second signature field to the first page of the PDF document.
            var signatureField2 = document.Form.Fields.AddSignature(document.Pages[0], 300, 500, 250, 50);

            // Initiate second signing of a PDF file with the specified digital ID file and the password.
            signatureField2.Sign("%#GemBoxExampleExplorer.pfx%", "GemBoxPassword");

            // Finish second signing of a same PDF file.
            document.Save();
        }
    }
}
Imports GemBox.Pdf

Module Program

    Sub Main()

        ' If using Professional version, put your serial key below.
        ComponentInfo.SetLicense("FREE-LIMITED-KEY")

        Using document = PdfDocument.Load("%InputFileName%")

            ' Add a first signature field to the first page of the PDF document.
            Dim signatureField1 = document.Form.Fields.AddSignature(document.Pages(0), 100, 500, 200, 50)

            ' Initiate first signing of a PDF file with the specified digital ID file and the password.
            signatureField1.Sign("%#JohnDoe.pfx%", "JohnDoePassword")

            ' Finish first signing of a PDF file.
            document.Save("Multiple Digital Signature.pdf")

            ' Add a second signature field to the first page of the PDF document.
            Dim signatureField2 = document.Form.Fields.AddSignature(document.Pages(0), 300, 500, 250, 50)

            ' Initiate second signing of a PDF file with the specified digital ID file and the password.
            signatureField2.Sign("%#GemBoxExampleExplorer.pfx%", "GemBoxPassword")

            ' Finish second signing of a same PDF file.
            document.Save()
        End Using
    End Sub
End Module

Digital ID file JohnDoe.pfx used in the example is a self-signed digital ID and the same notes related to self-signed digital IDs applicable to GemBoxExampleExplorer.pfx in the first example are applied to it.

As shown in the screenshot from above, the PDF file contains two revisions.

The first revision contains the original PDF document content and John Doe's signature and is created by using the PdfDocument.Save(System.String) method overload.

The second revision contains the GemBox Example Explorer's signature and is appended to the same PDF file by using a parameterless PdfDocument.Save() method overload.

This file structure is normal because PDF supports multiple digital signatures only through multiple revisions by appending additional signatures to an already signed PDF file.

Digitally sign a PDF file with an external signature

The following example shows how to add an external digital signature to an existing PDF file.

Upload your file (Drag file here)
using System;
using System.Security.Cryptography;
using System.Security.Cryptography.Pkcs;
using System.Security.Cryptography.X509Certificates;
using GemBox.Pdf;
using GemBox.Pdf.Forms;

class Program
{
    static void Main()
    {
        // If using Professional version, put your serial key below.
        ComponentInfo.SetLicense("FREE-LIMITED-KEY");

        using (var document = PdfDocument.Load("%InputFileName%"))
        {
            // Add an invisible signature field to the PDF document.
            var signatureField = document.Form.Fields.AddSignature();

            // Change the value based on your signature's size.
            int estimatedSignatureContentsLength = 2199;

            // Initiate signing of a PDF file with the specified signer delegate.
            signatureField.Sign(pdfFileStream =>
            {
                // Create a signed CMS object using the content that should be signed,
                // but not included in the signed CMS object (detached: true).
                var content = new byte[pdfFileStream.Length];
                pdfFileStream.Read(content, 0, content.Length);
                var signedCms = new SignedCms(new ContentInfo(content), detached: true);

                X509Certificate2 certificate = null;
                try
                {
                    // Compute the signature using the specified digital ID file and the password.
                    certificate = new X509Certificate2("%#GemBoxExampleExplorer.pfx%", "GemBoxPassword");
                    var cmsSigner = new CmsSigner(certificate);
                    cmsSigner.DigestAlgorithm = new Oid("2.16.840.1.101.3.4.2.1"); // SHA256
                    signedCms.ComputeSignature(cmsSigner);
                }
                finally
                {
                    // Starting with the .NET Framework 4.6, this type implements the IDisposable interface.
                    (certificate as IDisposable)?.Dispose();
                }

                // Return the signature encoded into a CMS/PKCS #7 message.
                return signedCms.Encode();

            }, PdfSignatureFormat.PKCS7, estimatedSignatureContentsLength);

            // Finish signing of a PDF file.
            document.Save("External Digital Signature.pdf");
        }
    }
}
Imports System
Imports System.Security.Cryptography
Imports System.Security.Cryptography.Pkcs
Imports System.Security.Cryptography.X509Certificates
Imports GemBox.Pdf
Imports GemBox.Pdf.Forms

Module Program

    Sub Main()

        ' If using Professional version, put your serial key below.
        ComponentInfo.SetLicense("FREE-LIMITED-KEY")

        Using document = PdfDocument.Load("%InputFileName%")

            ' Add an invisible signature field to the PDF document.
            Dim signatureField = document.Form.Fields.AddSignature()

            ' Change the value based on your signature's size.
            Dim estimatedSignatureContentsLength As Integer = 2199

            ' Initiate signing of a PDF file with the specified signer delegate.
            signatureField.Sign(
                Function(pdfFileStream)
                    ' Create a signed CMS object using the content that should be signed,
                    ' but not included in the signed CMS object (detached: true).
                    Dim content = New Byte(CInt(pdfFileStream.Length) - 1) {}
                    pdfFileStream.Read(content, 0, content.Length)
                    Dim signedCms = New SignedCms(New ContentInfo(content), detached:=True)

                    Dim certificate As X509Certificate2 = Nothing
                    Try

                        ' Compute the signature using the specified digital ID file and the password.
                        certificate = New X509Certificate2("%#GemBoxExampleExplorer.pfx%", "GemBoxPassword")
                        Dim cmsSigner = New CmsSigner(certificate)
                        cmsSigner.DigestAlgorithm = New Oid("2.16.840.1.101.3.4.2.1") ' SHA256
                        signedCms.ComputeSignature(cmsSigner)

                    Finally

                        ' Starting with the .NET Framework 4.6, this type implements the IDisposable interface.
                        TryCast(certificate, IDisposable)?.Dispose()
                    End Try

                    ' Return the signature encoded into a CMS/PKCS #7 message.
                    Return signedCms.Encode()

                End Function, PdfSignatureFormat.PKCS7, estimatedSignatureContentsLength)

            ' Finish signing of a PDF file.
            document.Save("External Digital Signature.pdf")
        End Using
    End Sub
End Module

The external signature created in the example is in PKCS #7 (CMS) format and is created by using classes from System.Security.Cryptography.Pkcs namespace, which can also be used in .NET Standard project by adding reference to a System.Security.Cryptography.Pkcs NuGet package.

Using the same technique, an external signature can be created from various sources such as HSM, USB token, smart card or service.

Remove existing digital signatures from a PDF file

The following example shows how to remove existing digital signatures from a PDF file.

Screenshot of PDF file with removed digital signature
PDF file with removed digital signature
Upload your file (Drag file here)
using System.Linq;
using GemBox.Pdf;
using GemBox.Pdf.Forms;

class Program
{
    static void Main()
    {
        // If using Professional version, put your serial key below.
        ComponentInfo.SetLicense("FREE-LIMITED-KEY");

        using (var document = PdfDocument.Load("%InputFileName%"))
        {
            // Get a list of all signature fields in the document.
            var signatureFields = document.Form.Fields.
                Where(f => f.FieldType == PdfFieldType.Signature).
                Cast<PdfSignatureField>().
                ToList();

            // Either remove the signature or the signature field.
            for (int i = 0; i < signatureFields.Count; ++i)
                if (i % 2 == 0)
                    signatureFields[i].Value = null;
                else
                    document.Form.Fields.Remove(signatureFields[i]);

            document.Save("Remove Digital Signature.pdf");
        }
    }
}
Imports System.Linq
Imports GemBox.Pdf
Imports GemBox.Pdf.Forms

Module Program

    Sub Main()

        ' If using Professional version, put your serial key below.
        ComponentInfo.SetLicense("FREE-LIMITED-KEY")

        Using document = PdfDocument.Load("%InputFileName%")

            ' Get a list of all signature fields in the document.
            Dim signatureFields = document.Form.Fields.
                Where(Function(f) f.FieldType = PdfFieldType.Signature).
                Cast(Of PdfSignatureField)().
                ToList()

            ' Either remove the signature or the signature field.
            For i As Integer = 0 To signatureFields.Count - 1
                If i Mod 2 = 0 Then
                    signatureFields(i).Value = Nothing
                Else
                    document.Form.Fields.Remove(signatureFields(i))
                End If
            Next

            document.Save("Remove Digital Signature.pdf")
        End Using
    End Sub
End Module

There are two ways to remove an existing signature from a PDF file:

  • Remove the signature. This will keep the signature field and its widget annotation (visual appearance placeholder). The signature field can be reused for a new signature.
  • Remove the signature field. This will also remove the field's widget annotation from the page.

Check next example or download examples from GitHub.