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:

Before reviewing the output of the following examples in your Adobe Acrobat Reader, please read the Digital ID notes.

Before running any of the following examples on your machine, please read the Dependencies notes.

Digitally sign a PDF file

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

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

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();

            // Get a digital ID from PKCS#12/PFX file.
            var digitalId = new PdfDigitalId("%InputDigitalId[0]%", "GemBoxPassword");

            // Create a PDF signer that will create the digital signature.
            var signer = new PdfSigner(digitalId);

            // Adobe Acrobat Reader currently doesn't download certificate chain
            // so we will also embed certificate of intermediate Certificate Authority in the signature.
            // (see https://community.adobe.com/t5/acrobat/signature-validation-using-aia-extension-not-enabled-by-default/td-p/10729647)
            signer.ValidationInfo = new PdfSignatureValidationInfo(new PdfCertificate[] { new PdfCertificate("%InputDigitalId[1]%") }, null, null);

            // Initiate signing of a PDF file with the specified signer.
            signatureField.Sign(signer);

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

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()

            ' Get a digital ID from PKCS#12/PFX file.
            Dim digitalId = New PdfDigitalId("%InputDigitalId[0]%", "GemBoxPassword")

            ' Create a PDF signer that will create the digital signature.
            Dim signer = New PdfSigner(digitalId)

            ' Adobe Acrobat Reader currently doesn't download certificate chain
            ' so we will also embed certificate of intermediate Certificate Authority in the signature.
            ' (see https://community.adobe.com/t5/acrobat/signature-validation-using-aia-extension-not-enabled-by-default/td-p/10729647)
            signer.ValidationInfo = New PdfSignatureValidationInfo(New PdfCertificate() {New PdfCertificate("%InputDigitalId[1]%")}, Nothing, Nothing)

            ' Initiate signing of a PDF file with the specified signer.
            signatureField.Sign(signer)

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

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.

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

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;

            // Set font family.
            signatureAppearance.FontFamily = new PdfFontFamily("Times New Roman");
            // Show 'Reason' label and value.
            signatureAppearance.Reason = "Legal agreement between the seller and the buyer about the purchase";
            // Show 'Location' label and value.
            signatureAppearance.Location = "New York, USA";
            // Do not show 'Date' label nor value.
            signatureAppearance.DateFormat = string.Empty;
            // Shrink text if it overflows signature field's annotation rectangle.
            signatureAppearance.ShrinkTextOnOverflow = true;

            // Get a digital ID from PKCS#12/PFX file.
            var digitalId = new PdfDigitalId("%InputDigitalId[0]%", "GemBoxPassword");

            // Create a PDF signer that will create the digital signature.
            var signer = new PdfSigner(digitalId);

            // Adobe Acrobat Reader currently doesn't download certificate chain
            // so we will also embed certificate of intermediate Certificate Authority in the signature.
            // (see https://community.adobe.com/t5/acrobat/signature-validation-using-aia-extension-not-enabled-by-default/td-p/10729647)
            signer.ValidationInfo = new PdfSignatureValidationInfo(new PdfCertificate[] { new PdfCertificate("%InputDigitalId[1]%") }, null, null);

            // Initiate signing of a PDF file with the specified signer.
            signatureField.Sign(signer);

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

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

            ' Set font family.
            signatureAppearance.FontFamily = New PdfFontFamily("Times New Roman")
            ' Show 'Reason' label and value.
            signatureAppearance.Reason = "Legal agreement between the seller and the buyer about the purchase"
            ' Show 'Location' label and value.
            signatureAppearance.Location = "New York, USA"
            ' Do not show 'Date' label nor value.
            signatureAppearance.DateFormat = String.Empty
            ' Shrink text if it overflows signature field's annotation rectangle.
            signatureAppearance.ShrinkTextOnOverflow = True

            ' Get a digital ID from PKCS#12/PFX file.
            Dim digitalId = New PdfDigitalId("%InputDigitalId[0]%", "GemBoxPassword")

            ' Create a PDF signer that will create the digital signature.
            Dim signer = New PdfSigner(digitalId)

            ' Adobe Acrobat Reader currently doesn't download certificate chain
            ' so we will also embed certificate of intermediate Certificate Authority in the signature.
            ' (see https://community.adobe.com/t5/acrobat/signature-validation-using-aia-extension-not-enabled-by-default/td-p/10729647)
            signer.ValidationInfo = New PdfSignatureValidationInfo(New PdfCertificate() {New PdfCertificate("%InputDigitalId[1]%")}, Nothing, Nothing)

            ' Initiate signing of a PDF file with the specified signer.
            signatureField.Sign(signer)

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

Signature appearance settings represented by the 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.

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

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);

            // Get a first digital ID from PKCS#12/PFX file.
            var digitalId1 = new PdfDigitalId("%InputDigitalId1[0]%", "GemBoxPassword");

            // Create a PDF signer that will create the first signature.
            var signer1 = new PdfSigner(digitalId1);

            // Adobe Acrobat Reader currently doesn't download certificate chain
            // so we will also embed certificate of intermediate Certificate Authority in the signature.
            // (see https://community.adobe.com/t5/acrobat/signature-validation-using-aia-extension-not-enabled-by-default/td-p/10729647)
            signer1.ValidationInfo = new PdfSignatureValidationInfo(new PdfCertificate[] { new PdfCertificate("%InputDigitalId1[1]%") }, null, null);

            // Initiate first signing of a PDF file with the specified signer.
            signatureField1.Sign(signer1);

            // 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);

            // Get a second digital ID from PKCS#12/PFX file.
            var digitalId2 = new PdfDigitalId("%InputDigitalId2[0]%", "GemBoxPassword");

            // Create a PDF signer that will create the second signature.
            var signer2 = new PdfSigner(digitalId2);

            // Adobe Acrobat Reader currently doesn't download certificate chain
            // so we will also embed certificate of intermediate Certificate Authority in the signature.
            // (see https://community.adobe.com/t5/acrobat/signature-validation-using-aia-extension-not-enabled-by-default/td-p/10729647)
            signer2.ValidationInfo = new PdfSignatureValidationInfo(new PdfCertificate[] { new PdfCertificate("%InputDigitalId2[1]%") }, null, null);

            // Initiate second signing of a PDF file with the specified signer.
            signatureField2.Sign(signer2);

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

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)

            ' Get a first digital ID from PKCS#12/PFX file.
            Dim digitalId1 = New PdfDigitalId("%InputDigitalId1[0]%", "GemBoxPassword")

            ' Create a PDF signer that will create the first signature.
            Dim signer1 = New PdfSigner(digitalId1)

            ' Adobe Acrobat Reader currently doesn't download certificate chain
            ' so we will also embed certificate of intermediate Certificate Authority in the signature.
            ' (see https://community.adobe.com/t5/acrobat/signature-validation-using-aia-extension-not-enabled-by-default/td-p/10729647)
            signer1.ValidationInfo = New PdfSignatureValidationInfo(New PdfCertificate() {New PdfCertificate("%InputDigitalId1[1]%")}, Nothing, Nothing)

            ' Initiate first signing of a PDF file with the specified signer.
            signatureField1.Sign(signer1)

            ' 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)

            ' Get a second digital ID from PKCS#12/PFX file.
            Dim digitalId2 = New PdfDigitalId("%InputDigitalId2[0]%", "GemBoxPassword")

            ' Create a PDF signer that will create the second signature.
            Dim signer2 = New PdfSigner(digitalId2)

            ' Adobe Acrobat Reader currently doesn't download certificate chain
            ' so we will also embed certificate of intermediate Certificate Authority in the signature.
            ' (see https://community.adobe.com/t5/acrobat/signature-validation-using-aia-extension-not-enabled-by-default/td-p/10729647)
            signer2.ValidationInfo = New PdfSignatureValidationInfo(New PdfCertificate() {New PdfCertificate("%InputDigitalId2[1]%")}, Nothing, Nothing)

            ' Initiate second signing of a PDF file with the specified signer.
            signatureField2.Sign(signer2)

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

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

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

The second revision contains the second 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.

PDF file with externally created digital signature
Screenshot of PDF file with externally created digital signature
Upload your file (Drag file here)
using GemBox.Pdf;
using GemBox.Pdf.Forms;
using GemBox.Pdf.Security;

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);

            // Get a digital ID from XML (private key) and certificate files.
            var digitalId = new RSAXmlDigitalId("%#GemBoxRSA1024PrivateKey.xml%", "%#GemBoxRSA1024.crt%");

            // Create a PDF signer that will create the digital signature.
            var signer = new PdfSigner(digitalId);

            // Adobe Acrobat Reader currently doesn't download certificate chain
            // so we will also embed certificate of intermediate Certificate Authority in the signature.
            // (see https://community.adobe.com/t5/acrobat/signature-validation-using-aia-extension-not-enabled-by-default/td-p/10729647)
            signer.ValidationInfo = new PdfSignatureValidationInfo(new PdfCertificate[] { new PdfCertificate("%#GemBoxRSA.crt%") }, null, null);

            // Initiate signing of a PDF file with the specified signer.
            signatureField.Sign(signer);

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

/// <summary>
/// Represents a digital ID that reads an RSA private key from an XML file.
/// </summary>
class RSAXmlDigitalId : PdfDigitalId
{
    private readonly string privateKeyXmlString;

    public RSAXmlDigitalId(string privateKeyXmlFileName, string certificateFileName) : base(new PdfCertificate(certificateFileName))
    {
        this.privateKeyXmlString = System.IO.File.ReadAllText(privateKeyXmlFileName);
    }

    protected override byte[] SignHash(byte[] hash, PdfHashAlgorithm hashAlgorithm, PdfRSASignaturePadding rsaSignaturePadding)
    {
        using (var rsa = System.Security.Cryptography.RSA.Create())
        {
            rsa.FromXmlString(this.privateKeyXmlString);

            return rsa.SignHash(
                hash,
                new System.Security.Cryptography.HashAlgorithmName(hashAlgorithm.ToString()),
                rsaSignaturePadding == PdfRSASignaturePadding.Pss ? System.Security.Cryptography.RSASignaturePadding.Pss : System.Security.Cryptography.RSASignaturePadding.Pkcs1);
        }
    }
}
Imports GemBox.Pdf
Imports GemBox.Pdf.Forms
Imports GemBox.Pdf.Security

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)

            ' Get a digital ID from XML (private key) and certificate files.
            Dim digitalId = New RSAXmlDigitalId("%#GemBoxRSA1024PrivateKey.xml%", "%#GemBoxRSA1024.crt%")

            ' Create a PDF signer that will create the digital signature.
            Dim signer = New PdfSigner(digitalId)

            ' Adobe Acrobat Reader currently doesn't download certificate chain
            ' so we will also embed certificate of intermediate Certificate Authority in the signature.
            ' (see https://community.adobe.com/t5/acrobat/signature-validation-using-aia-extension-not-enabled-by-default/td-p/10729647)
            signer.ValidationInfo = New PdfSignatureValidationInfo(New PdfCertificate() {New PdfCertificate("%#GemBoxRSA.crt%")}, Nothing, Nothing)

            ' Initiate signing of a PDF file with the specified signer.
            signatureField.Sign(signer)

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

''' <summary>
''' Represents a digital ID that reads an RSA private key from an XML file.
''' </summary>
Class RSAXmlDigitalId
    Inherits PdfDigitalId
    Private ReadOnly privateKeyXmlString As String

    Public Sub New(ByVal privateKeyXmlFileName As String, ByVal certificateFileName As String)
        MyBase.New(New PdfCertificate(certificateFileName))
        Me.privateKeyXmlString = System.IO.File.ReadAllText(privateKeyXmlFileName)
    End Sub

    Protected Overrides Function SignHash(ByVal hash As Byte(), ByVal hashAlgorithm As PdfHashAlgorithm, ByVal rsaSignaturePadding As PdfRSASignaturePadding) As Byte()

        Using rsa = System.Security.Cryptography.RSA.Create()

            rsa.FromXmlString(Me.privateKeyXmlString)

            Return rsa.SignHash(
                hash,
                New System.Security.Cryptography.HashAlgorithmName(hashAlgorithm.ToString()),
                If(rsaSignaturePadding = PdfRSASignaturePadding.Pss, System.Security.Cryptography.RSASignaturePadding.Pss, System.Security.Cryptography.RSASignaturePadding.Pkcs1))
        End Using
    End Function
End Class

The external signature is created by the RSAXmlDigitalId class that, for demonstration purposes, reads the RSA private key parameters from an XML file and uses an instance of a System.Security.Cryptography.RSA class to do the actual signing.

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

Remove existing digital signatures from a PDF file

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

PDF file with removed digital signature
Screenshot of 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.

Digital ID notes

Digital ID files used in the preceding examples are part of a simple Public Key Infrastructure (PKI) created just for this demonstration which contains the following hierarchy of certificates and CRLs:

To get a valid signature in your Adobe Acrobat Reader as seen in the screenshots above, you will have to add GemBoxCA.crt certificate to the list of Trusted Certificates using the following steps:

  1. Download GemBoxCA.crt certificate.
  2. Open Adobe Acrobat Reader, select Edit > Preferences > Signatures. In Identities & Trusted Certificates click More.
  3. Select Trusted Certificates and click Import. Browse to the downloaded GemBoxCA.crt certificate and click Import.
  4. Select the imported GemBoxCA <info@gemboxsofware.com> certificate, click Edit Trust and add a check-mark next to Use this certificate as a trusted root.
  5. You can now delete the downloaded GemBoxCA.crt certificate. You can always later remove GemBoxCA <info@gemboxsofware.com> from Trusted Certificates by selecting it from the list of Trusted Certificates and clicking Remove.

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

Dependencies notes

Except GemBox.Pdf, your project should reference the following NuGet packages:

Want more?

Next example GitHub

Check the next example or select an example from the menu. You can also download our examples from the GitHub.


Like it?

Download Buy

If you want to try the GemBox.Pdf yourself, you can download the free version. It delivers the same performance and set of features as the professional version, but with some operations limited. To remove the limitation, you need to purchase a license.