Skip to main content

Sign PDF Documents — PDF Document API for Java

  • 14 minutes to read

The PDF Document API allows you to sign PDF documents with X.509 certificates. A digital signature identifies the signer and confirms that the document has not changed since it was signed. The API can also certify documents, lock form fields, add timestamps, and read information about existing signatures.

Signature Basics

A SignatureField stores a signature. A SignatureWidgetAnnotation displays the field 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.

Use the following API to sign documents:

API Description
SignatureOptions Contains signature settings (the certificate, hash algorithm, signer information, and certification level).
addSignature(SignatureField field, SignatureOptions options) Signs the specified signature field with a PKCS#7 signature based on the specified options.
Pkcs7DocumentSigner A document signer that creates a PKCS#7 signature with an optional timestamp and a specified signature profile (PDF or PAdES).
addSignature(SignatureField field, DocumentSigner signer) Signs the specified signature field with the specified signer.
setSaveMode(SaveMode value) Sets the save mode for documents that contain signatures.

The API signs fields when you save the document. The API also sets signature flags of the document’s interactive form (IDocumentFormFieldCollection.getSignatureFlags()). These flags indicate that the document contains signatures and that PDF applications must save changes as an incremental update.

Create and Sign a Signature Field

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

  1. Create a SignatureField object and add it to the field collection (PdfDocument.getFields()).
  2. Create a SignatureWidgetAnnotation object to display the field on a page. Pass the field and widget bounds to the SignatureWidgetAnnotation(formField, bounds) constructor. Add the widget to the page annotation collection (Page.getAnnotations()).
  3. Create a SignatureOptions object. Specify the signing certificate and signer information.
  4. Pass the field and options to the PdfDocument.addSignature(field, options) method.
  5. Save the document.

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

import java.io.*;
import java.nio.file.*;
import com.devexpress.docs.pdf.*;
import com.devexpress.system.drawing.*;

public class Main {
    public static void main(String[] args) throws Exception {
        try (InputStream inputStream = Files.newInputStream(Path.of("Document.pdf"));
             PdfDocument pdfDocument = new PdfDocument(inputStream);
             InputStream certificateStream = Files.newInputStream(Path.of("certificate.pfx"))) {
            // Create a signature field and add it to the field collection.
            SignatureField signatureField = new SignatureField("Signature1");
            pdfDocument.getFields().add(signatureField);

            // Bind the field to a widget on the first page.
            SignatureWidgetAnnotation signatureWidget =
                    new SignatureWidgetAnnotation(signatureField, new RectangleF(20, 400, 200, 60));
            pdfDocument.getPages().getFirst().getAnnotations().add(signatureWidget);

            // Specify the certificate and signer information.
            SignatureOptions options = new SignatureOptions();
            options.setCertificate(certificateStream, "CERTIFICATE_PASSWORD");
            options.setHashAlgorithm(HashAlgorithm.SHA_256);
            options.setSignerName("Jane Cooper");
            options.setReason("I approve this document");
            options.setLocation("Glendale, CA");
            options.setContactInfo("jane.cooper@example.com");

            // Sign the field.
            pdfDocument.addSignature(signatureField, options);

            Files.createDirectories(Path.of("output"));
            try (OutputStream outputStream = Files.newOutputStream(Path.of("output", "Document.pdf"))) {
                pdfDocument.save(outputStream);
            }
        }
    }
}

Refer to the following help topics for additional information about form fields and page coordinates:

Sign an Existing Signature Field

Call the IFormFieldCollection.findByName(name) method to find the signature field and pass the field to the addSignature method. Call the SignatureField.getIsSigned() method to check whether the field already contains a signature.

The Specify the Save Mode section contains a code snippet that signs an existing field.

Specify Signature Settings

Signature Certificate

Call one of the following methods to specify the signature certificate and private key:

Method Description
setCertificate(InputStream stream, String password) Sets the signature certificate and private key from a stream that contains PKCS#12 (PFX) data.
setCertificate(ReadableByteChannel channel, String password) Sets the signature certificate and private key from a channel that contains PKCS#12 (PFX) data.
setCertificate(byte[] data, String password) Sets the signature certificate and private key from PKCS#12 (PFX) data.
setCertificate(KeyStore keyStore, String alias, char[] password) Sets the signature certificate and private key from the specified key store entry.
setCertificate(X509Certificate certificate, PrivateKey privateKey) Sets the signature certificate and private key.

The following code snippet loads a PKCS#12 key store and specifies the certificate stored in the signer entry:

// Load a PKCS#12 key store.
KeyStore keyStore = KeyStore.getInstance("PKCS12");
try (InputStream keyStoreStream = Files.newInputStream(Path.of("certificate.pfx"))) {
    keyStore.load(keyStoreStream, "CERTIFICATE_PASSWORD".toCharArray());
}

// Specify the signing certificate and private key.
SignatureOptions options = new SignatureOptions();
options.setCertificate(keyStore, "signer", "CERTIFICATE_PASSWORD".toCharArray());

Note

The API supports RSA, DSA, and EC private keys and re-encodes the private key in PKCS#8 format. Non-exportable private keys (for example, keys stored on a PKCS#11 token or in a hardware security module) are not supported.

Signer Information and Hash Algorithm

Call the following SignatureOptions methods to configure a signature:

Method Description
setHashAlgorithm(HashAlgorithm value) Specifies the algorithm that hashes the signed content: SHA-256 (default), SHA-384, or SHA-512.
setSignerName(String value) Specifies the signer name. If you do not specify the name, the API writes the name from the signature certificate.
setReason(String value) Specifies the reason for signing (for example, “I approve this document”).
setLocation(String value) Specifies where the document was signed (for example, a company address).
setContactInfo(String value) Specifies the signer contact information that recipients can use to verify the signature.
setSigningTime(OffsetDateTime value) Specifies the signing date and time. If you do not specify the signing time, the API writes the time when you save the document.
setCertificationLevel(CertificationLevel value) Specifies whether the signature certifies the document and which changes the signature allows (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 users can make in the signed document.

A document can contain a single certification signature, and it must be the first approval or certification signature in the document. The API certifies the document if the document contains no approval or certification signatures. If you sign multiple fields before you save the document, only the first signature can certify the document.

Call the SignatureOptions.setCertificationLevel(value) method to specify the certification level:

Value Description
NO_CERTIFICATION The signature does not certify the document.
NO_CHANGES_ALLOWED The signature certifies the document and does not allow changes.
FILL_FORMS The signature certifies the document and allows users to fill in forms and sign the document.
FILL_FORMS_AND_ANNOTATE The signature certifies the document and allows users to fill in forms, sign the document, and create, edit, or delete annotations.

The following code snippet certifies a document, allows users to fill in forms and sign the document, and locks the Amount and Date form fields:

import java.io.*;
import java.nio.file.*;
import java.util.List;
import com.devexpress.docs.pdf.*;
import com.devexpress.system.drawing.*;

public class Main {
    public static void main(String[] args) throws Exception {
        try (InputStream inputStream = Files.newInputStream(Path.of("Document.pdf"));
             PdfDocument pdfDocument = new PdfDocument(inputStream);
             InputStream certificateStream = Files.newInputStream(Path.of("certificate.pfx"))) {
            // Create a signature field and bind it to a widget on the first page.
            SignatureField signatureField = new SignatureField("ManagerSignature");
            pdfDocument.getFields().add(signatureField);
            pdfDocument.getPages().getFirst().getAnnotations().add(
                    new SignatureWidgetAnnotation(signatureField, new RectangleF(20, 400, 200, 60)));

            // Lock the "Amount" and "Date" fields after the field is signed.
            signatureField.setLock(FieldLockInfo.createInclude(List.of("Amount", "Date")));

            // Certify the document.
            SignatureOptions options = new SignatureOptions();
            options.setCertificate(certificateStream, "CERTIFICATE_PASSWORD");
            options.setCertificationLevel(CertificationLevel.FILL_FORMS);

            pdfDocument.addSignature(signatureField, options);

            Files.createDirectories(Path.of("output"));
            try (OutputStream outputStream = Files.newOutputStream(Path.of("output", "Document.pdf"))) {
                pdfDocument.save(outputStream);
            }
        }
    }
}

Restrict Changes with an Approval Signature

If the document already contains an approval or certification signature, the new signature is an approval signature. The API converts the certification level to a SignaturePermission value and stores it in the signature field lock dictionary. The API applies the value only if it is more restrictive than permissions of existing signatures. Otherwise, the API ignores the value. Call the ApprovalSignatureInfo.getPermission() method to get the resulting permission.

The following table lists how certification levels map to signature permissions:

Certification Level Signature Permission
CertificationLevel.NO_CERTIFICATION No restriction (null).
CertificationLevel.NO_CHANGES_ALLOWED NO_CHANGES
CertificationLevel.FILL_FORMS FORM_FILLING_AND_SIGNING
CertificationLevel.FILL_FORMS_AND_ANNOTATE ANNOTATIONS_AND_FORM_FILLING

If an existing signature does not allow changes (SignaturePermission.NO_CHANGES), addSignature methods do not add the signature and throw an InvalidOperationException.

Note

For a signature field loaded from a document, the SignatureField.getPermission() method returns the permission stored in the field lock dictionary. Call the SignatureField.setPermission(value) method for an unsigned field to specify which changes a PDF viewer allows after a user signs the field. The addSignature methods do not use this setting.

Lock Form Fields

You can specify form fields that become read-only after a signature field is signed. Call one of the following methods to create a FieldLockInfo object and pass the object to the SignatureField.setLock(value) method before you save the signed document:

Method Description
createAll() Creates an object that locks all form fields in the document.
createInclude Creates an object that locks the specified form fields.
createExclude Creates an object that locks all form fields except the specified fields.

Specify full field names. A lock that lists a field also applies to child fields of this field. The API does not check whether the document contains the listed fields.

The code snippet in the Certify a Document section locks the Amount and Date form fields.

Specify the Save Mode

To specify how the API saves a document that contains signatures, pass a SaveOptions object to the PdfDocument.save(stream, options) method. Call the SaveOptions.setSaveMode(value) method to specify one of the following values:

Value Description
AUTO If the document is loaded from a stream or channel and contains signatures or pending 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 appends changes. Existing signatures remain valid. The API includes the following changes in an incremental update:

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

If you sign a loaded document in SaveMode.AUTO mode, the API saves an incremental update even if the document contained no signatures before.

Important

  • An incremental update does not include changes that signatures in the loaded document do not allow. The update also does not include other changes (for example, new pages, page content changes, or document metadata changes, including creation and modification dates and metadata synchronization). To save other changes, call the setSaveMode(SaveMode.REWRITE) method.
  • If you rewrite a document that contains signatures, the saved document does not contain signatures from the loaded document. The signature fields remain in the document as unsigned fields.

Note

  • An incremental update requires the original document data. Keep the source stream or channel open until you save the document, or pass true as the detachStreamAfterLoadComplete parameter of a PdfDocument constructor.
  • If the cross-reference table of the source document is corrupted, the API cannot save an incremental update, and the PdfDocument.save method throws an InvalidOperationException. In this instance, call the setSaveMode(SaveMode.REWRITE) method.

The following code snippet signs an existing signature field and rewrites the entire document:

import java.io.*;
import java.nio.file.*;
import com.devexpress.docs.pdf.*;

public class Main {
    public static void main(String[] args) throws Exception {
        try (InputStream inputStream = Files.newInputStream(Path.of("Document.pdf"));
             PdfDocument pdfDocument = new PdfDocument(inputStream);
             InputStream certificateStream = Files.newInputStream(Path.of("certificate.pfx"))) {
            if (pdfDocument.getFields().findByName("Signature1") instanceof SignatureField signatureField
                    && !signatureField.getIsSigned()) {
                SignatureOptions options = new SignatureOptions();
                options.setCertificate(certificateStream, "CERTIFICATE_PASSWORD");
                options.setReason("Approved");
                pdfDocument.addSignature(signatureField, options);

                SaveOptions saveOptions = new SaveOptions();
                saveOptions.setSaveMode(SaveMode.REWRITE);

                Files.createDirectories(Path.of("output"));
                try (OutputStream outputStream = Files.newOutputStream(Path.of("output", "Document.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 to create a PAdES signature. Pass the signer to the PdfDocument.addSignature(field, signer) method.

Timestamp

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

Pkcs7DocumentSigner(options)
Creates a signer without a timestamp. Call this constructor if you need to specify the signature profile only.
Pkcs7DocumentSigner(options, timestampOptions)
Creates a signer that requests a timestamp from the TSA server specified by a TimestampOptions object. Pass the server URL to the TimestampOptions(url) constructor. If the server requires authentication, call TimestampOptions.setUserName(value) and TimestampOptions.setPassword(value) methods. Call the TimestampOptions.setHashAlgorithm(value) method to specify the hash algorithm for timestamp requests.
Pkcs7DocumentSigner(options, tsaClient)
Creates a signer that requests a timestamp from an ITsaClient implementation (for example, a TsaClient object).

The API requests the timestamp when you save the document.

Signature Profile

Call the Pkcs7DocumentSigner.setProfile(value) method to specify the signature format:

Value Description
PDF A standard PDF signature in PKCS#7 format.
P_AD_ES_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:

import java.io.*;
import java.nio.file.*;
import com.devexpress.docs.pdf.*;
import com.devexpress.system.drawing.*;

public class Main {
    public static void main(String[] args) throws Exception {
        try (InputStream inputStream = Files.newInputStream(Path.of("Document.pdf"));
             PdfDocument pdfDocument = new PdfDocument(inputStream);
             InputStream certificateStream = Files.newInputStream(Path.of("certificate.pfx"))) {
            // Create a signature field and bind it to a widget on the first page.
            SignatureField signatureField = new SignatureField("Signature1");
            pdfDocument.getFields().add(signatureField);
            pdfDocument.getPages().getFirst().getAnnotations().add(
                    new SignatureWidgetAnnotation(signatureField, new RectangleF(20, 400, 200, 60)));

            // Specify the certificate and signer information.
            SignatureOptions options = new SignatureOptions();
            options.setCertificate(certificateStream, "CERTIFICATE_PASSWORD");
            options.setHashAlgorithm(HashAlgorithm.SHA_256);
            options.setReason("Approved");

            // Request a timestamp from a TSA server.
            TimestampOptions timestampOptions = new TimestampOptions("https://freetsa.org/tsr");
            timestampOptions.setHashAlgorithm(HashAlgorithm.SHA_256);

            // Create a PAdES signature.
            Pkcs7DocumentSigner signer = new Pkcs7DocumentSigner(options, timestampOptions);
            signer.setProfile(SignatureProfile.P_AD_ES_BES);

            pdfDocument.addSignature(signatureField, signer);

            Files.createDirectories(Path.of("output"));
            try (OutputStream outputStream = Files.newOutputStream(Path.of("output", "Document.pdf"))) {
                pdfDocument.save(outputStream);
            }
        }
    }
}

Customize the Signature Appearance

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

Method Description
addTextFragment(String text, float x, float y) Adds text to the signature appearance.
addImageFragment(DXImage image, float x, float y) Adds an image to the signature appearance.
addFragment(PageFragment fragment) Adds the specified fragment to the signature appearance.

Fragment coordinates are in points relative to the bottom-left corner of the widget. To customize the widget border and background, call methods that the widget inherits from the WidgetAnnotation class (for example, SignatureWidgetAnnotation.setOutlineColor(value)).

The following code snippet adds a scanned signature and the signer name to the signature appearance:

import java.io.*;
import java.nio.file.*;
import com.devexpress.docs.pdf.*;
import com.devexpress.drawing.*;
import com.devexpress.system.drawing.*;

public class Main {
    public static void main(String[] args) throws Exception {
        try (InputStream inputStream = Files.newInputStream(Path.of("Document.pdf"));
             PdfDocument pdfDocument = new PdfDocument(inputStream);
             InputStream certificateStream = Files.newInputStream(Path.of("certificate.pfx"));
             InputStream imageStream = Files.newInputStream(Path.of("Signature.png"));
             DXImage signatureImage = DXImage.fromStream(imageStream)) {
            SignatureField signatureField = new SignatureField("Signature1");
            pdfDocument.getFields().add(signatureField);

            SignatureWidgetAnnotation signatureWidget =
                    new SignatureWidgetAnnotation(signatureField, new RectangleF(20, 400, 200, 60));

            // Add a scanned signature and the signer name to the widget.
            signatureWidget.addImageFragment(signatureImage, 5, 5);
            signatureWidget.addTextFragment("Jane Cooper", 90, 20);
            pdfDocument.getPages().getFirst().getAnnotations().add(signatureWidget);

            SignatureOptions options = new SignatureOptions();
            options.setCertificate(certificateStream, "CERTIFICATE_PASSWORD");
            options.setSignerName("Jane Cooper");
            pdfDocument.addSignature(signatureField, options);

            Files.createDirectories(Path.of("output"));
            try (OutputStream outputStream = Files.newOutputStream(Path.of("output", "Document.pdf"))) {
                pdfDocument.save(outputStream);
            }
        }
    }
}

Get Signature Information

Call the PdfDocument.getSignatures() method to get all signatures in a document. The PdfDocument.tryGetSignatures(signatures) method replaces the content of the specified list with the document signatures and returns whether the document contains at least one signature. To get the signature of a specific field, call the SignatureField.getSignatureInfo() method (the getSignatureInfo() method returns null for unsigned fields).

All signatures are SignatureInfo descendants. The SignatureInfo class contains the following methods:

Method Description
getSignerName() Returns the signer name.
getSigningTime() Returns the signing date and time.
getReason() Returns the reason for signing (for example, “I approve this document”).
getContactInfo() Returns the signer’s contact information.
getField() Returns the signature field that contains the signature.

The signature type determines which descendant the API returns:

Class Signature Type Specific Methods
ApprovalSignatureInfo An approval signature. getFieldLock(), getPermission()
AuthoringSignatureInfo A certification (author) signature. getFieldLock(), getPermission()
TimestampSignatureInfo A document-level timestamp. -
UsageRightsSignatureInfo A usage rights signature that enables actions that a PDF viewer otherwise restricts (for example, saving form data). -

The following code snippet displays information about all signatures in a document:

import java.io.*;
import java.nio.file.*;
import com.devexpress.docs.pdf.*;

public class Main {
    public static void main(String[] args) throws Exception {
        try (InputStream inputStream = Files.newInputStream(Path.of("Document.pdf"));
             PdfDocument pdfDocument = new PdfDocument(inputStream)) {
            for (SignatureInfo signature : pdfDocument.getSignatures()) {
                System.out.println("Field: " + signature.getField().getName());
                System.out.println("Signer: " + signature.getSignerName()
                        + ", signed at: " + signature.getSigningTime());

                switch (signature) {
                    case AuthoringSignatureInfo authoring ->
                        System.out.println("Certification signature. Allowed changes: "
                                + authoring.getPermission());
                    case ApprovalSignatureInfo approval ->
                        System.out.println("Approval signature. Lock action: "
                                + (approval.getFieldLock() != null ? approval.getFieldLock().getAction() : null));
                    case TimestampSignatureInfo timestamp ->
                        System.out.println("Document-level timestamp");
                    default -> { }
                }
            }
        }
    }
}

Next Steps

See Also