In the previous lesson InvoiceLab learned to sign: invoice F-2026-0001 now carries Nebula Distribution's signature, and the registration form carries Example Hardware's in its signature.customer field. But a signature is only worth something if someone checks it, and that's the other half of the job: when Nebula receives a signed registration form, or when a customer wants to be sure the invoice hasn't been tampered with, it has to be verified. In this lesson, the last in the module, we'll build SignatureVerifier, which for each signature in a PDF extracts the signed bytes, verifies the CMS with Bouncy Castle, checks whether the signature covers the whole file, detects later revisions and decides whether the certificate is trusted. We'll use it to prove why a signed PDF can't be given a full save. And we'll finish by giving signatures a face: a visible appearance with Nebula's logo, the signer, the date and the reason, following the approach of the official CreateVisibleSignature2 example.
Contents
- What verifying a signature means
- Locating the signatures and the signed bytes
- Verifying the CMS with Bouncy Castle
- Coverage, later revisions and DocMDP
- Certificate validity and trust
- Signature statuses
- The
SignatureVerifierclass - Verifying InvoiceLab's signatures
- Demonstration: how a signature breaks
- Visible signatures: approaches in PDFBox
- The
SignatureAppearanceclass - Visibly signing the invoice and the registration form
What verifying a signature means
"The signature is valid" actually sums up several independent checks, and each one can fail on its own:
flowchart TD
A["Signature in the PDF"] --> B{"Does the /ByteRange point<br/>to a correct /Contents placeholder?"}
B -- no --> R1["BROKEN: file rewritten"]
B -- yes --> C{"Does the fingerprint of the signed bytes<br/>match the CMS's<br/>and is the RSA signature correct?"}
C -- no --> R2["BROKEN: content altered"]
C -- yes --> D{"Are there revisions after<br/>the signature?"}
D -- "yes, and DocMDP P=1" --> R3["DISALLOWED CHANGES"]
D -- "no, or allowed" --> E{"Certificate valid at signing time<br/>and trusted?"}
E -- no --> R4["IDENTITY NOT VERIFIED"]
E -- yes --> F{"Does it cover the whole file?"}
F -- yes --> R5["VALID"]
F -- no --> R6["VALID WITH LATER CHANGES"]
The first two check integrity (pure mathematics); the third, later changes (PDF structure); the fourth, authenticity (trust in the certificate). A good verifier reports each of them separately instead of giving a simple yes or no.
Locating the signatures and the signed bytes
PDFBox offers two ways of going through the signatures:
| Method | Returns | Use it when |
|---|---|---|
document.getSignatureDictionaries() |
List<PDSignature> of the signed fields |
You're only interested in the /Sig dictionary |
document.getSignatureFields() |
List<PDSignatureField>, signed or empty |
You also want the field name (signature.customer) |
For each PDSignature, three methods give us everything we need:
byte[] file = Files.readAllBytes(pdf);
int[] range = signature.getByteRange(); // [a, b, c, d]
byte[] cms = signature.getContents(file); // the CMS, read from the file's placeholder
byte[] signed = signature.getSignedContent(file); // bytes [a, a+b) + [c, c+d)getContents(byte[])reads the CMS from the file, at the position given by the/ByteRange, instead of using the value PDFBox has parsed. It's the safest option: if the/ByteRangeand the placeholder don't match, we'll notice.getSignedContent(byte[])concatenates the two ranges. They are, byte for byte, the same data ourPdfSigner.signreceived when signing.- We load the file into a
byte[]and open the document withLoader.loadPDF(byte[])from that same array: that way PDFBox and our checks see exactly the same bytes.
Verifying the CMS with Bouncy Castle
With the signed bytes and the CMS, Bouncy Castle reconstructs the detached signature:
CMSSignedData data = new CMSSignedData(new CMSProcessableByteArray(signed), cms);
SignerInformation info = data.getSignerInfos().getSigners().iterator().next();
Collection<X509CertificateHolder> matches = data.getCertificates().getMatches(info.getSID());
X509Certificate certificate = new JcaX509CertificateConverter().getCertificate(matches.iterator().next());
boolean correct = info.verify(new JcaSimpleSignerInfoVerifierBuilder().build(certificate));new CMSSignedData(content, cms): the two-argument constructor is the one for detached signatures: we supply separately the data that isn't inside the CMS.getSignerInfos().getSigners(): the signers. In our PDF signatures there's exactly one.getCertificates().getMatches(info.getSID()): the signer's certificate, looked up by its identifier (issuer + serial number) among the ones the CMS carries. If it isn't there, we can't verify.info.verify(...): checks two things at once: that the fingerprint ofsignedmatches the CMS's messageDigest attribute, and that the RSA signature over the signed attributes is correct with the certificate's public key.
verify already compares the fingerprint, but in SignatureVerifier we also do it explicitly, for two reasons: so you can see there's no magic (it's the check we did with MessageDigest in 07-02) and so we can give a clear message ("the fingerprint doesn't match: the document has been modified after signing") instead of a plain false.
Important: a valid CMS only says that someone with that key signed those bytes. Who that someone is is decided by the trust check, and whether those bytes are the whole document, by the coverage check.
Coverage, later revisions and DocMDP
Does it cover the whole file? This is the check made by the official ShowSignature example:
a == 0: the first range starts at the beginning.c + d == file.length: the second range reaches the end.b + contents.length × 2 + 2 == c: the placeholder is exactly the/Contentsin hexadecimal plus the<>. If not, someone could have hidden data in the placeholder.
How many revisions come after it? Each incremental revision ends with %%EOF. Counting the markers from c + d onwards gives the number of revisions added after the signature. It's a simple heuristic that's good enough for our files (in theory, an %%EOF could appear inside a stream; a rigorous analysis would walk the cross-reference tables via /Prev).
Were they allowed? This is where DocMDP comes in (07-02 and 07-03):
| Situation | Interpretation |
|---|---|
| No certification, later revisions | Normal if they're other signatures or filled-in fields. The verifier warns; a person or a business rule decides |
| Certified with P=2 or P=3, later revisions | Valid if only fields were filled in, signatures added (and, with P=3, annotations made). You need to check what changed |
| Certified with P=1, later revisions | The certification has been violated |
Deciding exactly what changed in a revision requires comparing the objects of both versions (which is what Adobe Acrobat does); that's beyond the scope of this course. But we can do something very useful with what we already know: recover the version exactly as it was signed (bytes 0 to c + d, which form a complete PDF) and compare it visually with the current one using VisualComparator (06-04).
Certificate validity and trust
An intact CMS signed by an unknown certificate proves nothing about identity. The checks:
| Check | How | In SignatureVerifier |
|---|---|---|
| Validity at signing time | certificate.checkValidity(date), with the timestamp's date if there is one, or /M if not |
Yes |
| Chain of trust up to an anchor | Build the path signer → intermediates → root and check each signature (Java's CertPathValidator with PKIX) |
Simplified: the certificate is an anchor or was issued directly by an anchor |
| Revocation | Consult the CRL (list of revoked certificates published by the CA) or the OCSP service (online query) | No: conceptual only |
| Key usage | KeyUsage with digitalSignature or nonRepudiation |
No (we checked it when loading with keytool) |
| Timestamp | That the timestamped fingerprint is this signature's; ideally, also trust in the TSA | Partial: the fingerprint yes, trust in the TSA no |
About revocation: if a certificate's private key is compromised, the CA revokes it, and signatures made after the revocation must not be accepted. Signatures made before remain valid, which is why it matters so much to know when the signing happened (hence the timestamp) and to keep the revocation information from that moment inside the PDF (PAdES B-LT level, 07-02). For full verification with European trusted lists, revocation and PAdES levels, production systems rely on specialised libraries such as DSS (from the European Commission) or on a validation service; our SignatureVerifier is a teaching tool that helps you understand each piece and is useful for internal checks.
Trust anchors are the certificates we decide to trust in advance. In production they would be the recognised root CAs; in the course, our two self-signed test certificates.
Signature statuses
| Status | Integrity | Later changes | Trust | What to do |
|---|---|---|---|---|
VALID |
✓ | No | ✓ | Accept |
VALID_WITH_LATER_CHANGES |
✓ | Yes (not prohibited by DocMDP) | ✓ | Accept the signature; review what changed afterwards (signed version) |
DISALLOWED_CHANGES |
✓ | Yes, with DocMDP P=1 | — | Reject: the document was modified against what was certified |
IDENTITY_NOT_VERIFIED |
✓ | — | ✗ | The document hasn't been altered, but we don't know who signed it: confirm the certificate through another channel |
BROKEN |
✗ | — | — | Reject: the signed bytes have been altered or the file was rewritten |
The SignatureVerifier class
package com.invoicelab.security;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.security.cert.CertificateExpiredException;
import java.security.cert.CertificateNotYetValidException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Set;
import org.apache.pdfbox.Loader;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.interactive.digitalsignature.PDSignature;
import org.apache.pdfbox.pdmodel.interactive.form.PDSignatureField;
import org.bouncycastle.asn1.ASN1OctetString;
import org.bouncycastle.asn1.cms.Attribute;
import org.bouncycastle.asn1.cms.CMSAttributes;
import org.bouncycastle.asn1.pkcs.PKCSObjectIdentifiers;
import org.bouncycastle.cert.X509CertificateHolder;
import org.bouncycastle.cert.jcajce.JcaX509CertificateConverter;
import org.bouncycastle.cms.CMSException;
import org.bouncycastle.cms.CMSProcessableByteArray;
import org.bouncycastle.cms.CMSSignedData;
import org.bouncycastle.cms.SignerInformation;
import org.bouncycastle.cms.jcajce.JcaSimpleSignerInfoVerifierBuilder;
import org.bouncycastle.operator.OperatorCreationException;
import org.bouncycastle.tsp.TSPException;
import org.bouncycastle.tsp.TimeStampToken;
/** Verifies a PDF's signatures: cryptographic integrity, coverage, later changes and trust. */
public final class SignatureVerifier {
public enum Status {
/** Intact, covers the whole file and the signer is trusted. */
VALID,
/** Intact and trusted, but revisions have been added after signing. */
VALID_WITH_LATER_CHANGES,
/** Intact, but the document is certified with no changes (P=1) and has been modified anyway. */
DISALLOWED_CHANGES,
/** Intact, but we can't trust the identity (unknown or out-of-date certificate). */
IDENTITY_NOT_VERIFIED,
/** The signed bytes have been altered or the CMS isn't valid: the signature is broken. */
BROKEN
}
public record Result(String field, String signer, Calendar date, String reason, String subFilter,
boolean intact, boolean coversAll, int laterRevisions, int docMdp,
boolean trusted, Date timestamp, Status status, List<String> warnings) {
}
private final Set<X509Certificate> trustAnchors;
/** anchors: certificates we trust (in production, the root CAs on the trusted list). */
public SignatureVerifier(Set<X509Certificate> anchors) {
this.trustAnchors = Set.copyOf(anchors);
}
public List<Result> verify(Path pdf) throws IOException {
byte[] file = Files.readAllBytes(pdf);
List<Result> results = new ArrayList<>();
try (PDDocument document = Loader.loadPDF(file)) {
int docMdp = Certification.permission(document);
for (PDSignatureField field : document.getSignatureFields()) {
PDSignature signature = field.getSignature();
if (signature != null) { // empty fields aren't signatures
results.add(verify(file, field.getFullyQualifiedName(), signature, docMdp));
}
}
}
return results;
}Resultgathers everything we've checked: declared data (field,reason,date), verified data (signer, taken from the certificate, not from/Name) and each check separately, plus the summarystatusand a list of human-readablewarnings.Certification.permission(07-03) gives us the document's DocMDP level.
The heart of the class, one signature at a time:
private Result verify(byte[] file, String field, PDSignature signature, int docMdp) throws IOException {
List<String> warnings = new ArrayList<>();
int[] range = signature.getByteRange();
byte[] cms;
byte[] signed;
try {
cms = signature.getContents(file); // the CMS, read from the file's placeholder
signed = signature.getSignedContent(file); // the bytes covered by /ByteRange
} catch (IOException | RuntimeException e) {
// Typical of a FULL save after signing: the offsets no longer point to the placeholder
warnings.add("The /ByteRange doesn't point to the signature: the file has been rewritten (" + e.getClass().getSimpleName() + ")");
return new Result(field, signature.getName(), signature.getSignDate(), signature.getReason(), signature.getSubFilter(),
false, false, 0, docMdp, false, null, Status.BROKEN, warnings);
}
// 1) Does it cover the whole file? Is the placeholder exactly /Contents?
long signedEnd = (long) range[2] + range[3];
boolean coversAll = range[0] == 0 && signedEnd == file.length;
if (range[1] + signature.getContents().length * 2L + 2 != range[2]) {
warnings.add("The ByteRange placeholder doesn't match /Contents: possible tampering");
}
int revisions = countEofMarkers(file, (int) Math.min(signedEnd, file.length));
// 2) Cryptographic integrity: fingerprint + CMS signature
boolean intact = false;
String signer = signature.getName();
boolean trusted = false;
Date timestamp = null;
try {
CMSSignedData data = new CMSSignedData(new CMSProcessableByteArray(signed), cms);
SignerInformation info = data.getSignerInfos().getSigners().iterator().next();
@SuppressWarnings("unchecked")
Collection<X509CertificateHolder> matches = data.getCertificates().getMatches(info.getSID());
if (matches.isEmpty()) {
throw new IOException("The CMS doesn't include the signer's certificate");
}
X509Certificate certificate = new JcaX509CertificateConverter().getCertificate(matches.iterator().next());
signer = KeyVault.commonName(certificate);
boolean digestMatches = digestMatches(info, signed, warnings);
intact = digestMatches && info.verify(new JcaSimpleSignerInfoVerifierBuilder().build(certificate));
// 3) Timestamp (if any) and trust in the certificate
timestamp = timestampOf(info, warnings);
Date moment = timestamp != null ? timestamp : signature.getSignDate() != null ? signature.getSignDate().getTime() : new Date();
trusted = validAt(certificate, moment, warnings) && isTrusted(certificate, warnings);
} catch (CMSException | OperatorCreationException | GeneralSecurityException e) {
warnings.add("Cryptographic error: " + e.getMessage());
}
if (revisions > 0 && docMdp >= Certification.FORM_FILLING) {
warnings.add("Certified document (P=" + docMdp + ") with later changes: check that they are only "
+ "the allowed ones (filling in fields, signing" + (docMdp == 3 ? ", annotating)" : ")"));
}
Status status = !intact ? Status.BROKEN
: revisions > 0 && docMdp == Certification.NO_CHANGES ? Status.DISALLOWED_CHANGES
: !trusted ? Status.IDENTITY_NOT_VERIFIED
: coversAll ? Status.VALID
: Status.VALID_WITH_LATER_CHANGES;
return new Result(field, signer, signature.getSignDate(), signature.getReason(), signature.getSubFilter(),
intact, coversAll, revisions, docMdp, trusted, timestamp, status, warnings);
}- First
try: if the file has been rewritten, the/ByteRange(which still says the same thing) points to bytes that are no longer the placeholder, andgetContentsfails when it reads something that isn't hexadecimal. We turn that into aBROKENresult instead of letting an exception stop the verification of the other signatures. signeris taken from the certificate (commonName, 07-02)./Nameis only what the signer declared.- Order of the statuses: integrity comes first (if the bytes were altered, nothing else matters); then a DocMDP violation; then trust; and, finally, coverage.
- The reference moment for the certificate's validity is the timestamp's if there is one (reliable) and
/Mif not (declared).
The helper methods:
/** Explicit check (verify() also does it): SHA-256 of the signed bytes = the CMS's messageDigest. */
private static boolean digestMatches(SignerInformation info, byte[] signed, List<String> warnings)
throws GeneralSecurityException {
Attribute attribute = info.getSignedAttributes() == null ? null
: info.getSignedAttributes().get(CMSAttributes.messageDigest);
if (attribute == null) {
warnings.add("The CMS has no messageDigest attribute");
return false;
}
byte[] declared = ASN1OctetString.getInstance(attribute.getAttrValues().getObjectAt(0)).getOctets();
String algorithm = info.getDigestAlgOID(); // 2.16.840.1.101.3.4.2.1 = SHA-256
byte[] computed = MessageDigest.getInstance(algorithm).digest(signed);
if (!MessageDigest.isEqual(declared, computed)) {
warnings.add("The fingerprint doesn't match: the document has been modified after signing");
return false;
}
return true;
}- The messageDigest attribute is an ASN.1
OCTET STRINGholding the fingerprint the signer calculated. MessageDigest.getInstanceaccepts the algorithm's OID (2.16.840.1.101.3.4.2.1is SHA-256), so it works with whatever algorithm the signer used.MessageDigest.isEqualcompares in constant time; it's the correct way to compare cryptographic values.
private static Date timestampOf(SignerInformation info, List<String> warnings) {
if (info.getUnsignedAttributes() == null) {
return null;
}
Attribute attribute = info.getUnsignedAttributes().get(PKCSObjectIdentifiers.id_aa_signatureTimeStampToken);
if (attribute == null) {
return null;
}
try {
TimeStampToken token = new TimeStampToken(new CMSSignedData(
attribute.getAttrValues().getObjectAt(0).toASN1Primitive().getEncoded()));
byte[] expected = MessageDigest.getInstance(token.getTimeStampInfo().getMessageImprintAlgOID().getId())
.digest(info.getSignature());
if (!MessageDigest.isEqual(expected, token.getTimeStampInfo().getMessageImprintDigest())) {
warnings.add("The timestamp doesn't correspond to this signature");
return null;
}
warnings.add("Timestamp from " + token.getSID().getIssuer() + " (trust in the TSA not checked)");
return token.getTimeStampInfo().getGenTime();
} catch (IOException | CMSException | TSPException | GeneralSecurityException e) {
warnings.add("Unreadable timestamp: " + e.getMessage());
return null;
}
}This is the reverse of TsaClient.addTimestamp (07-03): we look for the unsigned signatureTimeStampToken attribute, turn it into a TimeStampToken and check that the timestamped fingerprint (message imprint) is that of this signature. A complete verifier would also validate the timestamp's signature and the TSA's chain, as SigUtils.validateTimestampToken does in the official examples.
private static boolean validAt(X509Certificate certificate, Date moment, List<String> warnings) {
try {
certificate.checkValidity(moment);
return true;
} catch (CertificateExpiredException | CertificateNotYetValidException e) {
warnings.add("Certificate not valid at the time of signing");
return false;
}
}
/** Simplified trust: the certificate is an anchor or was issued directly by an anchor. */
private boolean isTrusted(X509Certificate certificate, List<String> warnings) {
for (X509Certificate anchor : trustAnchors) {
if (anchor.equals(certificate)) {
return true;
}
if (anchor.getSubjectX500Principal().equals(certificate.getIssuerX500Principal())) {
try {
certificate.verify(anchor.getPublicKey());
return true;
} catch (GeneralSecurityException e) {
// same issuer name, different key: not trusted
}
}
}
warnings.add(KeyVault.selfSigned(certificate)
? "Self-signed certificate that isn't among the trust anchors"
: "Unknown certificate issuer");
return false;
}isTrusted doesn't rely on names: if the certificate's issuer has the same name as an anchor, it checks with verify that it really was signed by the anchor's key. Anyone can create a certificate that says "issued by InvoiceLab Test CA"; nobody without its private key can sign it.
Finally, the revision counter and recovering the signed version:
/** How many %%EOF markers there are from the given position: each one closes a later revision. */
static int countEofMarkers(byte[] file, int from) {
byte[] marker = "%%EOF".getBytes(StandardCharsets.US_ASCII);
int count = 0;
for (int i = from; i <= file.length - marker.length; i++) {
if (Arrays.equals(file, i, i + marker.length, marker, 0, marker.length)) {
count++;
}
}
return count;
}
/** Recovers the document version exactly as it was signed: the bytes up to the end of the ByteRange. */
public static void extractSignedVersion(Path pdf, String field, Path target) throws IOException {
byte[] file = Files.readAllBytes(pdf);
try (PDDocument document = Loader.loadPDF(file)) {
PDSignature signature = PdfSigner.signatureField(document, field).getSignature();
if (signature == null) {
throw new IOException("The field " + field + " isn't signed");
}
int[] range = signature.getByteRange();
Files.write(target, Arrays.copyOf(file, range[2] + range[3]));
}
}
}extractSignedVersion works because an incremental save never modifies earlier bytes: cutting the file at the end of the /ByteRange gives back exactly the PDF that was signed, with its %%EOF. We reuse PdfSigner.signatureField (07-03), which has package visibility.
Verifying InvoiceLab's signatures
package com.invoicelab.examples;
import com.invoicelab.security.Protection;
import com.invoicelab.security.SignatureVerifier;
import java.nio.file.Path;
import java.util.Set;
public class VerifySignatures {
public static void main(String[] args) throws Exception {
// We trust the two test certificates (in production: the CAs on the trusted list)
SignatureVerifier verifier = new SignatureVerifier(Set.of(
Protection.readCertificate(Path.of("certificates/nebula-test.cer")),
Protection.readCertificate(Path.of("certificates/hardware-test.cer"))));
String[] files = args.length > 0 ? args : new String[] {
"output/signed/F-2026-0001-signed.pdf",
"output/signed/F-2026-0001-accepted.pdf",
"output/signed/F-2026-0001-certified.pdf",
"output/registration-archive/ALTA-2026-0002.pdf" };
for (String file : files) {
System.out.println(file);
for (SignatureVerifier.Result r : verifier.verify(Path.of(file))) {
System.out.printf(" [%s] %s · %s · %s%n", r.field(), r.signer(), r.reason(), r.status());
System.out.printf(" intact=%s, covers all=%s, later revisions=%d, DocMDP=%d, trusted=%s%n",
r.intact(), r.coversAll(), r.laterRevisions(), r.docMdp(), r.trusted());
r.warnings().forEach(w -> System.out.println(" ! " + w));
}
}
}
}Protection.readCertificate (07-01) reads the .cer files we exported in 07-02. Output:
output/signed/F-2026-0001-signed.pdf
[Signature1] Nebula Distribution (TEST) · Issue of invoice F-2026-0001 · VALID
intact=true, covers all=true, later revisions=0, DocMDP=0, trusted=true
output/signed/F-2026-0001-accepted.pdf
[Signature1] Nebula Distribution (TEST) · Issue of invoice F-2026-0001 · VALID_WITH_LATER_CHANGES
intact=true, covers all=false, later revisions=1, DocMDP=0, trusted=true
[Signature2] Example Hardware (TEST) · Received in good order · VALID
intact=true, covers all=true, later revisions=0, DocMDP=0, trusted=true
output/signed/F-2026-0001-certified.pdf
[Signature1] Nebula Distribution (TEST) · Issue of invoice F-2026-0001 · VALID
intact=true, covers all=true, later revisions=0, DocMDP=2, trusted=true
output/registration-archive/ALTA-2026-0002.pdf
[signature.customer] Example Hardware (TEST) · Customer registration request · VALID_WITH_LATER_CHANGES
intact=true, covers all=false, later revisions=1, DocMDP=0, trusted=trueEach line tells a story you already know:
- Nebula's signature in
accepted.pdfis still intact, but it has a later revision: the customer's signature. That's what you'd expect with successive signatures. - In
ALTA-2026-0002.pdfthe later revision is the oneRegistrationIntakeadded with the registration number (07-03). The customer's signature hasn't been broken, and the verifier warns us that the document changed afterwards. - With the timestamped invoice (
F-2026-0001-timestamped.pdf) you also get the warning "Timestamp from O=Free TSA, … (trust in the TSA not checked)". - If we create the verifier without anchors (
Set.of()), they all becomeIDENTITY_NOT_VERIFIEDwith the warning "Self-signed certificate that isn't among the trust anchors". That's the same thing Acrobat shows ("validity unknown").
Demonstration: how a signature breaks
Since 04-01 we've been repeating that a signed document must only be modified incrementally. Now we can prove it with three manipulations:
package com.invoicelab.examples;
import com.invoicelab.editing.PdfEditor;
import com.invoicelab.editing.Stamper;
import com.invoicelab.extraction.VisualComparator;
import com.invoicelab.security.Protection;
import com.invoicelab.security.SignatureVerifier;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.time.LocalDate;
import java.util.Set;
public class BreakSignature {
public static void main(String[] args) throws Exception {
SignatureVerifier verifier = new SignatureVerifier(
Set.of(Protection.readCertificate(Path.of("certificates/nebula-test.cer"))));
Path signed = Path.of("output/signed/F-2026-0001-signed.pdf");
Path folder = Files.createDirectories(Path.of("output/signed/tests"));
// 1) FULL save, without touching anything
Path full = folder.resolve("full.pdf");
PdfEditor.edit(signed, full, PdfEditor.Mode.FULL, document -> { });
show(verifier, "Full save", full);
// 2) Change one byte inside the signed range: the year in /M, 2026 → 2025
byte[] bytes = Files.readAllBytes(signed);
int pos = new String(bytes, StandardCharsets.ISO_8859_1).indexOf("/M (D:2026") + "/M (D:202".length();
bytes[pos] = '5';
Path oneByte = folder.resolve("one-byte.pdf");
Files.write(oneByte, bytes);
show(verifier, "One byte changed", oneByte);
// 3) "PAID" stamp INCREMENTALLY on the certified invoice (P=2)
Path certified = Path.of("output/signed/F-2026-0001-certified.pdf");
Path paid = folder.resolve("certified-paid.pdf");
PdfEditor.edit(certified, paid, PdfEditor.Mode.INCREMENTAL,
document -> new Stamper(document).paidStamp(document.getPage(0), LocalDate.of(2026, 2, 10)));
show(verifier, "Incremental stamp", paid);
// What has changed? We compare the signed version with the current one (VisualComparator, 06-04)
Path version = folder.resolve("signed-version.pdf");
SignatureVerifier.extractSignedVersion(paid, "Signature1", version);
for (VisualComparator.Result r : VisualComparator.compare(version, paid, 72, 16, folder)) {
System.out.printf(" page %d: %,d differing pixels (%.2f %%)%n", r.page(), r.different(), r.percentage());
}
}
static void show(SignatureVerifier verifier, String scenario, Path pdf) throws Exception {
for (SignatureVerifier.Result r : verifier.verify(pdf)) {
System.out.printf("%-18s → %s %s%n", scenario, r.status(), r.warnings());
}
}
}Full save → BROKEN [The /ByteRange doesn't point to the signature: the file has been rewritten (IOException)]
One byte changed → BROKEN [The fingerprint doesn't match: the document has been modified after signing, Certificate not valid at the time of signing]
Incremental stamp → VALID_WITH_LATER_CHANGES [Certified document (P=2) with later changes: check that they are only the allowed ones (filling in fields, signing)]
page 1: 2,746 differing pixels (0.55 %)
page 2: 0 differing pixels (0.00 %)Let's analyse each case:
- Full save with no changes. Just loading and saving is enough. PDFBox rewrites the entire file (in PDF 1.6, with object streams): all the offsets change, the signature dictionary is copied as is with its old
/ByteRange, and that/ByteRangenow points to bytes that aren't the placeholder. PDFBox can't even read the CMS (Invalid hex string). There's no way to "repair" this: the original signature no longer has anything to be compared against. - A single byte. Changing the year of the declared date
/M(which is inside the signed range) is enough for the fingerprint not to match. What's more, since the declared date is now in 2025, before our test certificate was issued, the verifier adds that the certificate wasn't valid: two alarms for the price of one. - "PAID" stamp, incrementally. Nebula's signature is still intact: the signed bytes haven't been touched. But there's a later revision and the invoice was certified with P=2, which only allows filling in fields and signing. Stamping content onto the page is not an allowed change; our verifier can't be sure of that from the structure alone, but the visual comparison between the signed version and the current one gives it away: 2,746 differing pixels on page 1, exactly those of the stamp we measured in 06-04. Adobe Acrobat would mark this certification as invalid. With P=1, our verifier gives
DISALLOWED_CHANGESstraight away.
The practical lesson for InvoiceLab: on a signed PDF, only incremental saves, and only the changes the signature allows. If an invoice that's been signed has to be stamped "PAID", either do it before signing, or accept that the stamp will show up as a change after the signature (and don't certify with P=1 or P=2).
Visible signatures: approaches in PDFBox
A visible signature is a normal signature whose widget has a rectangle on the page and an appearance (/AP), a form XObject that the viewer draws. We'll repeat what we said in 07-02 because it's crucial: the appearance is just a drawing. Anyone can draw a box saying "Digitally signed by…"; what proves anything is the cryptographic verification.
PDFBox offers two approaches, both in the official examples:
| Approach | Official example | Advantages | Drawbacks |
|---|---|---|---|
PDVisibleSignDesigner + PDVisibleSigProperties |
CreateVisibleSignature |
Few lines for an image | Not very flexible; the API builds the template internally |
Your own template with PDFormXObject and PDPageContentStream |
CreateVisibleSignature2 |
Full control: text, fonts, colours, images. It's the one recommended by the PDFBox developers | More code |
We'll use the second. The idea: build a one-page template PDF, the same size as the original page, with a signature field whose widget already has the appearance drawn; we pass it to SignatureOptions.setVisualSignature(InputStream) and PDFBox copies that appearance into the signed document. It fits the PdfSigner.Appearance interface we left ready in 07-03.
The SignatureAppearance class
package com.invoicelab.security;
import com.invoicelab.pdf.NebulaColors;
import com.invoicelab.pdf.InvoiceLabFonts;
import com.invoicelab.pdf.Images;
import com.invoicelab.pdf.TextMetrics;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.cert.X509Certificate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.PDResources;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.common.PDStream;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.graphics.form.PDFormXObject;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationWidget;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAppearanceDictionary;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAppearanceStream;
import org.apache.pdfbox.pdmodel.interactive.digitalsignature.PDSignature;
import org.apache.pdfbox.pdmodel.interactive.form.PDAcroForm;
import org.apache.pdfbox.pdmodel.interactive.form.PDSignatureField;
/** Visible signature appearance in the style of CreateVisibleSignature2: logo + signer + date + reason. */
public final class SignatureAppearance implements PdfSigner.Appearance {
private static final DateTimeFormatter DATE =
DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm").withZone(ZoneId.of("Europe/Madrid"));
private final X509Certificate certificate;
private final String logoPath; // null = no logo
private final PDRectangle positionWithoutField; // used if we're not signing in an existing field
public SignatureAppearance(X509Certificate certificate, String logoPath, PDRectangle positionWithoutField) {
this.certificate = certificate;
this.logoPath = logoPath;
this.positionWithoutField = positionWithoutField;
}
@Override
public InputStream template(PDDocument original, PDSignature signature, int page, PDRectangle rect)
throws IOException {
if (original.getPage(page).getRotation() != 0) {
throw new IOException("This appearance doesn't support rotated pages (see CreateVisibleSignature2)");
}
PDRectangle box = rect != null ? rect : positionWithoutField;
try (PDDocument template = new PDDocument()) {
// 1) A one-page document of the same size, with a signature field and its widget
PDPage sheet = new PDPage(original.getPage(page).getMediaBox());
template.addPage(sheet);
PDAcroForm form = new PDAcroForm(template);
template.getDocumentCatalog().setAcroForm(form);
PDSignatureField field = new PDSignatureField(form);
form.getFields().add(field);
form.setSignaturesExist(true);
form.setAppendOnly(true);
PDAnnotationWidget widget = field.getWidgets().get(0);
widget.setRectangle(box);
// 2) The appearance: a form XObject the size of the box, with its origin at (0, 0)
PDFormXObject xobject = new PDFormXObject(new PDStream(template));
xobject.setResources(new PDResources());
xobject.setFormType(1);
xobject.setBBox(new PDRectangle(box.getWidth(), box.getHeight()));
PDAppearanceStream appearance = new PDAppearanceStream(xobject.getCOSObject());
PDAppearanceDictionary dictionary = new PDAppearanceDictionary();
dictionary.setNormalAppearance(appearance);
widget.setAppearance(dictionary);
try (PDPageContentStream cs = new PDPageContentStream(template, appearance)) {
draw(cs, template, signature, box.getWidth(), box.getHeight());
}
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
template.save(bytes);
return new ByteArrayInputStream(bytes.toByteArray());
}
}Step by step, following createVisualSignatureTemplate from the official example:
- A page of the same size as the original, with an
/AcroFormand aPDSignatureField. The widget's rectangle is the existing field's (rect) or, if we're signing without a field, the one we were given when constructing the appearance. - The appearance XObject has a
/BBoxthe size of the box, with its origin at(0, 0): inside the appearance we draw in local coordinates, without worrying about where the box is on the page. It's the same idea as the field appearances we drew by hand in 05-03. new PDPageContentStream(template, appearance): the constructor that writes to an appearance stream instead of a page.- We save the template in memory and return an
InputStream.PdfSignerwill pass it toSignatureOptions.setVisualSignature, which is why those options must stay open until the save. - Rotated pages: the official example adjusts the form matrix according to
/Rotate(90, 180, 270). To keep the lesson from growing too long, our version only supports unrotated pages and says so clearly with an exception, instead of drawing the signature askew.
The drawing reuses the utilities from module 2:
private void draw(PDPageContentStream cs, PDDocument template, PDSignature signature, float width, float height)
throws IOException {
// Background and border
cs.setNonStrokingColor(NebulaColors.BACKGROUND_BLUE);
cs.setStrokingColor(NebulaColors.BLUE);
cs.setLineWidth(0.8f);
cs.addRect(0.4f, 0.4f, width - 0.8f, height - 0.8f);
cs.fillAndStroke();
float x = 6;
if (logoPath != null) {
PDImageXObject logo = Images.loadResource(template, logoPath);
Images.Size s = Images.drawFitted(cs, logo, x, height - 6, 60, height - 12);
x += s.width() + 8;
}
InvoiceLabFonts fonts = new InvoiceLabFonts(template);
PDFont regular = fonts.regular();
PDFont bold = fonts.bold();
float textWidth = width - x - 6;
String[][] lines = {
{ "Digitally signed by", "r" },
{ KeyVault.commonName(certificate), "b" },
{ "Date: " + DATE.format(signature.getSignDate().toInstant()), "r" },
{ "Reason: " + signature.getReason(), "r" } };
float y = height - 13;
for (String[] line : lines) {
PDFont font = line[1].equals("b") ? bold : regular;
float size = line[1].equals("b") ? 8.5f : 7f;
String text = TextMetrics.truncateWithEllipsis(font, size,
InvoiceLabFonts.sanitize(font, line[0]), textWidth);
cs.beginText();
cs.setFont(font, size);
cs.setNonStrokingColor(line[1].equals("b") ? NebulaColors.BLUE : NebulaColors.TEXT_GREY);
cs.newLineAtOffset(x, y);
cs.showText(text);
cs.endText();
y -= size + 4;
}
}
}- The border is drawn inset by half the line width (
0.4) so the/BBoxdoesn't clip it. - The logo is fitted into at most 60 pt of width with
Images.drawFitted(02-06). - The fonts are DejaVu, loaded with
InvoiceLabFontsin the template document (remember from 02-03: aPDType0Fontbelongs to one document). They're embedded as a subset when the template is saved, and PDFBox copies them along with the appearance. - The name comes from the certificate, not from
/Name; the date, from/M(whichprepareSignaturesets just before); text that doesn't fit is truncated with an ellipsis (TextMetrics, 02-04).
Visibly signing the invoice and the registration form
The invoice has no signature field. We could let PDFBox create one at the positionWithoutField position, but we prefer to prepare the box first with PdfFields.signature (05-03), on the last page, in the free space below the total. That step is saved with a full save, because there's no signature to protect yet; then we sign incrementally.
package com.invoicelab.examples;
import com.invoicelab.editing.PdfEditor;
import com.invoicelab.forms.PdfFields;
import com.invoicelab.security.KeyVault;
import com.invoicelab.security.SignatureAppearance;
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;
import org.apache.pdfbox.pdmodel.PDPage;
public class VisibleInvoiceSignature {
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");
KeyVault.Credential hardware = KeyVault.load(Path.of("certificates/hardware-test.p12"),
Secrets.chars("INVOICELAB_P12_HARDWARE"), "hardware");
Path folder = Files.createDirectories(Path.of("output/signed"));
// 1) Prepare the box: a signature field on the last page (FULL save: there are no signatures yet)
Path prepared = folder.resolve("F-2026-0001-with-field.pdf");
PdfEditor.edit(Path.of("output/F-2026-0001.pdf"), prepared, PdfEditor.Mode.FULL, document -> {
PDPage last = document.getPage(document.getNumberOfPages() - 1);
new PdfFields(document).signature("signature.issuer", last, PdfFields.rect(300, 250, 245, 62));
});
// 2) Sign in that field with a visible appearance (logo + details)
Path visible = folder.resolve("F-2026-0001-visible-signature.pdf");
new PdfSigner(nebula).sign(prepared, visible,
SignatureData.approval("Nebula Distribution Ltd.", "Zaragoza", "Issue of invoice F-2026-0001")
.inField("signature.issuer"),
new SignatureAppearance(nebula.certificate(), "/img/logo-nebula.png", null));
System.out.printf("%s: %,d bytes%n", visible, Files.size(visible));
// 3) The customer visibly signs its registration form in signature.customer
Path registration = Path.of("output/registrations/registration-hardware-visible-signature.pdf");
new PdfSigner(hardware).sign(Path.of("output/registrations/registration-hardware.pdf"), registration,
SignatureData.approval("Example Hardware Co.", "Huesca", "Customer registration request")
.inField("signature.customer"),
new SignatureAppearance(hardware.certificate(), null, null));
System.out.printf("%s: %,d bytes%n", registration, Files.size(registration));
}
}output/signed/F-2026-0001-visible-signature.pdf: 126,529 bytes
output/registrations/registration-hardware-visible-signature.pdf: 86,884 bytesWhen you render page 2 of the invoice (06-04), below the orange "INVOICE TOTAL" box there's a light blue rectangle with a blue border: Nebula's logo on the left and, on the right, "Digitally signed by", Nebula Distribution (TEST) in bold, "Date: 27/11/2026 19:40" and "Reason: Issue of invoice F-2026-0001". On the registration form, the "Signature of the legal representative" box we drew in 05-03 now shows "Example Hardware (TEST)", the date and the reason, without a logo.
And verification? Exactly the same as for invisible signatures:
output/signed/F-2026-0001-visible-signature.pdf
[signature.issuer] Nebula Distribution (TEST) · Issue of invoice F-2026-0001 · VALID
output/registrations/registration-hardware-visible-signature.pdf
[signature.customer] Example Hardware (TEST) · Customer registration request · VALIDThe appearance is part of the signed revision, so it's protected too: if someone changes it afterwards, it will be a change after the signature. The PDFs are somewhat larger: the prepared invoice is 52,876 bytes and, after the visible signature, 126,529 (about 35 KB more than the invisible signature), because of the logo and the DejaVu subset the appearance carries.
Common Mistakes and Tips
- Verifying with
/Nameinstead of the certificate./Nameis written by the signer; the reliable name is in the CMS certificate, and only if it's trusted. - Treating a signature as valid because the CMS verifies. Integrity isn't authenticity: always check trust in the certificate and coverage.
- Ignoring later revisions. "Valid" and "the document hasn't changed since it was signed" aren't the same thing. Check
coversAlland, if necessary, extract the signed version. - Doing a full save of a signed PDF (or putting it through a tool that "optimises" or converts it). It breaks every signature. Signed = incremental only, and only allowed changes.
- Stamping stamps or watermarks onto certified invoices. With P=1 or P=2 they aren't allowed. Make those changes before signing, or don't certify.
- Closing
SignatureOptionsbefore saving with a visible signature: the template is left without data.PdfSigneralready gets this right with its try-with-resources. - Signing visibly on rotated pages without adjusting the matrix: the appearance comes out askew.
SignatureAppearancerejects them; to support them, adapt the rotationswitchfromCreateVisibleSignature2. - Using fonts from another document in the template. Each
PDType0Fontbelongs to onePDDocument; load the fonts withInvoiceLabFonts(template). - Relying on
SignatureVerifierfor legal decisions. It's a teaching tool: it doesn't check revocation, trust in the TSA or long chains. For validation with legal effect, use specialised tools and consult a professional.
Exercises
Exercise 1. Using the test CA from exercise 2 in 07-02, sign F-2026-0001.pdf with the keystore credential (certificates/ca/keystore-test.p12). Verify it twice: with a SignatureVerifier whose only anchor is ca-test.cer, and with another whose only anchor is nebula-test.cer. Explain the results.
Exercise 2. Write a program that verifies all the PDFs in output/signed (in alphabetical order) and prints one line per signature with the file, the field, the signer and the status; PDFs without signatures must appear as "no signatures" and those that can't be read as "unreadable", without stopping the process.
Exercise 3. Write List<Integer> visibleChanges(Path pdf, String field), which returns the pages (1-based) whose appearance has changed since the signature in the given field was made. Test it with tests/certified-paid.pdf (Signature1), ALTA-2026-0002.pdf (signature.customer) and F-2026-0001-accepted.pdf (Signature1), and interpret the results.
Solutions
Solution 1.
KeyVault.Credential keystore = KeyVault.load(Path.of("certificates/ca/keystore-test.p12"),
Secrets.chars("INVOICELAB_P12_KEYSTORE"), "keystore");
new PdfSigner(keystore).sign(Path.of("output/F-2026-0001.pdf"), Path.of("output/signed/keystore.pdf"),
SignatureData.approval("Nebula Keystore", "Zaragoza", "Chain of trust test"));
Path signed = Path.of("output/signed/keystore.pdf");
for (var r : new SignatureVerifier(Set.of(Protection.readCertificate(Path.of("certificates/ca/ca-test.cer"))))
.verify(signed)) {
System.out.println("Anchor = CA: " + r.status() + " " + r.warnings());
}
for (var r : new SignatureVerifier(Set.of(Protection.readCertificate(Path.of("certificates/nebula-test.cer"))))
.verify(signed)) {
System.out.println("Anchor = Nebula: " + r.status() + " " + r.warnings());
}With the CA as the anchor, isTrusted sees that the issuer of the keystore's certificate matches the CA's subject and that certificate.verify(ca.getPublicKey()) succeeds: we trust the certificate without ever having seen it, because we trust whoever issued it. That's how trust works in the real world, at scale. With Nebula's certificate as the anchor, the issuer is unknown; the CMS is still intact, but the identity can't be verified. Notice that the credential carries the complete chain (2 certificates) and PdfSigner includes it in the CMS with addCertificates.
Solution 2.
SignatureVerifier verifier = new SignatureVerifier(Set.of(
Protection.readCertificate(Path.of("certificates/nebula-test.cer")),
Protection.readCertificate(Path.of("certificates/hardware-test.cer"))));
List<Path> pdfs = new ArrayList<>();
try (DirectoryStream<Path> ds = Files.newDirectoryStream(Path.of("output/signed"), "*.pdf")) {
ds.forEach(pdfs::add);
}
Collections.sort(pdfs);
for (Path pdf : pdfs) {
try {
List<SignatureVerifier.Result> results = verifier.verify(pdf);
if (results.isEmpty()) {
System.out.printf("%-34s no signatures%n", pdf.getFileName());
}
for (SignatureVerifier.Result r : results) {
System.out.printf("%-34s %-14s %-32s %s%n", pdf.getFileName(), r.field(), r.signer(), r.status());
}
} catch (IOException e) {
System.out.printf("%-34s unreadable (%s)%n", pdf.getFileName(), e.getMessage());
}
}Extract from the output:
F-2026-0001-accepted.pdf Signature1 Nebula Distribution (TEST) VALID_WITH_LATER_CHANGES
F-2026-0001-accepted.pdf Signature2 Example Hardware (TEST) VALID
F-2026-0001-certified.pdf Signature1 Nebula Distribution (TEST) VALID
F-2026-0001-visible-signature.pdf signature.issuer Nebula Distribution (TEST) VALID
F-2026-0001-with-field.pdf no signatures
keystore.pdf Signature1 Nebula Keystore (TEST) IDENTITY_NOT_VERIFIEDF-2026-0001-with-field.pdf has a signature field, but it's empty: verify skips it because getSignature() is null. keystore.pdf (from exercise 1) isn't trusted by this verifier, which doesn't include the CA. The per-file try/catch means a damaged PDF (for example, the 0-byte one from exercise 2 in 07-03, if you saved it here) doesn't stop the report.
Solution 3.
static List<Integer> visibleChanges(Path pdf, String field) throws IOException {
Path folder = Files.createTempDirectory("invoicelab-changes");
Path version = folder.resolve("signed-version.pdf");
SignatureVerifier.extractSignedVersion(pdf, field, version);
List<Integer> pages = new ArrayList<>();
for (VisualComparator.Result r : VisualComparator.compare(version, pdf, 72, 16, folder)) {
if (r.different() > 0) {
pages.add(r.page());
}
}
return pages;
}Results: [1] for the certified invoice with the "PAID" stamp (the stamp is on page 1); [1] for ALTA-2026-0002.pdf (when filling in internal.registrationNumber, RegistrationIntake generated the field's appearance, which is visible on page 1); and [] for accepted.pdf, because the customer's signature is invisible and doesn't change the look of any page. A visual comparison doesn't replace an object-level analysis (a change in the metadata or in a hidden field can't be seen), but it answers very well the question that matters most to a person: "is what I'm seeing what was signed?". The temporary folder holds VisualComparator's difference maps; delete it when you no longer need it.
Conclusion
With this lesson you complete module 7. In it you've learned to verify signatures properly: locate each signature and its signed bytes with getByteRange, getContents and getSignedContent; verify the CMS with Bouncy Castle, checking the fingerprint explicitly; find out whether a signature covers the whole file, count the later revisions and relate them to DocMDP; and decide whether a certificate is trusted, with its validity period, its issuer and the concepts of revocation. You've seen with your own files why a full save breaks any signature, and how to recover the signed version to compare it with the current one. And you've given signatures a face with SignatureAppearance, following the approach of CreateVisibleSignature2.
Throughout the module you've built the com.invoicelab.security package: Secrets and Protection to keep passwords out of the code and encrypt documents with a password or a certificate; KeyVault to load PKCS#12 credentials; PdfSigner, Certification and TsaClient to sign, certify and timestamp; and SignatureVerifier and SignatureAppearance to check signatures and make them visible. InvoiceLab no longer just generates, modifies and reads PDFs: it also protects them and vouches for their authenticity.
All that's left is to take all this into production. In module 8 we'll start with PDF/A, the format designed for archiving documents for decades, essential for keeping signed invoices over the long term; then we'll make invoices accessible with tagged PDF, take care of performance and memory, publish generation as a REST service and wrap up with automated tests that check every InvoiceLab PDF is exactly what it should be.
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
