We now know what a PDF signature looks like on the inside: a /Sig dictionary, a /Contents placeholder holding a CMS structure and a /ByteRange that covers everything except that placeholder, all written in an incremental revision. Now we're going to produce one. The work is split between two libraries: PDFBox handles the PDF side (creating the field and the dictionary, reserving the placeholder, calculating the /ByteRange and writing the revision) and Bouncy Castle handles the cryptographic side (building the CMS with the signature, the certificate and, if we want, a timestamp). The point where they meet is a one-method interface, SignatureInterface. With it we'll build PdfSigner, which will sign invoice F-2026-0001 invisibly, certify it with DocMDP, sign it through an external service, add a timestamp, sign in the signature.customer field of the registration form and chain Nebula's signature with the customer's. We're still using only the test certificates from 07-02.
Contents
- Adding Bouncy Castle to the project
- How PDFBox signs: the complete sequence
PDSignatureandSignatureOptionsSignatureInterface: generating the CMS with Bouncy Castle- The
PdfSignerclass - Signing invoice F-2026-0001
- Certification signature with DocMDP:
Certification - PAdES B-B profile
- External signing: HSMs and remote services
- Timestamp:
TsaClient - Signing in an existing field:
signature.customer - Successive signatures: issuer and customer
Reminder: everything we sign here uses test certificates, self-signed and with no legal validity. What kind of signature a real invoice needs (and whether it must also be in a specific electronic invoice format) is a legal and tax matter that must be reviewed by a professional or by your compliance department.
Adding Bouncy Castle to the project
PDFBox declares Bouncy Castle as an optional dependency: it doesn't download it on its own, because it's only needed for signatures and for certificate encryption (07-01). We add it to pom.xml:
<properties>
<!-- ... previous properties ... -->
<bouncycastle.version>1.83</bouncycastle.version>
</properties>
<dependencies>
<!-- ... pdfbox, xmpbox, zxing ... -->
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcpkix-jdk18on</artifactId>
<version>${bouncycastle.version}</version>
</dependency>
<dependency>
<groupId>org.bouncycastle</groupId>
<artifactId>bcprov-jdk18on</artifactId>
<version>${bouncycastle.version}</version>
</dependency>
</dependencies>| Artifact | Contains | We use it for |
|---|---|---|
bcprov-jdk18on |
The cryptographic provider (algorithms) and ASN.1 | The basis for everything else |
bcutil-jdk18on |
Shared ASN.1 utilities | Comes in as a dependency of bcpkix |
bcpkix-jdk18on |
CMS, certificates, timestamps (TSP), OCSP | CMSSignedDataGenerator, TimeStampRequest… |
- The
jdk18onsuffix means "Java 8 or later"; it's the current line (the oldjdk15onones are abandoned). - We declare
bcprovexplicitly with the same version so that Maven doesn't mix versions if another dependency brings in a different one. Mixing Bouncy Castle versions producesNoSuchMethodErrorerrors that are hard to diagnose. - All the code in this module has been verified with PDFBox 3.0.8 and Bouncy Castle 1.83.
How PDFBox signs: the complete sequence
Signing with PDFBox essentially comes down to two calls: document.addSignature(signature, signer, options) and document.saveIncremental(output). The interesting part is what happens inside the second one:
sequenceDiagram
participant App as InvoiceLab
participant Doc as PDDocument
participant W as COSWriter (saveIncremental)
participant F as SignatureInterface (PdfSigner)
participant BC as Bouncy Castle
App->>Doc: addSignature(PDSignature, signer, options)
Note over Doc: creates the /FT /Sig field and its widget,<br/>sets /SigFlags 3, stores the reference to the signer
App->>W: saveIncremental(output)
W->>W: writes the new revision with /Contents full of zeros<br/>and a provisional /ByteRange
W->>W: calculates and writes the real /ByteRange
W->>F: sign(InputStream with the ByteRange bytes)
F->>BC: SHA-256 fingerprint + RSA signature + certificate → CMS
BC-->>F: CMS (≈ 2 KB)
F-->>W: byte[] cms
W->>W: writes the CMS in hexadecimal into the placeholder
W-->>App: signed file
Key points:
addSignaturedoesn't sign: it only prepares the structure and records who will sign.- The
signmethod receives the exact bytes covered by the/ByteRange(the whole file except the placeholder). You don't have to calculate anything about the PDF: just sign those bytes. - The signature is written into the placeholder without moving anything else. That's why the placeholder size is fixed before signing.
PDSignature and SignatureOptions
PDSignature represents the /Sig dictionary:
| Method | Entry | Value in InvoiceLab |
|---|---|---|
setFilter(PDSignature.FILTER_ADOBE_PPKLITE) |
/Filter |
Always Adobe.PPKLite |
setSubFilter(...) |
/SubFilter |
SUBFILTER_ADBE_PKCS7_DETACHED or SUBFILTER_ETSI_CADES_DETACHED |
setName(String) |
/Name |
"Nebula Distribution Ltd." |
setLocation(String) |
/Location |
"Zaragoza" |
setReason(String) |
/Reason |
"Issue of invoice F-2026-0001" |
setSignDate(Calendar) |
/M |
Calendar.getInstance(), the moment of signing. Mandatory in practice: without it many viewers won't validate |
SignatureOptions groups options for the operation:
| Method | What for |
|---|---|
setPreferredSignatureSize(int) |
Placeholder size in binary bytes (in the file it takes up twice as much, in hexadecimal). Default DEFAULT_SIGNATURE_SIZE = 9,472 |
setVisualSignature(InputStream) |
Template with the appearance of a visible signature (07-04) |
setPage(int) |
Page (zero-based) of the visible signature |
SignatureOptions is Closeable and has a rule worth memorising: it's closed after saving, never before. If it carries a visible signature, it contains objects that are copied into the document during the save; closing it earlier produces closed-stream errors (that's the PDFBOX-3743 warning in the official examples).
How much space to reserve? Our CMS structures are around 2 KB without a timestamp and about 6.6 KB with one, but a real certificate chain (signer + intermediate + root) or a timestamp from a TSA with a long chain can exceed the default 9,472 bytes. Like the official examples, we'll reserve twice that: 18,944 bytes, which are 37,890 characters in the file. The leftover zeros compress very badly, so each signature adds about 39 KB to the PDF; that's the price of not running short.
SignatureInterface: generating the CMS with Bouncy Castle
SignatureInterface has a single method:
It receives the bytes to sign and returns the CMS. This is how PdfSigner implements it (we'll see the full class shortly):
@Override
public byte[] sign(InputStream content) throws IOException {
try {
X509Certificate certificate = credential.certificate();
ContentSigner signer = new JcaContentSignerBuilder("SHA256withRSA").build(credential.privateKey());
JcaSignerInfoGeneratorBuilder info =
new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().build());
if (profile == Profile.PADES_B) {
info.setSignedAttributeGenerator(padesAttributes(certificate));
}
CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
generator.addSignerInfoGenerator(info.build(signer, certificate));
generator.addCertificates(new JcaCertStore(Arrays.asList(credential.chain())));
CMSTypedData data = new CMSProcessableByteArray(content.readAllBytes());
CMSSignedData signed = generator.generate(data, false); // false = "detached": the PDF isn't copied
if (tsa != null) {
signed = tsa.addTimestamp(signed);
}
return signed.getEncoded();
} catch (GeneralSecurityException | OperatorCreationException | CMSException e) {
throw new IOException("Could not create the CMS signature", e);
}
}Step by step:
JcaContentSignerBuilder("SHA256withRSA").build(privateKey): the object that will sign with our RSA private key using SHA-256. For an elliptic curve key it would be"SHA256withECDSA". (The official examples usecert.getSigAlgName(), the algorithm the certificate was signed with; it usually matches, but not always, so we prefer to set it explicitly.)JcaSignerInfoGeneratorBuilder: prepares the SignerInfo, the part of the CMS that describes a signer. It needs aDigestCalculatorProviderto calculate fingerprints. By default it adds the standard signed attributes: content type, the document's fingerprint (messageDigest), signing time (signingTime) and algorithm protection. It's important to understand that what gets signed with RSA isn't the PDF's fingerprint directly, but these attributes, which include that fingerprint.CMSSignedDataGenerator: the CMS generator. We add the signer and the chain's certificates (JcaCertStore) to it, so the verifier doesn't have to go looking for them.CMSProcessableByteArray(content.readAllBytes()): the data to sign. We read everything into memory, which is reasonable for invoices of tens of KB. For PDFs of hundreds of MB, PDFBox's official examples include theCMSProcessableInputStreamclass, which processes the stream without loading it all; copy it from there if you need it (it isn't part of thepdfboxlibrary).generate(data, false): thefalsecreates a detached signature: the CMS contains the signature but not a copy of the PDF. That's whatadbe.pkcs7.detachedandETSI.CAdES.detachedrequire. Withtrueyou'd be putting the whole document inside its own placeholder.- Optional timestamp: if a TSA is configured, it's added to the CMS (we'll see this later).
getEncoded(): the CMS in DER (binary). PDFBox will convert it to hexadecimal and write it into the placeholder.
Bouncy Castle's exceptions are wrapped in IOException because that's the only exception the interface signature allows.
The PdfSigner class
The class lives in com.invoicelab.security and implements SignatureInterface. It begins with the types that make up its API:
package com.invoicelab.security;
import com.invoicelab.editing.PdfEditor;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Hashtable;
import org.apache.pdfbox.Loader;
import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationWidget;
import org.apache.pdfbox.pdmodel.interactive.digitalsignature.ExternalSigningSupport;
import org.apache.pdfbox.pdmodel.interactive.digitalsignature.PDSignature;
import org.apache.pdfbox.pdmodel.interactive.digitalsignature.SignatureInterface;
import org.apache.pdfbox.pdmodel.interactive.digitalsignature.SignatureOptions;
import org.apache.pdfbox.pdmodel.interactive.form.PDAcroForm;
import org.apache.pdfbox.pdmodel.interactive.form.PDField;
import org.apache.pdfbox.pdmodel.interactive.form.PDSignatureField;
import org.bouncycastle.asn1.ASN1EncodableVector;
import org.bouncycastle.asn1.DERSet;
import org.bouncycastle.asn1.cms.Attribute;
import org.bouncycastle.asn1.cms.AttributeTable;
import org.bouncycastle.asn1.cms.CMSAttributes;
import org.bouncycastle.asn1.ess.ESSCertIDv2;
import org.bouncycastle.asn1.ess.SigningCertificateV2;
import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers;
import org.bouncycastle.cert.jcajce.JcaCertStore;
import org.bouncycastle.cms.CMSAttributeTableGenerator;
import org.bouncycastle.cms.CMSException;
import org.bouncycastle.cms.CMSProcessableByteArray;
import org.bouncycastle.cms.CMSSignedData;
import org.bouncycastle.cms.CMSSignedDataGenerator;
import org.bouncycastle.cms.CMSTypedData;
import org.bouncycastle.cms.DefaultSignedAttributeTableGenerator;
import org.bouncycastle.cms.jcajce.JcaSignerInfoGeneratorBuilder;
import org.bouncycastle.operator.ContentSigner;
import org.bouncycastle.operator.OperatorCreationException;
import org.bouncycastle.operator.jcajce.JcaContentSignerBuilder;
import org.bouncycastle.operator.jcajce.JcaDigestCalculatorProviderBuilder;
/** Signs PDFs with PDFBox (structure) and Bouncy Castle (CMS cryptography). */
public final class PdfSigner implements SignatureInterface {
/** CMS format. PKCS7: adbe.pkcs7.detached; PADES_B: ETSI.CAdES.detached (PAdES B-B). */
public enum Profile { PKCS7, PADES_B }
/** What to sign and how. field == null → sign in a new field; docMdpPermission == 0 → approval. */
public record SignatureData(String name, String location, String reason, String field, int docMdpPermission) {
public static SignatureData approval(String name, String location, String reason) {
return new SignatureData(name, location, reason, null, 0);
}
public SignatureData inField(String fieldName) {
return new SignatureData(name, location, reason, fieldName, docMdpPermission);
}
public SignatureData certifying(int permission) {
return new SignatureData(name, location, reason, field, permission);
}
}
/** Creates the appearance of a visible signature (we'll implement it in 07-04). */
public interface Appearance {
/** Returns a template PDF with the appearance. rect: the existing field's, or null if there's no field. */
InputStream template(PDDocument document, PDSignature signature, int page, PDRectangle rect)
throws IOException;
}
/** Service that produces the CMS outside PDFBox (HSM, remote signing service...). */
@FunctionalInterface
public interface SigningService {
byte[] sign(InputStream contentToSign) throws IOException;
}
/** Placeholder reserved for the CMS: 2 x 9,472 bytes (≈ 37 KB in hexadecimal). */
public static final int SIGNATURE_SIZE = SignatureOptions.DEFAULT_SIGNATURE_SIZE * 2;
private final KeyVault.Credential credential;
private final Profile profile;
private final TsaClient tsa; // null = no timestamp
public PdfSigner(KeyVault.Credential credential) {
this(credential, Profile.PKCS7, null);
}
public PdfSigner(KeyVault.Credential credential, Profile profile, TsaClient tsa) {
this.credential = credential;
this.profile = profile;
this.tsa = tsa;
}SignatureDatais a record with "with" methods (withers):approval(...)creates the basic data andinField(...)/certifying(...)return modified copies. It reads almost like a sentence:SignatureData.approval(...).inField("signature.customer").Appearanceis the extension point for visible signatures. Today we'll always sign invisibly (null); in 07-04 we'll write an implementation.SigningServiceabstracts "something that, given some bytes, returns a CMS". We'll use it for external signing.
The main method reuses PdfEditor from module 4: it loads, applies the change, saves incrementally to a temporary file and moves it atomically.
public void sign(Path source, Path target, SignatureData data) throws IOException {
sign(source, target, data, null);
}
public void sign(Path source, Path target, SignatureData data, Appearance appearance) throws IOException {
// The options are closed AFTER saving: they contain objects that are copied into the signed document
try (SignatureOptions options = new SignatureOptions()) {
options.setPreferredSignatureSize(SIGNATURE_SIZE);
PdfEditor.edit(source, target, PdfEditor.Mode.INCREMENTAL, document -> {
PDSignature signature = prepareSignature(document, data);
if (appearance != null) {
PDAnnotationWidget widget = data.field() == null ? null : widgetOf(document, data.field());
int page = widget == null ? 0 : document.getPages().indexOf(pageOf(document, widget));
PDRectangle rect = widget == null ? null : widget.getRectangle();
options.setVisualSignature(appearance.template(document, signature, page, rect));
options.setPage(page);
}
document.addSignature(signature, this, options); // PdfEditor will call saveIncremental
});
}
}- The
SignatureOptionstry-with-resources wraps the call toedit: the options stay open whilePdfEditorsaves and are closed at the end. It's the rule from the previous section applied naturally. - Inside the lambda we only prepare the signature and call
addSignature(signature, this, options):thisis theSignatureInterface.PdfEditor'ssaveIncrementalwill trigger oursign. - Thanks to
PdfEditor, if something fails halfway through, the target isn't left half-written; andsourceandtargetcan be the same file.
Preparing the /Sig dictionary:
private PDSignature prepareSignature(PDDocument document, SignatureData data) throws IOException {
if (Certification.permission(document) == Certification.NO_CHANGES) {
throw new IllegalStateException("Document certified with no changes allowed (DocMDP P=1)");
}
PDSignature signature = new PDSignature();
signature.setFilter(PDSignature.FILTER_ADOBE_PPKLITE);
signature.setSubFilter(profile == Profile.PADES_B
? PDSignature.SUBFILTER_ETSI_CADES_DETACHED : PDSignature.SUBFILTER_ADBE_PKCS7_DETACHED);
signature.setName(data.name());
signature.setLocation(data.location());
signature.setReason(data.reason());
signature.setSignDate(Calendar.getInstance()); // /M: time declared by the signer (not reliable without a TSA)
if (data.docMdpPermission() > 0) {
Certification.certify(document, signature, data.docMdpPermission());
}
if (data.field() != null) {
PDSignatureField field = signatureField(document, data.field());
if (field.getSignature() != null) {
throw new IllegalStateException("The field " + data.field() + " is already signed");
}
// The field's /V → our signature: addSignature will recognise the field and reuse it.
// (setValue(signature) also works, but warns that it can't generate the appearance)
field.getCOSObject().setItem(COSName.V, signature);
}
return signature;
}- If the document is certified with P=1, no further signature can be added: we fail before writing anything, as the official examples do (
CreateSignature.signDetached). - We'll explain the certification and existing-field branches in their own sections.
And the utilities for locating fields and pages (we'll reuse them in 07-04):
static PDSignatureField signatureField(PDDocument document, String name) throws IOException {
PDAcroForm form = document.getDocumentCatalog().getAcroForm(null);
PDField field = form == null ? null : form.getField(name);
if (field instanceof PDSignatureField signature) {
return signature;
}
throw new IOException("There is no signature field named " + name);
}
private static PDAnnotationWidget widgetOf(PDDocument document, String field) throws IOException {
return signatureField(document, field).getWidgets().get(0);
}
/** The widget's page: via /P or, if it's missing, by searching the /Annots of each page. */
static PDPage pageOf(PDDocument document, PDAnnotationWidget widget) throws IOException {
if (widget.getPage() != null) {
return widget.getPage();
}
for (PDPage page : document.getPages()) {
for (var annotation : page.getAnnotations()) {
if (annotation.getCOSObject() == widget.getCOSObject()) {
return page;
}
}
}
throw new IOException("The widget isn't on any page");
}Remember from 05-02 why we use getAcroForm(null): without arguments, PDFBox applies fixes to the form (it regenerates appearances), and that's the last thing we want in a document we're about to sign. Looking up the page through /Annots is the same idea as in FormInspector (05-02): the widget's /P is optional.
We'll see the rest of the class (signExternally, sign and padesAttributes) in their own sections.
Signing invoice F-2026-0001
With what we've covered we can now sign. The example loads Nebula's credential with KeyVault and Secrets and signs in three ways; we'll start with the first:
package com.invoicelab.examples;
import com.invoicelab.security.KeyVault;
import com.invoicelab.security.Certification;
import com.invoicelab.security.PdfSigner;
import com.invoicelab.security.PdfSigner.SignatureData;
import com.invoicelab.security.Secrets;
import java.nio.file.Files;
import java.nio.file.Path;
public class SignInvoice {
public static void main(String[] args) throws Exception {
KeyVault.Credential nebula = KeyVault.load(Path.of("certificates/nebula-test.p12"),
Secrets.chars("INVOICELAB_P12_NEBULA"), "nebula");
PdfSigner signer = new PdfSigner(nebula);
Path invoice = Path.of("output/F-2026-0001.pdf");
Path folder = Files.createDirectories(Path.of("output/signed"));
SignatureData issue = SignatureData.approval("Nebula Distribution Ltd.", "Zaragoza",
"Issue of invoice F-2026-0001");
// 1) Approval signature, invisible
Path signed = folder.resolve("F-2026-0001-signed.pdf");
signer.sign(invoice, signed, issue);
report(invoice, signed);
// 2) Certification signature: only forms and signatures allowed (P=2), PAdES B-B profile
Path certified = folder.resolve("F-2026-0001-certified.pdf");
new PdfSigner(nebula, PdfSigner.Profile.PADES_B, null)
.sign(invoice, certified, issue.certifying(Certification.FORM_FILLING));
report(invoice, certified);
// 3) External signing: here the "service" is the signer itself; in production, an HSM or a remote service
Path external = folder.resolve("F-2026-0001-external.pdf");
signer.signExternally(invoice, external, issue, signer::sign);
report(invoice, external);
}
static void report(Path before, Path after) throws Exception {
System.out.printf("%s → %s: %,d → %,d bytes%n", before.getFileName(), after.getFileName(),
Files.size(before), Files.size(after));
}
}F-2026-0001.pdf → F-2026-0001-signed.pdf: 52,410 → 91,457 bytes
F-2026-0001.pdf → F-2026-0001-certified.pdf: 52,410 → 91,791 bytes
F-2026-0001.pdf → F-2026-0001-external.pdf: 52,410 → 91,457 bytesWhat's inside F-2026-0001-signed.pdf? Exactly what we studied in 07-02: the original 52,410 bytes untouched and a new revision with the /Sig dictionary (/ByteRange [0 52758 90648 809]), a Signature1 field with an invisible widget (rectangle [0 0 0 0]), /SigFlags 3 in the /AcroForm and a new cross-reference table. The CMS takes up 1,941 of the 18,944 bytes reserved; the rest are zeros.
If you open the signed invoice in Adobe Acrobat Reader you'll see the blue signature bar with a warning along the lines of "signature validity is UNKNOWN": the signature is intact, but the certificate is self-signed and Acrobat doesn't know it. That's the correct behaviour. In 07-04 we'll write our own verifier and tell it which certificates to trust.
Certification signature with DocMDP: Certification
The example's second signature is a certification signature with P=2. PDFBox has no high-level API for DocMDP; the official examples solve it with two methods in SigUtils that work at COS level. We adapt them in a class of our own:
package com.invoicelab.security;
import java.io.IOException;
import org.apache.pdfbox.cos.COSArray;
import org.apache.pdfbox.cos.COSDictionary;
import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.interactive.digitalsignature.PDSignature;
/** Certification signatures (DocMDP). Adapted from SigUtils, in PDFBox's official examples. */
public final class Certification {
/** No changes allowed. */
public static final int NO_CHANGES = 1;
/** Fill in forms and sign. */
public static final int FORM_FILLING = 2;
/** All the above plus annotations. */
public static final int ANNOTATIONS = 3;
private Certification() {
}
/** The document's DocMDP permission: 0 if it isn't certified; 1, 2 or 3 if it is. */
public static int permission(PDDocument document) {
COSDictionary perms = document.getDocumentCatalog().getCOSObject().getCOSDictionary(COSName.PERMS);
if (perms == null) {
return 0;
}
COSDictionary signature = perms.getCOSDictionary(COSName.DOCMDP); // the certification signature
if (signature == null) {
return 0;
}
COSArray references = signature.getCOSArray(COSName.REFERENCE);
if (references == null) {
return 0;
}
for (int i = 0; i < references.size(); i++) {
// getObject(i) resolves indirect references (unlike get(i))
if (references.getObject(i) instanceof COSDictionary reference
&& COSName.DOCMDP.equals(reference.getDictionaryObject(COSName.TRANSFORM_METHOD))) {
COSDictionary params = reference.getCOSDictionary(COSName.TRANSFORM_PARAMS);
int p = params == null ? FORM_FILLING : params.getInt(COSName.P, FORM_FILLING);
return p < 1 || p > 3 ? FORM_FILLING : p; // missing or invalid value → 2 (the standard says so)
}
}
return 0;
}permission follows the path we saw in 07-02: catalog → /Perms → /DocMDP (the certification signature) → /Reference → the dictionary whose /TransformMethod is /DocMDP → /TransformParams → /P. The standard says that a missing /P means 2, and the official example also treats out-of-range values as 2.
/** Turns the signature into a certification signature with the given permission. It must be the FIRST signature. */
public static void certify(PDDocument document, PDSignature signature, int permission) throws IOException {
if (permission < 1 || permission > 3) {
throw new IllegalArgumentException("Invalid DocMDP permission: " + permission);
}
for (PDSignature existing : document.getSignatureDictionaries()) {
if (!COSName.DOC_TIME_STAMP.equals(existing.getCOSObject().getItem(COSName.TYPE))
&& existing.getCOSObject().containsKey(COSName.CONTENTS)) {
throw new IOException("Only a document without approval signatures can be certified");
}
}
// /TransformParams << /Type /TransformParams /P n /V /1.2 >>
COSDictionary params = new COSDictionary();
params.setItem(COSName.TYPE, COSName.TRANSFORM_PARAMS);
params.setInt(COSName.P, permission);
params.setName(COSName.V, "1.2");
params.setDirect(true);
// /Reference [ << /Type /SigRef /TransformMethod /DocMDP /TransformParams ... >> ]
COSDictionary reference = new COSDictionary();
reference.setItem(COSName.TYPE, COSName.SIG_REF);
reference.setItem(COSName.TRANSFORM_METHOD, COSName.DOCMDP);
reference.setItem(COSName.DIGEST_METHOD, COSName.getPDFName("SHA1"));
reference.setItem(COSName.TRANSFORM_PARAMS, params);
reference.setDirect(true);
COSArray references = new COSArray();
references.add(reference);
references.setDirect(true);
signature.getCOSObject().setItem(COSName.REFERENCE, references);
// Catalog: /Perms << /DocMDP signature >>
COSDictionary catalog = document.getDocumentCatalog().getCOSObject();
COSDictionary perms = new COSDictionary();
perms.setItem(COSName.DOCMDP, signature);
catalog.setItem(COSName.PERMS, perms);
catalog.setNeedToBeUpdated(true);
perms.setNeedToBeUpdated(true);
}
}- Certification must be the first signature. If there are already approval signatures (the ones with
/Contents), we throw an exception. Document timestamps (/DocTimeStamp) don't count. - Direct objects (
setDirect(true)): the standard requires the dictionaries inside the signature to be direct (written inside the/Sigdictionary itself, not as separate referenced objects). /DigestMethod /SHA1: this is a legacy field that viewers expect; it isn't used for the cryptographic signature, which is still SHA-256.setNeedToBeUpdated(true)on the catalog and on/Perms: remember from 04-01 that in PDFBox 3's incremental save only objects marked as modified are written. Without that flag, the new revision's catalog wouldn't have/Perms. The signature dictionary is new, so it gets written without needing to be marked.
The checks we've made with this code:
| Attempt | Result |
|---|---|
Signing F-2026-0001-certified.pdf (P=2) with another approval signature |
Allowed |
| Signing a document certified with P=1 | IllegalStateException: Document certified with no changes allowed (DocMDP P=1) |
Certifying F-2026-0001-signed.pdf (it already has an approval signature) |
IOException: Only a document without approval signatures can be certified |
PAdES B-B profile
The certified invoice was also signed with the PADES_B profile. To comply with the basic PAdES level (ETSI EN 319 142-1) it isn't enough to change the SubFilter to ETSI.CAdES.detached; the CMS changes too:
- It must include the signing-certificate-v2 signed attribute, with the fingerprint of the signer's certificate. That way nobody can replace the certificate inside the CMS with another one with the same key.
- It must not include the signing-time attribute: in PAdES the declared time goes in the signature dictionary's
/M.
/** PAdES B-B: signing-certificate-v2 signed attribute and NO signingTime (the time goes in /M). */
private static CMSAttributeTableGenerator padesAttributes(X509Certificate certificate)
throws GeneralSecurityException {
byte[] fingerprint = MessageDigest.getInstance("SHA-256").digest(certificate.getEncoded());
SigningCertificateV2 signingCertificate = new SigningCertificateV2(new ESSCertIDv2(fingerprint)); // SHA-256 by default
ASN1EncodableVector attributes = new ASN1EncodableVector();
attributes.add(new Attribute(PKCSObjectIdentifiers.id_aa_signingCertificateV2, new DERSet(signingCertificate)));
DefaultSignedAttributeTableGenerator base = new DefaultSignedAttributeTableGenerator(new AttributeTable(attributes));
return params -> {
Hashtable<?, ?> withTime = base.getAttributes(params).toHashtable(); // contentType, messageDigest...
withTime.remove(CMSAttributes.signingTime);
return new AttributeTable(withTime);
};
}ESSCertIDv2(fingerprint)uses SHA-256 by default as the algorithm for the certificate's fingerprint.DefaultSignedAttributeTableGeneratorgenerates the standard attributes (contentType, messageDigest, signingTime, cmsAlgorithmProtection) plus the ones we pass in. We wrap it in a lambda (CMSAttributeTableGeneratoris a single-method interface) that removes signingTime from the result.
Inspecting the CMS with Bouncy Castle confirms the difference: the one in F-2026-0001-signed.pdf has 4 signed attributes, including signingTime; the one in F-2026-0001-certified.pdf also has 4, but with signing-certificate-v2 and without signingTime. Full PAdES conformance is certified by specialised validators (for example, the European Commission's DSS tool); use them if your case requires it.
External signing: HSMs and remote services
In production, a company's private key doesn't usually sit in a .p12 file: it lives in an HSM (hardware security module), on a smart card or in a cloud-based remote signing service, and it never leaves it. PDFBox caters for this with saveIncrementalForExternalSigning, which separates writing the PDF from calculating the signature:
public void signExternally(Path source, Path target, SignatureData data, SigningService service)
throws IOException {
Path temp = Files.createTempFile(target.toAbsolutePath().getParent(), "invoicelab-", ".tmp");
try {
try (PDDocument document = Loader.loadPDF(source.toFile());
SignatureOptions options = new SignatureOptions();
OutputStream output = new BufferedOutputStream(Files.newOutputStream(temp))) {
options.setPreferredSignatureSize(SIGNATURE_SIZE);
document.addSignature(prepareSignature(document, data), options); // no SignatureInterface
ExternalSigningSupport external = document.saveIncrementalForExternalSigning(output);
byte[] cms = service.sign(external.getContent()); // the ByteRange bytes
external.setSignature(cms); // writes the CMS into the placeholder
}
Files.move(temp, target, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE);
} finally {
Files.deleteIfExists(temp);
}
}sequenceDiagram
participant App as InvoiceLab
participant Doc as PDDocument
participant S as Signing service (HSM / cloud)
App->>Doc: addSignature(signature, options) — no SignatureInterface
App->>Doc: saveIncrementalForExternalSigning(output)
Doc-->>App: ExternalSigningSupport (PDF written with an empty placeholder)
App->>S: getContent() → ByteRange bytes (or their fingerprint)
S-->>App: signed CMS
App->>Doc: setSignature(cms) → written into the placeholder
addSignature(signature, options)registers the signature without aSignatureInterface.saveIncrementalForExternalSigningwrites the PDF with the placeholder and returns anExternalSigningSupport.getContent()gives the/ByteRangebytes;setSignature(cms)completes the file.- We don't use
PdfEditorhere because its incremental mode callssaveIncremental; we repeat its temporary file +ATOMIC_MOVEpattern. - In the example we pass
signer::signas the service (the method reference fitsSigningService), so the result is identical to internal signing: the same 91,457 bytes. In a real case,SigningServicewould call the provider's API. Many services don't receive the document but the fingerprint (or the fingerprint of the signed attributes) and return the raw RSA signature; the CMS is then assembled locally. The details depend on each provider.
The official examples (CreateVisibleSignature2) also show a "deferred" variant: save with setSignature(new byte[0]), remember the position getByteRange()[1] + 1 and write the CMS later with a RandomAccessFile, even from another process. Useful when signing takes time (for example, because a manager has to approve it on their phone).
Timestamp: TsaClient
/M states the time on the computer that signed, and that computer's clock may be wrong (or lying). A timestamp (RFC 3161) is issued by a time-stamping authority (TSA), a trusted third party that signs the statement "this fingerprint existed at this instant". Adding one to the signature is what turns a PAdES B-B signature into B-T.
sequenceDiagram
participant F as PdfSigner.sign
participant C as TsaClient
participant T as TSA (RFC 3161)
F->>F: CMS with Nebula's signature
F->>C: addTimestamp(cms)
C->>C: SHA-256 of the SIGNATURE (not of the PDF)
C->>T: POST application/timestamp-query<br/>(fingerprint + nonce)
T-->>C: TimeStampResponse (token signed by the TSA)
C->>C: validate: same fingerprint, same nonce
C-->>F: CMS + unsigned attribute signatureTimeStampToken
Note what gets timestamped: the fingerprint of Nebula's signature. That way the timestamp proves the signature already existed at that instant. And since the timestamp is added as an unsigned attribute of the CMS, it can be added after signing without invalidating anything.
We adapt TSAClient and ValidationTimeStamp from the official examples, using the JDK's HttpClient:
package com.invoicelab.security;
import java.io.IOException;
import java.math.BigInteger;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import org.bouncycastle.asn1.ASN1EncodableVector;
import org.bouncycastle.asn1.ASN1Primitive;
import org.bouncycastle.asn1.DERSet;
import org.bouncycastle.asn1.cms.Attribute;
import org.bouncycastle.asn1.cms.AttributeTable;
import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers;
import org.bouncycastle.cms.CMSSignedData;
import org.bouncycastle.cms.SignerInformation;
import org.bouncycastle.cms.SignerInformationStore;
import org.bouncycastle.tsp.TSPAlgorithms;
import org.bouncycastle.tsp.TSPException;
import org.bouncycastle.tsp.TimeStampRequest;
import org.bouncycastle.tsp.TimeStampRequestGenerator;
import org.bouncycastle.tsp.TimeStampResponse;
import org.bouncycastle.tsp.TimeStampToken;
/** Minimal RFC 3161 client. Adapted from TSAClient and ValidationTimeStamp (PDFBox's official examples). */
public final class TsaClient {
private static final SecureRandom RANDOM = new SecureRandom();
private final URI url;
private final HttpClient http = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(10)).build();
public TsaClient(String url) {
this.url = URI.create(url);
}
/** Asks the TSA for a timestamp over the SHA-256 of the data. */
public TimeStampToken timestamp(byte[] data) throws IOException {
byte[] fingerprint;
try {
fingerprint = MessageDigest.getInstance("SHA-256").digest(data);
} catch (NoSuchAlgorithmException e) {
throw new IOException(e);
}
TimeStampRequestGenerator generator = new TimeStampRequestGenerator();
generator.setCertReq(true); // we want the TSA's certificate in the response
BigInteger nonce = BigInteger.valueOf(RANDOM.nextInt(Integer.MAX_VALUE));
TimeStampRequest request = generator.generate(TSPAlgorithms.SHA256, fingerprint, nonce);
HttpRequest post = HttpRequest.newBuilder(url)
.timeout(Duration.ofSeconds(20))
.header("Content-Type", "application/timestamp-query")
.POST(HttpRequest.BodyPublishers.ofByteArray(request.getEncoded()))
.build();
HttpResponse<byte[]> httpResponse;
try {
httpResponse = http.send(post, HttpResponse.BodyHandlers.ofByteArray());
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new IOException("Request to the TSA interrupted", e);
}
if (httpResponse.statusCode() != 200) {
throw new IOException("The TSA responded with HTTP " + httpResponse.statusCode());
}
try {
TimeStampResponse response = new TimeStampResponse(httpResponse.body());
response.validate(request); // same fingerprint, same nonce, correct status
TimeStampToken token = response.getTimeStampToken();
if (token == null) {
throw new IOException("Response without a timestamp: " + response.getStatusString());
}
return token;
} catch (TSPException e) {
throw new IOException("Invalid TSA response", e);
}
}- The request carries only the fingerprint (32 bytes), never the document: the TSA doesn't see the invoice's content.
- The nonce is a random number that the TSA must return unchanged; it stops anyone slipping us an old response.
setCertReq(true)asks for the timestamp to include the TSA's certificate, which is needed to verify it later.response.validate(request)checks that the response corresponds to our request. Never skip it.
/** Adds to each signer a timestamp over THEIR signature (unsigned attribute signatureTimeStampToken). */
public CMSSignedData addTimestamp(CMSSignedData signed) throws IOException {
List<SignerInformation> signers = new ArrayList<>();
for (SignerInformation signer : signed.getSignerInfos().getSigners()) {
TimeStampToken token = timestamp(signer.getSignature());
ASN1EncodableVector attributes = signer.getUnsignedAttributes() == null
? new ASN1EncodableVector() : signer.getUnsignedAttributes().toASN1EncodableVector();
attributes.add(new Attribute(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken,
new DERSet(ASN1Primitive.fromByteArray(token.getEncoded()))));
signers.add(SignerInformation.replaceUnsignedAttributes(signer, new AttributeTable(attributes)));
}
return CMSSignedData.replaceSigners(signed, new SignerInformationStore(signers));
}
}Bouncy Castle objects are immutable: you can't "add" an attribute to a SignerInformation; you create a new one with replaceUnsignedAttributes and then a new CMSSignedData with replaceSigners. That's exactly what ValidationTimeStamp does in the official examples.
The example:
package com.invoicelab.examples;
import com.invoicelab.security.KeyVault;
import com.invoicelab.security.TsaClient;
import com.invoicelab.security.PdfSigner;
import com.invoicelab.security.PdfSigner.SignatureData;
import com.invoicelab.security.Secrets;
import java.nio.file.Files;
import java.nio.file.Path;
public class SignWithTimestamp {
/** PUBLIC TEST TSA (FreeTSA): for learning only. In production, the TSA you've contracted. */
private static final String TEST_TSA = "https://freetsa.org/tsr";
public static void main(String[] args) throws Exception {
String tsaUrl = System.getenv().getOrDefault("INVOICELAB_TSA_URL", TEST_TSA);
KeyVault.Credential nebula = KeyVault.load(Path.of("certificates/nebula-test.p12"),
Secrets.chars("INVOICELAB_P12_NEBULA"), "nebula");
PdfSigner signer = new PdfSigner(nebula, PdfSigner.Profile.PADES_B, new TsaClient(tsaUrl));
Path target = Path.of("output/signed/F-2026-0001-timestamped.pdf");
signer.sign(Path.of("output/F-2026-0001.pdf"), target,
SignatureData.approval("Nebula Distribution Ltd.", "Zaragoza", "Issue of invoice F-2026-0001"));
System.out.printf("Signed with a timestamp from %s → %s (%,d bytes)%n", tsaUrl, target, Files.size(target));
}
}Signed with a timestamp from https://freetsa.org/tsr → output/signed/F-2026-0001-timestamped.pdf (91,457 bytes)The file is the same size as without the timestamp: the CMS has grown from about 2 KB to 6,622 bytes, but it still fits in the 18,944-byte placeholder. This is why we reserve plenty of space.
WARNING about the TSA.
https://freetsa.org/tsris a free public test service, with no guarantee of availability and no legal value, and we use it only for learning. In production you use the TSA of a trusted provider you've contracted (qualified timestamps under eIDAS are issued by providers on the trusted list), usually with authentication. The URL goes in the configuration (INVOICELAB_TSA_URL), not in the code. If your network has no Internet access,TsaClientwill throw anIOExceptionand no file will be generated: the signing fails completely, it's never left half-done.
Signing in an existing field: signature.customer
The registration form from module 5 comes with an empty signature field, signature.customer. To sign in that field instead of creating a new one, prepareSignature does this:
PDSignatureField field = signatureField(document, data.field());
if (field.getSignature() != null) {
throw new IllegalStateException("The field " + data.field() + " is already signed");
}
field.getCOSObject().setItem(COSName.V, signature);addSignaturegoes through the document's signature fields and, if it finds one whose/Vis our signature dictionary, reuses it instead of creatingSignatureN. That's why it's enough to link the/Vbefore callingaddSignature.- We use
getCOSObject().setItem(COSName.V, signature)like the officialCreateVisibleSignature2example.field.setValue(signature)also works in PDFBox 3.0.8, but it tries to build appearances and writes the warning "Appearance generation for signature fields not implemented here". - A field that's already signed can't be signed again: we checked it,
IllegalStateException: The field signature.customer is already signed. A non-existent name givesIOException: There is no signature field named ….
Successive signatures: issuer and customer
Let's bring everything together in a complete scenario. Example Hardware has its own test certificate (07-02) and does two things: it signs "received in good order" on the invoice Nebula has already signed, and it signs its registration form in signature.customer. Then Nebula processes the registration with RegistrationIntake (05-04).
package com.invoicelab.examples;
import com.invoicelab.forms.RegistrationIntake;
import com.invoicelab.security.KeyVault;
import com.invoicelab.security.PdfSigner;
import com.invoicelab.security.PdfSigner.SignatureData;
import com.invoicelab.security.Secrets;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.LocalDateTime;
import org.apache.pdfbox.Loader;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.interactive.digitalsignature.PDSignature;
public class SuccessiveSignatures {
public static void main(String[] args) throws Exception {
KeyVault.Credential hardware = KeyVault.load(Path.of("certificates/hardware-test.p12"),
Secrets.chars("INVOICELAB_P12_HARDWARE"), "hardware");
PdfSigner customerSigner = new PdfSigner(hardware);
// 1) The customer signs the invoice already signed by Nebula: "received in good order"
Path signed = Path.of("output/signed/F-2026-0001-signed.pdf");
Path accepted = Path.of("output/signed/F-2026-0001-accepted.pdf");
customerSigner.sign(signed, accepted, SignatureData.approval("Example Hardware Co.", "Huesca",
"Received in good order"));
list(accepted);
// 2) The customer signs its registration form in the signature.customer field (created in 05-03)
Path registration = Path.of("output/registrations/registration-hardware.pdf");
Path signedRegistration = Path.of("output/registrations/registration-hardware-signed.pdf");
customerSigner.sign(registration, signedRegistration, SignatureData.approval("Example Hardware Co.", "Huesca",
"Customer registration request").inField("signature.customer"));
list(signedRegistration);
// 3) Nebula receives it: RegistrationIntake (05-04) detects the signature and only adds the number incrementally
RegistrationIntake.Result r = RegistrationIntake.process(signedRegistration, Path.of("output/registration-archive"),
"ALTA-2026-0002", LocalDateTime.of(2026, 1, 20, 10, 15));
System.out.println(r.status() + " → " + r.archivedFile() + " (" + Files.size(r.archivedFile()) + " bytes)");
}
static void list(Path pdf) throws Exception {
try (PDDocument document = Loader.loadPDF(new File(pdf.toString()))) {
System.out.println(pdf.getFileName() + " (" + Files.size(pdf) + " bytes)");
for (PDSignature signature : document.getSignatureDictionaries()) {
int[] r = signature.getByteRange();
System.out.printf(" %-28s %-24s ByteRange [%d %d %d %d]%n", signature.getName(), signature.getReason(),
r[0], r[1], r[2], r[3]);
}
}
}
}F-2026-0001-accepted.pdf (130654 bytes)
Nebula Distribution Ltd. Issue of invoice F-2026-0001 ByteRange [0 52758 90648 809]
Example Hardware Co. Received in good order ByteRange [0 91933 129823 831]
registration-hardware-signed.pdf (72586 bytes)
Example Hardware Co. Customer registration request ByteRange [0 33893 71783 803]
ARCHIVED_SIGNED → output/registration-archive/ALTA-2026-0002.pdf (73551 bytes)Let's interpret the numbers:
- In
F-2026-0001-accepted.pdf, Nebula's signature ends at90,648 + 809 = 91,457, the size ofF-2026-0001-signed.pdf: it covers its own revision and nothing more. The customer's ends at129,823 + 831 = 130,654, the whole file, including Nebula's signature. getSignatureDictionaries()returns the signatures in field order; to find out which is the latest in time, comparegetByteRange()[1](that's whatSigUtils.getLastRelevantSignaturedoes in the official examples).- The signed form goes through
RegistrationIntake, which detects the signature and only adds the registration number in an incremental save: 72,586 → 73,551 bytes. The customer's signature remains intact, but there's now a later revision. Is that acceptable? In 07-04 our verifier will tell us.
Common Mistakes and Tips
IOException: Can't write signature, not enough space; adjust it with SignatureOptions.setPreferredSignatureSize. The CMS doesn't fit in the placeholder. It happens above all when adding timestamps or long chains.PdfSignerreserves 18,944 bytes; increase it if your chain is large.- Closing
SignatureOptionsbefore saving. With visible signatures it causes closed-stream errors. The try-with-resources must wrap the save. - Saving with
save()instead ofsaveIncremental(). WithaddSignature, only the incremental save calculates and writes the signature. What's more, a fullsave()of an already signed document breaks the existing signatures. - Signing a
new PDDocument().saveIncrementalrequires a loaded document (04-01). Generate, save, then load and sign, asPdfSignerdoes withPdfEditor. - Forgetting
setSignDate. Without/M, many viewers mark the signature as invalid or don't show the date. - Mixing Bouncy Castle versions. Use the same version for
bcprov,bcutilandbcpkix; checkmvn dependency:treeif you seeNoSuchMethodError. - Calling
getAcroForm()without an argument before signing. It can regenerate appearances and alter the form in unexpected ways. UsegetAcroForm(null). - Certifying a document that already has signatures. Certification must be the first signature;
Certification.certifychecks this. - Leaving the TSA URL or the passwords in the code. Configuration and
Secrets. - Thinking the test signature "counts". Acrobat will show unknown validity, and that's correct: it's a self-signed certificate with no legal value.
Exercises
Exercise 1. Batch-sign January's five invoices (output/2026-01/F-2026-000N.pdf, from 04-04) and save them to output/2026-01-signed/ with the reason "Issue of invoice F-2026-000N". Reuse a single PdfSigner and measure the total time.
Exercise 2. Sign F-2026-0001.pdf with addSignature and saveIncremental directly (without PdfSigner.sign), using a PdfSigner as the SignatureInterface and setPreferredSignatureSize(1000). What happens and why? What minimum size would have been enough without a timestamp, and why isn't it a good idea to cut it that fine?
Exercise 3. Certify the invoice with P=1 (SignatureData...certifying(Certification.NO_CHANGES)) and then try to have Example Hardware sign "received in good order" on the result. Explain what happens and which certification level Nebula should use if it wants to allow that customer signature.
Solutions
Solution 1.
KeyVault.Credential nebula = KeyVault.load(Path.of("certificates/nebula-test.p12"),
Secrets.chars("INVOICELAB_P12_NEBULA"), "nebula");
PdfSigner signer = new PdfSigner(nebula);
Path target = Files.createDirectories(Path.of("output/2026-01-signed"));
long start = System.nanoTime();
try (DirectoryStream<Path> invoices = Files.newDirectoryStream(Path.of("output/2026-01"), "F-*.pdf")) {
for (Path invoice : invoices) {
String number = invoice.getFileName().toString().replace(".pdf", "");
signer.sign(invoice, target.resolve(invoice.getFileName()),
SignatureData.approval("Nebula Distribution Ltd.", "Zaragoza", "Issue of invoice " + number));
}
}
System.out.println("Batch signed in " + (System.nanoTime() - start) / 1_000_000 + " ms");On our machine, the five invoices are signed in about 90 ms. PdfSigner doesn't keep any per-signature state (each call creates its own PDSignature and SignatureOptions), so it can be reused without any problem; loading the credential just once avoids reading the .p12 five times. Bear in mind that DirectoryStream doesn't guarantee any order; if you need one, sort the list first.
Solution 2.
try (PDDocument doc = Loader.loadPDF(new File("output/F-2026-0001.pdf"));
SignatureOptions options = new SignatureOptions();
OutputStream output = new FileOutputStream("output/signed/small-placeholder.pdf")) {
options.setPreferredSignatureSize(1000);
PDSignature signature = new PDSignature();
signature.setFilter(PDSignature.FILTER_ADOBE_PPKLITE);
signature.setSubFilter(PDSignature.SUBFILTER_ADBE_PKCS7_DETACHED);
signature.setSignDate(Calendar.getInstance());
doc.addSignature(signature, new PdfSigner(nebula), options);
doc.saveIncremental(output);
}Result: IOException: Can't write signature, not enough space; adjust it with SignatureOptions.setPreferredSignatureSize. Our CMS takes up 1,941 bytes and there are only 1,000. The output file had already been created when PDFBox found out, and it's left unusable (in our test, at 0 bytes); that's why PdfSigner always writes to a temporary file: with PdfEditor the target wouldn't have been touched. Without a timestamp, about 2,000 bytes would be enough, but it's not a good idea to cut it that fine: the size changes with the key length, the certificate chain (a real three-certificate chain can triple it) and the timestamp (6,622 bytes with FreeTSA). Reserving 18,944 costs a few extra KB per signature and avoids failures in production.
Solution 3.
nebulaSigner.sign(Path.of("output/F-2026-0001.pdf"), Path.of("output/signed/p1.pdf"),
issue.certifying(Certification.NO_CHANGES));
customerSigner.sign(Path.of("output/signed/p1.pdf"), Path.of("output/signed/p1-accepted.pdf"),
SignatureData.approval("Example Hardware Co.", "Huesca", "Received in good order"));
// IllegalStateException: Document certified with no changes allowed (DocMDP P=1)The second signature fails in prepareSignature, before anything is written: with P=1 no change is allowed, not even another signature. If the customer used another tool that didn't make this check, they could add their signature, but viewers would mark Nebula's certification as invalid. To allow the "received in good order", Nebula must certify with P=2 (Certification.FORM_FILLING), which permits filling in forms and signing; that's what we did in F-2026-0001-certified.pdf.
Conclusion
In this lesson you've put into practice everything we saw in 07-02. You've added Bouncy Castle to the project, understood the addSignature + saveIncremental sequence and how PDFBox calls SignatureInterface.sign with the exact /ByteRange bytes, and generated the CMS with CMSSignedDataGenerator. You've built PdfSigner, which signs invisibly by reusing PdfEditor, certifies with DocMDP thanks to Certification (adapted from SigUtils), generates CMS with the PAdES B-B profile, signs through an external service with ExternalSigningSupport, adds timestamps with TsaClient and signs in existing fields such as signature.customer. You've also chained Nebula's signature with the customer's and seen how each one covers the previous revisions.
But signing is only half the job: we still need to check signatures. In the next lesson we'll write SignatureVerifier, which will extract the signed content of each signature, verify the CMS with Bouncy Castle, check whether the signature covers the whole document and whether there were later changes, and decide whether the certificate is trusted. And we'll give signatures a face: a visible appearance with Nebula's logo, the signer's name, the date and the reason, placed in the signature.customer field.
PDF Generation and Editing with Apache PDFBox
Module 1: PDF and PDFBox Fundamentals
- The PDF Format and Apache PDFBox
- Setting Up the Project with PDFBox 3
- Anatomy of a PDF: COS Objects, Pages and Resources
- Your First PDF: Creating, Saving and Loading Documents
- Debugging Tools: PDFDebugger and the Command Line
Module 2: Generating Content
- Pages and the Coordinate System
- Writing Text with PDPageContentStream and Standard Fonts
- Embedded TrueType Fonts and Unicode
- Text Layout: Measuring, Aligning and Wrapping Lines
- Vector Graphics: Lines, Shapes and Colours
- Inserting Images
Module 3: Business Documents
- Building Tables from Scratch
- Multi-Page Documents: Pagination, Headers and Footers
- Barcodes and QR Codes
- Designing a Reusable Document Generator
- Project: the Complete Invoice
Module 4: Editing Existing PDFs
- Load, Modify and Save: Full and Incremental Saves
- Adding Content to Existing Pages: Stamps and Watermarks
- Page Manipulation: Inserting, Removing, Rotating and Reordering
- Merging and Splitting Documents
- Overlays, Layers and Optional Content
- Document Metadata: Info and XMP
Module 5: AcroForm Forms
- Introduction to AcroForm Forms
- Reading and Filling In Forms
- Creating Forms Programmatically
- Form Appearances and Flattening
Module 6: Extraction and Analysis
- Extracting Text with PDFTextStripper
- Area-Based Extraction and Text Positions
- Extracting Images and Resources
- Rendering Pages to Images
- Bookmarks, Links and Annotations
Module 7: Security and Digital Signatures
- Encryption and Permissions
- Digital Signatures: Concepts and PDF Structure
- Signing Documents with PDFBox and Bouncy Castle
- Verifying Signatures and Visible Signatures
