Create a digitally signed PDF in C# and VB.NET

PDF digital signature enables you to authenticate a document to establish that the sender of the document is who they say they are and that the content of the document has not been tampered with.

GemBox.Document will digitally sign a PDF file with the private key and the associated X.509 certificate if either Certificate, CertificateBytes or CertificatePath is specified.

If you require to digitally sign a PDF file with multiple signatures or using a PKCS#11/Cryptoki device (for example, HSM, USB token or smart card) or a web service, take a look at this alternative approach for digitally signing PDF files using GemBox.Pdf.

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

The following example shows how you can create a digitally signed PDF file in C# and VB.NET, with visual representation.

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

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

        var document = DocumentModel.Load("%InputFileName%");

        // Create visual representation of digital signature.
        var signature = new Picture(document, "%#GemBoxSignature.png%");

        // Position signature image at the end of the document.
        var lastSection = document.Sections[document.Sections.Count - 1];
        lastSection.Blocks.Add(new Paragraph(document, signature));

        var options = new PdfSaveOptions()
        {
            DigitalSignature =
            {
                CertificatePath = "%InputDigitalId%",
                CertificatePassword = "GemBoxPassword",
                Signature = signature,
                IsAdvancedElectronicSignature = true
            }
        };

        document.Save("PDF Digital Signature.pdf", options);
    }
}
Imports GemBox.Document

Module Program

    Sub Main()

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

        Dim document = DocumentModel.Load("%InputFileName%")

        ' Create visual representation of digital signature.
        Dim signature As New Picture(document, "%#GemBoxSignature.png%")

        ' Position signature image at the end of the document.
        Dim lastSection = document.Sections(document.Sections.Count - 1)
        lastSection.Blocks.Add(New Paragraph(document, signature))

        Dim options As New PdfSaveOptions() With
        {
            .DigitalSignature = New PdfDigitalSignatureSaveOptions() With
            {
                .CertificatePath = "%InputDigitalId%",
                .CertificatePassword = "GemBoxPassword",
                .Signature = signature,
                .IsAdvancedElectronicSignature = True
            }
        }

        document.Save("PDF Digital Signature.pdf", options)
    End Sub
End Module

To get a valid signature in your Adobe Acrobat Reader as seen in the screenshot above, you will have to add either GemBoxRSA.crt or GemBoxECDsa.crt certificate to the list of Trusted Certificates as described in the Digital ID notes.

This is required because Adobe Acrobat Reader currently doesn't download certificate chain.

The next example shows another solution for this by using GemBox.Document and GemBox.Pdf components together to create PDF Advanced Electronic Signature (PAdES) of B-LTA level that embeds all validation-related information in the PDF file thus making the signature LTV enabled.

PAdES signature (LTV enabled)

PDF Advanced Electronic Signature (PAdES) is an electronic signature in a PDF file that has met the requirements set forth by the eIDAS regulation on electronic identification and trust services for electronic transactions in the European Single Market.

With GemBox.Document and GemBox.Pdf, you can create PAdES baseline signatures as specified in ETSI EN 319 142-1.

The following example shows how to create a digitally signed PDF file with PAdES B-LTA level signature.

PDF file with PAdES B-LTA level signature created with GemBox.Document and GemBox.Pdf
Screenshot of PDF file with PAdES B-LTA level signature created with GemBox.Document and GemBox.Pdf
Upload your file (Drag file here)
using GemBox.Document;
using GemBox.Pdf.Forms;
using GemBox.Pdf.Security;

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

        var document = DocumentModel.Load("%InputFileName%");

        // Create visual representation of digital signature.
        var signature = new Picture(document, "%#GemBoxSignature.png%");

        // Position signature image at the end of the document.
        var lastSection = document.Sections[document.Sections.Count - 1];
        lastSection.Blocks.Add(new Paragraph(document, signature));

        // If using the Professional version, put your serial key below.
        GemBox.Pdf.ComponentInfo.SetLicense("FREE-LIMITED-KEY");

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

        // Create a PDF signer that will create PAdES B-LTA level signature.
        var signer = new PdfSigner(digitalId);

        // PdfSigner should create CAdES-equivalent signature.
        signer.SignatureFormat = PdfSignatureFormat.CAdES;

        // PdfSigner will embed a timestamp created by freeTSA.org Time Stamp Authority in the signature.
        signer.Timestamper = new PdfTimestamper("https://freetsa.org/tsr");

        // Make sure that all properties specified on PdfSigner are according to PAdES B-LTA level.
        signer.SignatureLevel = PdfSignatureLevel.PAdES_B_LTA;

        // Inject PdfSigner from GemBox.Pdf into
        // PdfDigitalSignatureSaveOptions from GemBox.Document.
        var signatureOptions = PdfDigitalSignatureSaveOptions.FromSigner(
            () => signer.SignatureFormat.ToString(),
            () => signer.EstimatedSignatureContentsLength,
            signer.ComputeSignature);

        signatureOptions.Signature = signature;

        var options = new PdfSaveOptions()
        {
            DigitalSignature = signatureOptions
        };

        document.Save("PAdES B-LTA.pdf", options);

        using (var pdfDocument = GemBox.Pdf.PdfDocument.Load("PAdES B-LTA.pdf"))
        {
            var signatureField = (PdfSignatureField)pdfDocument.Form.Fields[0];

            // Download validation-related information for the signature and the signature's timestamp and embed it in the PDF file.
            // This will make the signature "LTV enabled".
            pdfDocument.SecurityStore.AddValidationInfo(signatureField.Value);

            // Add an invisible signature field to the PDF document that will hold the document timestamp.
            var timestampField = pdfDocument.Form.Fields.AddSignature();

            // Initiate timestamping of a PDF file with the specified timestamper.
            timestampField.Timestamp(signer.Timestamper);

            // Save any changes done to the PDF file that were done since the last time Save was called and
            // finish timestamping of a PDF file.
            pdfDocument.Save();
        }
    }
}
Imports GemBox.Document
Imports GemBox.Pdf.Forms
Imports GemBox.Pdf.Security

Module Program

    Sub Main()

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

        Dim document = DocumentModel.Load("%InputFileName%")

        ' Create visual representation of digital signature.
        Dim signature As New Picture(document, "%#GemBoxSignature.png%")

        ' Position signature image at the end of the document.
        Dim lastSection = document.Sections(document.Sections.Count - 1)
        lastSection.Blocks.Add(New Paragraph(document, signature))

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

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

        ' Create a PDF signer that will create PAdES B-LTA level signature.
        Dim signer = New PdfSigner(digitalId)

        ' PdfSigner should create CAdES-equivalent signature.
        signer.SignatureFormat = PdfSignatureFormat.CAdES

        ' PdfSigner will embed a timestamp created by freeTSA.org Time Stamp Authority in the signature.
        signer.Timestamper = New PdfTimestamper("https://freetsa.org/tsr")

        ' Make sure that all properties specified on PdfSigner are according to PAdES B-LTA level.
        signer.SignatureLevel = PdfSignatureLevel.PAdES_B_LTA

        ' Inject PdfSigner from GemBox.Pdf into
        ' PdfDigitalSignatureSaveOptions from GemBox.Document.
        Dim signatureOptions = PdfDigitalSignatureSaveOptions.FromSigner(
            Function() signer.SignatureFormat.ToString(),
            Function() signer.EstimatedSignatureContentsLength,
            Function(pdfFileStream) signer.ComputeSignature(pdfFileStream))

        signatureOptions.Signature = signature

        Dim options = New PdfSaveOptions() With
        {
            .DigitalSignature = signatureOptions
        }

        document.Save("PAdES B-LTA.pdf", options)

        Using pdfDocument = GemBox.Pdf.PdfDocument.Load("PAdES B-LTA.pdf")

            Dim signatureField = CType(pdfDocument.Form.Fields(0), PdfSignatureField)

            ' Download validation-related information for the signature and the signature's timestamp and embed it in the PDF file.
            ' This will make the signature "LTV enabled".
            pdfDocument.SecurityStore.AddValidationInfo(signatureField.Value)

            ' Add an invisible signature field to the PDF document that will hold the document timestamp.
            Dim timestampField = pdfDocument.Form.Fields.AddSignature()

            ' Initiate timestamping of a PDF file with the specified timestamper.
            timestampField.Timestamp(signer.Timestamper)

            ' Save any changes done to the PDF file that were done since the last time Save was called and
            ' finish timestamping of a PDF file.
            pdfDocument.Save()
        End Using
    End Sub
End Module

PAdES B-LTA level signature has the following characteristics:

  • PDF digital signature is an advanced electronic signature and includes the signer's certificate.
  • PDF digital signature has a time-stamp, respectively a time-mark that proves that the signature existed at a certain date and time.
  • Validation-related information (OCSP responses or CRLs and all certificates of the certificate chain, from the signer's certificate to the root CA certificate) for the signature is added to the Document Security Store (DSS) of a PDF document.
  • Validation-related information for the signature's time-stamp is added to the DSS and a document time stamp to the PDF document.

PAdES B-LTA level may help to validate the signature beyond any event that may limit its validity. This level is recommended for Qualified Electronic Signatures.

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.

Time-stamp notes

The Time Stamp Authority used in the preceding example is freeTSA.org.

The root certificate of the freeTSA.org Public Key Infrastructure (PKI) is tsa.crt.

To get a valid signature timestamp in your Adobe Acrobat Reader as seen in the screenshot above, you will have to add the tsa.crt certificate to the list of Trusted Certificates using the same steps as in the previous subsection.

See also


Next steps

GemBox.Document is a .NET component that enables you to read, write, edit, convert, and print document files from your .NET applications using one simple API. How about testing it today?

Download Buy