Skip to main content
You are viewing help content for pre-release software. This document and the features it describes are subject to change.
All docs
V26.2
  • Sign PDF Documents with the New DevExpress PDF Document API

    • 16 minutes to read

    The DevExpress PDF Document API allows you to sign PDF documents with X.509 certificates. A digital signature verifies the signer’s identity and confirms that the document has not changed after it was signed. You can also read signature information from a document and validate existing signatures.

    Signature Basics

    A signature is stored in a SignatureField. The field is bound to a SignatureWidgetAnnotation that defines where the signature appears on a page. You can sign a field that you create in code or a field that already exists in the document. A document can contain multiple signatures.

    The following APIs are used to sign documents:

    API Description
    SignatureOptions Contains the signature certificate, hash algorithm, signer information, and certification level.
    PdfDocument.AddSignature(SignatureField, SignatureOptions) Signs the specified field with a PKCS#7 signature based on the specified options.
    Pkcs7DocumentSigner Creates a PKCS#7 signature with additional settings: a timestamp and a signature profile (PDF or PAdES).
    PdfDocument.AddSignature(SignatureField, DocumentSigner) Signs the specified field with the specified signer.
    PdfDocument.Save(stream, options) Saves the signed document. Pass a SaveOptions object to specify the save mode.

    Create and Sign a Signature Field

    Follow the steps below to add a signature field to a document and sign it:

    1. Create a SignatureField object and add it to the PdfDocument.Fields collection.
    2. Create a SignatureWidgetAnnotation object to display the field on a page. Pass the field and the widget bounds to the widget’s constructor. Add the widget to the page’s Annotations collection.
    3. Create a SignatureOptions object. Assign the signing certificate to the Certificate property and specify signer information.
    4. Call the PdfDocument.AddSignature method and pass the field and options to it.
    5. Save the document.

    Refer to the following section for information about the coordinate system used to specify widget bounds: Coordinate System and Units.

    The following code snippet signs a new signature field with a certificate stored in a PFX file:

    using DevExpress.Docs.Pdf;
    using System.Drawing;
    using System.IO;
    using System.Security.Cryptography.X509Certificates;
    
    using (PdfDocument pdfDocument = new PdfDocument(File.OpenRead("Document.pdf"))) {
        // Create a signature field and add it to the field collection.
        SignatureField signatureField = new SignatureField("Signature1");
        pdfDocument.Fields.Add(signatureField);
    
        // Bind the field to a widget on the first page.
        SignatureWidgetAnnotation signatureWidget =
            new SignatureWidgetAnnotation(signatureField, new RectangleF(20, 400, 200, 60));
        pdfDocument.Pages[0].Annotations.Add(signatureWidget);
    
        // Specify the certificate and signer information.
        SignatureOptions options = new SignatureOptions();
        options.Certificate = new X509Certificate2("Certificate.pfx", "password");
        options.HashAlgorithm = HashAlgorithm.SHA256;
        options.SignerName = "Jane Cooper";
        options.Reason = "I approve this document";
        options.Location = "Glendale, CA";
        options.ContactInfo = "jane.cooper@example.com";
    
        // Sign the field.
        pdfDocument.AddSignature(signatureField, options);
    
        using (FileStream outputStream = File.Create("Document_Signed.pdf")) {
            pdfDocument.Save(outputStream);
        }
    }
    

    Note

    The certificate must include a private key. You can load a certificate from a PFX file (as shown above), from the Windows certificate store (the X509Store class), or from any other source that returns an X509Certificate2 object.

    Sign an Existing Signature Field

    Find the signature field in the PdfDocument.Fields collection and pass it to the AddSignature method. Check the SignatureField.IsSigned property to determine whether the field already contains a signature.

    using DevExpress.Docs.Pdf;
    using System.IO;
    using System.Security.Cryptography.X509Certificates;
    
    using (PdfDocument pdfDocument = new PdfDocument(File.OpenRead("Form.pdf"))) {
        if (pdfDocument.Fields.FindByName("Signature1") is SignatureField signatureField
            && !signatureField.IsSigned) {
            SignatureOptions options = new SignatureOptions();
            options.Certificate = new X509Certificate2("Certificate.pfx", "password");
            options.Reason = "Approved";
    
            pdfDocument.AddSignature(signatureField, options);
    
            using (FileStream outputStream = File.Create("Form_Signed.pdf")) {
                pdfDocument.Save(outputStream);
            }
        }
    }
    

    Specify Signature Settings

    Use the following SignatureOptions properties to configure a signature:

    Certificate
    Specifies the X.509 certificate used to sign the document.
    HashAlgorithm
    Specifies the algorithm used to calculate the document hash: SHA256, SHA384, or SHA512.
    SignerName
    Specifies the signer’s name.
    Reason
    Specifies the reason for signing (for example, “I approve this document”).
    Location
    Specifies where the document was signed (for example, a company address).
    ContactInfo
    Specifies the signer’s contact information that recipients can use to verify the signature.
    SigningTime
    Specifies the signing date and time.
    CertificationLevel
    Specifies whether the signature certifies the document and which changes are allowed after signing. See Certify a Document.

    Certify a Document

    A signature can be an approval signature or a certification (author) signature. A certification signature specifies which changes are allowed in the document after it is signed. A document can contain only one certification signature, and it must be the first signature in the document. If the document already contains an approval or certification signature, the CertificationLevel value does not certify the document. See Restrict Changes with an Approval Signature for details.

    Set the SignatureOptions.CertificationLevel property to one of the following CertificationLevel values to certify a document:

    Value Description
    NoCertification The signature does not certify the document.
    NoChangesAllowed The signature certifies the document and does not allow changes.
    FillForms The signature certifies the document and allows users to fill in forms and sign the document.
    FillFormsAndAnnotate The signature certifies the document and allows users to fill in forms, sign the document, and create, edit, or delete annotations.
    SignatureOptions options = new SignatureOptions();
    options.Certificate = new X509Certificate2("Certificate.pfx", "password");
    options.CertificationLevel = CertificationLevel.FillForms;
    
    pdfDocument.AddSignature(signatureField, options);
    

    Lock Form Fields

    You can specify form fields that become read-only after a signature field is signed. Assign a FieldLockInfo object to the SignatureField.Lock property before you sign the field. Use one of the following methods to create the object:

    FieldLockInfo.CreateAll()
    Locks all form fields in the document.
    FieldLockInfo.CreateInclude(fieldNames)
    Locks only the specified fields.
    FieldLockInfo.CreateExclude(fieldNames)
    Locks all fields except the specified fields.
    SignatureField signatureField = new SignatureField("ManagerSignature");
    pdfDocument.Fields.Add(signatureField);
    pdfDocument.Pages[0].Annotations.Add(
        new SignatureWidgetAnnotation(signatureField, new RectangleF(20, 400, 200, 60)));
    
    // Lock the "Amount" and "Date" fields after the field is signed.
    signatureField.Lock = FieldLockInfo.CreateInclude(new[] { "Amount", "Date" });
    
    pdfDocument.AddSignature(signatureField, options);
    

    Restrict Changes with an Approval Signature

    The SignatureOptions.CertificationLevel property also determines which changes are allowed after an approval signature is applied. The result depends on the signatures that the document already contains:

    • If the document contains no approval or certification signatures, the signature certifies the document (see Certify a Document).
    • If the document already contains a signature, the new signature is an approval signature. The specified level is stored in the signature field’s lock dictionary as a SignaturePermission value. This value applies only if it is more restrictive than the permissions of existing signatures. Otherwise, it is ignored. Use the ApprovalSignatureInfo.Permission property to obtain the resulting permission.

    The following table lists how CertificationLevel values map to SignaturePermission values:

    CertificationLevel SignaturePermission
    NoCertification No restriction (null).
    NoChangesAllowed NoChanges
    FillForms FormFillingAndSigning
    FillFormsAndAnnotate AnnotationsAndFormFilling

    If an existing signature does not allow any changes (NoChanges), the AddSignature method throws an InvalidOperationException.

    Note

    The SignatureField.Permission property returns the permission stored in the lock dictionary of a signature field loaded from a document. You can set this property for an unsigned field to specify which changes a PDF viewer should allow after a user signs this field. The AddSignature method does not use this property. The signature permission is determined by the SignatureOptions.CertificationLevel property.

    Specify the Save Mode

    Use the SaveOptions.SaveMode property to specify how a document that already contains signatures is saved. Pass the SaveOptions object to the PdfDocument.Save(stream, options) method. The following SaveMode values are available:

    Value Description
    Auto If the document is loaded from a stream and contains signatures, the API saves changes as an incremental update. Otherwise, the API rewrites the document.
    Rewrite The API rewrites the entire document with all changes and then applies pending signatures.

    An incremental update preserves the original document content, and existing signatures remain valid. If you rewrite a document that contains signatures, existing signatures become invalid.

    If the document has no signatures, save mode has no effect. The document is rewritten with all changes, and then pending signatures are applied.

    An incremental update includes only the following changes:

    • Form field values and definitions.
    • Annotations (including widgets).
    • New signatures.

    Changes that existing signatures do not allow (see Certify a Document and Lock Form Fields) are not saved. Other changes (for example, page content changes) are not included in an incremental update either. Use the Rewrite mode to save these changes before you sign the document.

    Note

    • An incremental update requires the original document data. Keep the source stream open until you save the document, or pass true as the detachStreamAfterLoadComplete parameter of the PdfDocument constructor to copy document data to memory. Otherwise, the Save method throws an InvalidOperationException.
    • If the document’s cross-reference table is corrupted, the signature cannot be added as an incremental update, and the Save method throws an InvalidOperationException. Use the Rewrite mode to rebuild the document before you sign it.
    pdfDocument.AddSignature(signatureField, options);
    
    SaveOptions saveOptions = new SaveOptions();
    saveOptions.SaveMode = SaveMode.Rewrite;
    
    using (FileStream outputStream = File.Create("Document_Signed.pdf")) {
        pdfDocument.Save(outputStream, saveOptions);
    }
    

    Add a Timestamp and Specify a Signature Profile

    Use the Pkcs7DocumentSigner class to add a timestamp to a signature or create a PAdES signature. Pass the signer to the PdfDocument.AddSignature(SignatureField, DocumentSigner) method.

    Timestamp

    A timestamp issued by a Time Stamp Authority (TSA) proves that the document existed in that state at a specific time. Use one of the following constructors to create a signer:

    Pkcs7DocumentSigner(options)
    Creates a signer without a timestamp. Use this constructor if you only need to specify a signature profile.
    Pkcs7DocumentSigner(options, tsaClient)
    Creates a signer that uses an ITsaClient implementation to request a timestamp from a TSA server. Use the built-in TsaClient class or implement a custom client.

    Pass the TSA server URI and the hash algorithm for timestamp requests to the TsaClient constructor. If the server requires authentication, use a TsaClient constructor overload that accepts a user name and password. To configure a proxy, TLS settings, or timeouts for timestamp requests, pass an HttpClient object to the TsaClient constructor.

    Signature Profile

    Use the Pkcs7DocumentSigner.Profile property to specify the signature format:

    Value Description
    Pdf A standard PDF signature in PKCS#7 format.
    PAdES_BES A PAdES (PDF Advanced Electronic Signatures) signature with the Basic Electronic Signature (BES) profile.

    PAdES signatures (ETSI EN 319 142) are required in many EU eIDAS workflows.

    The following code snippet creates a PAdES signature with a timestamp:

    using System;
    using System.Drawing;
    using System.IO;
    using System.Security.Cryptography.X509Certificates;
    using DevExpress.Docs.Pdf;
    using DevExpress.Office.DigitalSignatures;
    using DevExpress.Office.Tsp;
    
    using (var pdfDocument = new PdfDocument(File.OpenRead("Document.pdf"))) {
        // Create a signature field and bind it to a widget on the first page.
        var signatureField = new SignatureField("Signature1");
        pdfDocument.Fields.Add(signatureField);
        pdfDocument.Pages[0].Annotations.Add(
            new SignatureWidgetAnnotation(signatureField, new RectangleF(20, 400, 200, 60)));
    
        // Specify the certificate and signer information.
        var options = new SignatureOptions {
            Certificate = new X509Certificate2("Certificate.pfx", "password"),
            HashAlgorithm = HashAlgorithm.SHA256,
            Reason = "Approved"
        };
    
        // Request a timestamp from a TSA server.
        var timestampClient = new TsaClient(new Uri("https://freetsa.org/tsr"), HashAlgorithmType.SHA256);
    
        // Create a PAdES signature.
        var signer = new Pkcs7DocumentSigner(options, timestampClient);
        signer.Profile = SignatureProfile.PAdES_BES;
    
        pdfDocument.AddSignature(signatureField, signer);
    
        Directory.CreateDirectory("output");
        using (var outputStream = File.Create(Path.Combine("output", "Document.pdf"))) {
            pdfDocument.Save(outputStream);
        }
    }
    

    Customize the Signature Appearance

    Call the following SignatureWidgetAnnotation methods to add content to the signature’s appearance (for example, a scanned signature or company logo):

    Fragment coordinates are specified in points relative to the bottom-left corner of the widget. You can also use inherited widget properties (for example, OutlineColor) to customize the widget border and background.

    using DevExpress.Drawing;
    using System.IO;
    
    SignatureWidgetAnnotation signatureWidget =
        new SignatureWidgetAnnotation(signatureField, new RectangleF(20, 400, 200, 60));
    using (FileStream imageStream = File.OpenRead("Signature.png")) {
        signatureWidget.AddImageFragment(DXImage.FromStream(imageStream), 5, 5);
    }
    signatureWidget.AddTextFragment("Jane Cooper", 90, 20);
    pdfDocument.Pages[0].Annotations.Add(signatureWidget);
    

    For more information about signature fields, refer to the following help topic section: Add a Signature Field.

    Get Signature Information

    Call the PdfDocument.GetSignatures method to obtain all signatures in a document. Call the PdfDocument.TryGetSignatures method to retrieve signatures and check whether the document contains at least one signature. The method returns true if signatures are found. To get the signature of a specific field, use the SignatureField.SignatureInfo property (returns null for unsigned fields).

    All signatures are SignatureInfo descendants. The base class exposes the following properties:

    The signature type determines which descendant the API returns:

    Class Signature Type Specific Properties
    ApprovalSignatureInfo Approval signature. FieldLock, Permission
    AuthoringSignatureInfo Certification (author) signature. FieldLock, Permission
    TimestampSignatureInfo Document-level timestamp. -
    UsageRightsSignatureInfo Usage rights signature that enables additional features in PDF viewers. -
    using DevExpress.Docs.Pdf;
    using System.IO;
    
    using (PdfDocument pdfDocument = new PdfDocument(File.OpenRead("Document_Signed.pdf"))) {
        foreach (SignatureInfo signature in pdfDocument.GetSignatures()) {
            Console.WriteLine($"Field: {signature.Field.Name}");
            Console.WriteLine($"Signer: {signature.SignerName}, signed at: {signature.SigningTime}");
    
            switch (signature) {
                case AuthoringSignatureInfo authoring:
                    Console.WriteLine($"Certification signature. Allowed changes: {authoring.Permission}");
                    break;
                case ApprovalSignatureInfo approval:
                    Console.WriteLine($"Approval signature. Lock action: {approval.FieldLock?.Action}");
                    break;
                case TimestampSignatureInfo:
                    Console.WriteLine("Document-level timestamp");
                    break;
            }
        }
    }
    

    Validate Signatures

    Use the PdfSignatureValidator class to validate PKCS#7 signatures. Pass a stream that contains the signed document to the validator’s constructor. If the document is encrypted, pass the password as the second parameter.

    Verify a PKCS#7 Signature

    Call the PdfSignatureValidator.GetPkcs7Signature method to obtain a Pkcs7Signature object for the specified signature field. This object exposes the following members:

    IsSignatureVerified
    Indicates whether the signature is valid and the signed content has not changed.
    IsTimeStampVerified
    Indicates whether the signature timestamp is valid.
    TimeStampDate
    Returns the date and time from the signature timestamp.
    IsDocumentTimeStamp
    Indicates whether the signature is a document-level timestamp.
    SignatureCertificate, SignatureCertificateChain
    Return the signing certificate and its certificate chain.
    CrlList, OcspList
    Return Certificate Revocation List (CRL) and Online Certificate Status Protocol (OCSP) responses embedded in the signature.
    CheckCertificateRevocation
    Checks whether the signing certificate was revoked at the specified date and time. Pass true as the tryFetchCrlOnline and tryFetchOcspOnline parameters to download CRL and OCSP responses if they are not embedded in the document. The method returns a SignatureCertificateRevocationStatus object.

    Verify Long-Term Validation (LTV) Information

    Call the PdfSignatureValidator.VerifyLtv method to check whether signatures contain information required for long-term validation. The method returns a collection of LtvVerificationStatus objects (one per signature). The CertificateRevocationStatuses dictionary contains the revocation status of each verified certificate. Pass true as the verifyEntireCertificateChain parameter to check all certificates in the chain, not only the signing certificate. Pass true as the optional tryFetchCrlOnline and tryFetchOcspOnline parameters to download CRL and OCSP responses that are not embedded in the document.

    Example: Validate a Signature and Check LTV Information

    The following code snippet validates a signature, checks the signing certificate’s revocation status, and verifies LTV information:

    using DevExpress.Docs.Pdf;
    using System.IO;
    using System.Security.Cryptography.X509Certificates;
    
    using (FileStream documentStream = File.OpenRead("Document_Signed.pdf")) {
        PdfSignatureValidator validator = new PdfSignatureValidator(documentStream);
    
        // Verify the signature.
        Pkcs7Signature signature = validator.GetPkcs7Signature("Signature1");
        Console.WriteLine($"Signature verified: {signature.IsSignatureVerified}");
        Console.WriteLine($"Signed by: {signature.SignatureCertificate.Subject}");
        if (signature.TimeStampDate.HasValue)
            Console.WriteLine($"Timestamp: {signature.TimeStampDate}, verified: {signature.IsTimeStampVerified}");
    
        // Check whether the certificate was revoked at the timestamp time (or now if there is no timestamp).
        DateTimeOffset checkDate = signature.TimeStampDate ?? DateTimeOffset.Now;
        SignatureCertificateRevocationStatus revocationStatus =
            signature.CheckCertificateRevocation(checkDate, tryFetchCrlOnline: true, tryFetchOcspOnline: true);
        Console.WriteLine($"CRL revoked: {revocationStatus.IsCrlRevoked}");
        Console.WriteLine($"OCSP status: {revocationStatus.OcspRevocationStatus}");
    
        // Verify LTV information for all signatures.
        foreach (LtvVerificationStatus ltvStatus in validator.VerifyLtv(verifyEntireCertificateChain: true)) {
            Console.WriteLine($"LTV for {ltvStatus.SignatureFieldName}:");
            foreach (KeyValuePair<X509Certificate2, SignatureCertificateRevocationStatus> item in ltvStatus.CertificateRevocationStatuses)
                Console.WriteLine($"  {item.Key.Subject}: {item.Value.OcspRevocationStatus}");
        }
    }
    

    See Also