A PDF can be wrong in many ways, and hardly any of them jump out at you: a total that has moved two millimetres and no longer fits in its box, a font that has stopped being embedded after a dependency upgrade, a page number that reads "Page 2 of 1", a signature that breaks because someone swapped an incremental save for a full one, or a PDF/A that stops being one because of a new logo with transparency. Throughout the course we've been checking all this by hand, opening files and looking at them. In this lesson we'll turn it into automated tests with JUnit 5: tests of structure, content, positions, forms, signatures and PDF/A; visual regression tests with reference PDFs; parameterised and property tests with extreme invoices; and the integration of all of it into the Maven build and continuous integration. We'll also learn how to make the output reproducible, byte for byte.
Contents
- Strategy: what to test and at which level
- Preparation: dependencies and test data
- Structure tests
- Content tests
- Position tests
- Form tests
- Signature tests
- PDF/A tests
- Reproducible output
- Visual regression with reference PDFs
- Parameterised and property tests
- The QR code gets tested too
- Continuous integration
Strategy: what to test and at which level
As in any application, not all tests are worth the same or cost the same. For InvoiceLab we propose a three-level pyramid:
flowchart TB
V["Level 3 · The resulting PDF<br/>appearance (visual regression), PDF/A, signatures<br/>few, slow, very revealing"]
M["Level 2 · Layout<br/>pages, text, positions, fonts, metadata<br/>quite a few, fast"]
D["Level 1 · Model<br/>Invoice calculations, validations, formats<br/>many, instant, no PDF"]
V --- M --- D
| Level | What it checks | Example | Tools | Cost |
|---|---|---|---|---|
| 1. Model | Calculations and rules without generating a PDF | total() of an invoice with two VAT rates; Formats.euros |
JUnit, AssertJ | Microseconds |
| 2. Layout | What's in the PDF and where | Number of pages, the total appears, it's aligned, fonts embedded | Loader, PdfText, TextLocator, ResourceInventory |
Tens of ms |
| 3. Resulting PDF | The document as a whole | It looks the same as the reference; it's valid PDF/A; the signature is valid | VisualComparator, veraPDF, SignatureVerifier |
Hundreds of ms |
The rule of thumb: every error, at the lowest possible level. If the total is miscalculated, a model test should fail, not the visual regression test. Visual tests catch what nobody thought of checking, but they say little about the cause.
Notice how much we reuse what we've already built: to test PDFs we use the same classes InvoiceLab uses to read supplier PDFs (module 6) and to verify signatures (module 7).
Preparation: dependencies and test data
spring-boot-starter-test (08-04) already brings JUnit 5, AssertJ and Mockito; if your project doesn't use Spring, junit-jupiter (01-02) and assertj-core are enough. The tests go in src/test/java, in the com.invoicelab.tests package, except those that need package access (such as the QR test, later on).
A small class gathers the common data:
final class Fixtures {
/** Fixed clock: the same invoice always produces the same metadata. */
static final Clock CLOCK = Clock.fixed(Instant.parse("2026-01-15T09:00:00Z"), ZoneId.of("Europe/Madrid"));
static final InvoiceGenerator GENERATOR = new InvoiceGenerator(Theme.nebula());
static byte[] invoice(int lines) throws IOException {
return GENERATOR.generate(SampleData.invoice(lines));
}
static byte[] pdfAInvoice(Invoice invoice, PdfALevel level) throws IOException {
return new PdfAInvoiceGenerator(GENERATOR, level, CLOCK).generate(invoice);
}
/** Copy of an invoice with different lines (same number, issuer and customer). */
static Invoice withLines(Invoice base, List<InvoiceLine> lines) {
return new Invoice(base.number(), base.date(), base.issuer(), base.customer(), lines, base.paymentTerms());
}
}- The generators return
byte[](03-04): the tests don't need to touch the disk except when a tool requires it (veraPDF,VisualComparator,PdfSigner). For those cases we'll use@TempDir, a temporary folder that JUnit creates and deletes. - The fixed
Clockis the reasonPdfAInvoiceGeneratortook a clock back in 08-01.
Structure tests
These check the "shape" of the document: pages, sizes, fonts and metadata.
class InvoiceStructureTest {
@ParameterizedTest(name = "{0} lines → {1} page(s)")
@CsvSource({ "1, 1", "12, 1", "30, 2", "80, 4" })
void pagesDependOnLines(int lines, int pages) throws IOException {
try (PDDocument doc = Loader.loadPDF(Fixtures.invoice(lines))) {
assertThat(doc.getNumberOfPages()).isEqualTo(pages);
for (PDPage page : doc.getPages()) {
assertThat(page.getMediaBox().getWidth()).isEqualTo(PDRectangle.A4.getWidth());
assertThat(page.getMediaBox().getHeight()).isEqualTo(PDRectangle.A4.getHeight());
}
}
}
@Test
void allFontsEmbeddedAsSubsets() throws IOException {
try (PDDocument doc = Loader.loadPDF(Fixtures.invoice(30))) {
assertThat(ResourceInventory.fonts(doc))
.isNotEmpty()
.allSatisfy(f -> {
assertThat(f.embedded()).as("%s embedded", f.name()).isTrue();
assertThat(f.subset()).as("%s subset", f.name()).isTrue();
});
}
}
@Test
void archiveVersionMetadata() throws Exception {
byte[] pdf = Fixtures.pdfAInvoice(SampleData.invoice(30), PdfALevel.PDF_A_2B);
try (PDDocument doc = Loader.loadPDF(pdf)) {
assertThat(doc.getDocumentInformation().getTitle()).isEqualTo("Invoice F-2026-0001");
assertThat(doc.getDocumentInformation().getCustomMetadataValue("InvoiceNumber")).isEqualTo("F-2026-0001");
assertThat(doc.getDocumentCatalog().getLanguage()).isEqualTo("en-GB");
XMPMetadata xmp = Metadata.readXmp(doc);
assertThat(xmp.getPDFAIdentificationSchema().getPart()).isEqualTo(2);
assertThat(xmp.getPDFAIdentificationSchema().getConformance()).isEqualTo("B");
assertThat(xmp.getDublinCoreSchema().getTitle()).isEqualTo("Invoice F-2026-0001");
}
}
}@ParameterizedTestwith@CsvSourceextends the test from 03-05;namemakes the report show "30 lines → 2 page(s)" instead of an index.- AssertJ's
allSatisfychecks a condition on every element and reports all those that fail. With.as(...), the message says which font failed. ResourceInventory.fonts(06-03) is the tool that would detect a font no longer being embedded, for example if someone swappedInvoiceLabFontsfor Helvetica "just to try it".
Content tests
Does the PDF say what it should? PdfText (06-01) extracts and normalises the text:
class InvoiceContentTest {
private final Invoice invoice = SampleData.invoice(30);
@Test
void containsTheKeyData() throws IOException {
try (PDDocument doc = Loader.loadPDF(Fixtures.GENERATOR.generate(invoice))) {
String text = PdfText.normalize(PdfText.text(doc));
assertThat(text)
.contains("F-2026-0001")
.contains("J00000000") // customer's VAT ID
.contains("Example Hardware Co.")
.contains("INVOICE TOTAL")
.contains(PdfText.normalize(Formats.euros(invoice.total())));
assertThat(PdfText.byPage(doc).get(0)).contains("Carried forward");
}
}- The expected total is calculated with the model (
invoice.total()) and formatted with the sameFormats.eurosthe generator uses. Never type "4.193,94 €" by hand in the test: if the sample data changed, the test would fail for a reason that isn't a bug. - We normalise both sides with
PdfText.normalize, becauseFormats.eurosuses a non-breaking space before the "€" and extraction may return it differently (06-01). byPagelets us check that page 1 ends with the "Carried forward" from 03-02.
Position tests
It isn't enough for the text to be there: it has to be where it should be. TextLocator (06-02) gives us each word with its coordinates. We check that the total is right-aligned inside TotalsBlock's orange box: the block sits against the right edge of the content box and the amount ends 3 mm before it, so as not to touch the rounded border:
@Test
void totalIsRightAlignedInTheBlock() throws IOException {
try (PDDocument doc = Loader.loadPDF(Fixtures.GENERATOR.generate(invoice))) {
int last = doc.getNumberOfPages();
List<Line> lines = TextLocator.lines(TextLocator.words(doc, last), 2f);
Line totalLine = lines.stream().filter(l -> l.text().startsWith("INVOICE TOTAL")).findFirst()
.orElseThrow(() -> new AssertionError("INVOICE TOTAL not found on page " + last));
assertThat(PdfText.normalize(totalLine.text()))
.endsWith(PdfText.normalize(Formats.euros(invoice.total())));
Word lastWord = totalLine.words().get(totalLine.words().size() - 1);
float expectedEdge = ContentBox.invoice(PDRectangle.A4).right() - Measures.mm(3);
assertThat(lastWord.right()).isCloseTo(expectedEdge, Offset.offset(1f));
}
}
}- We look for the line by its label and take the last word: the right edge of the amount.
isCloseTowith a tolerance of 1 point (0.35 mm): positions are real numbers, and small rounding differences mustn't break the test. If someone changes the block's margin or the alignment becomes left, the difference will be several millimetres and the test will fail.expectedEdgeis calculated with the same pieces the generator uses (ContentBox,Measures), not with a magic number.
Form tests
For the customer registration form from module 5, the essential property is the round trip: what's filled in, saved and read back is the same.
class RegistrationFormTest {
static final RegistrationRequest HARDWARE = new RegistrationRequest(
new Customer("Example Hardware Co.", "J00000000", "45 Test Avenue, Unit 2", "22001",
"Huesca", "[email protected]"),
"22", "Lucía Martín Ejemplo", "974 000 000", PaymentMethod.TRANSFER, null,
true, true, false, "Morning deliveries only.");
@Test
void whatIsFilledInReadsBackTheSameAfterSaving() throws IOException {
byte[] filled;
try (PDDocument doc = Loader.loadPDF(GenerateRegistrationForm.generate())) {
PDAcroForm form = doc.getDocumentCatalog().getAcroForm(null);
RegistrationFormFiller.fill(form, HARDWARE);
ByteArrayOutputStream output = new ByteArrayOutputStream();
doc.save(output);
filled = output.toByteArray();
}
try (PDDocument doc = Loader.loadPDF(filled)) { // round trip through bytes
PDAcroForm form = doc.getDocumentCatalog().getAcroForm(null);
assertThat(RegistrationFormFiller.validate(form)).isEmpty();
assertThat(form.getField(RegistrationFormFiller.TAX_ID).getValueAsString()).isEqualTo("J00000000");
assertThat(form.getField(RegistrationFormFiller.PAYMENT_METHOD).getValueAsString()).isEqualTo("Transfer");
assertThat(form.getField(RegistrationFormFiller.TERMS).getValueAsString()).isEqualTo("Yes");
assertThat(RegistrationFormFiller.read(form)).isEqualTo(HARDWARE);
}
}
}- Saving and reloading is essential: checking the values in the same
PDDocumentthey were written to doesn't prove they were saved. - The concrete values in the PDF (
"Transfer","Yes") are the contract with whoever reads the form outside InvoiceLab; that's why we check them as well as the complete round trip withread. getAcroForm(null)avoids the fix-ups (05-01), so that we test the form exactly as we created it.
Signature tests
Signatures need the test certificate and its password, which are not in the repository (07-01). The test disables itself wherever they don't exist:
@EnabledIfEnvironmentVariable(named = "INVOICELAB_P12_NEBULA", matches = ".+")
class InvoiceSignatureTest {
static KeyVault.Credential nebula;
@BeforeAll
static void loadCredential() throws Exception {
nebula = KeyVault.load(Path.of("certificates/nebula-test.p12"),
Secrets.chars("INVOICELAB_P12_NEBULA"), "nebula");
}
@Test
void signedInvoiceIsValid(@TempDir Path folder) throws Exception {
Path invoice = folder.resolve("invoice.pdf");
Path signed = folder.resolve("signed.pdf");
Files.write(invoice, Fixtures.invoice(30));
new PdfSigner(nebula).sign(invoice, signed,
SignatureData.approval("Nebula Distribution Ltd.", "Zaragoza", "Automated test"));
List<SignatureVerifier.Result> results = new SignatureVerifier(Set.of(nebula.certificate()))
.verify(signed);
assertThat(results).singleElement()
.satisfies(r -> assertThat(r.status()).isEqualTo(SignatureVerifier.Status.VALID));
}
@Test
void fullSaveBreaksTheSignature(@TempDir Path folder) throws Exception {
Path invoice = folder.resolve("invoice.pdf");
Path signed = folder.resolve("signed.pdf");
Path rewritten = folder.resolve("rewritten.pdf");
Files.write(invoice, Fixtures.invoice(12));
new PdfSigner(nebula).sign(invoice, signed,
SignatureData.approval("Nebula Distribution Ltd.", "Zaragoza", "Automated test"));
try (PDDocument doc = Loader.loadPDF(signed.toFile())) {
doc.getDocumentInformation().setSubject("change");
doc.save(rewritten.toFile()); // a full save!
}
assertThat(new SignatureVerifier(Set.of(nebula.certificate())).verify(rewritten))
.singleElement()
.satisfies(r -> assertThat(r.status()).isEqualTo(SignatureVerifier.Status.BROKEN));
}
}- The second test is a negative test: it checks that the verifier detects what it should detect. Without it, a
SignatureVerifierthat always answeredVALIDwould pass the first one. singleElement()requires exactly one signature: if the document were signed twice by mistake, we'd find out.- In continuous integration, the password is injected as a CI system secret. Where it isn't present (the laptop of someone who has just cloned the project), JUnit marks the class as disabled instead of failing.
PDF/A tests
With PdfAValidator (08-01) and @EnumSource, a single test validates every level:
class PdfATest {
@ParameterizedTest
@EnumSource(PdfALevel.class)
void everyLevelPassesVeraPdf(PdfALevel level, @TempDir Path folder) throws Exception {
Path pdf = folder.resolve("invoice.pdf");
Files.write(pdf, Fixtures.pdfAInvoice(SampleData.invoice(30), level));
PdfAValidator.Report report = PdfAValidator.veraPdf(pdf);
assertThat(report.errors()).as(report.validator()).isEmpty();
assertThat(report.valid()).isTrue();
}
@Test
void preflightAcceptsPdfA1b(@TempDir Path folder) throws Exception {
Path pdf = folder.resolve("invoice-1b.pdf");
Files.write(pdf, Fixtures.pdfAInvoice(SampleData.invoice(30), PdfALevel.PDF_A_1B));
assertThat(PdfAValidator.preflight(pdf).errors()).isEmpty();
}
}Checking first that the list of errors is empty, and only then valid(), has an advantage: if it fails, the JUnit report shows which rules were broken, not a terse "expected true but was false". If you add a level to the enum (like PDF_A_2A in the 08-02 exercise), the test covers it automatically.
Reproducible output
To compare PDFs, the same input has to produce the same output. Does InvoiceLab do that? We generated the same PDF/A invoice twice, with the fixed clock, and compared the bytes:
The two versions differ only in the trailer's /ID: two strings that PDFBox calculates on every save() based on, among other things, the current time. The other sources of variation were already under control:
| Source of variation | Where it appears | How InvoiceLab controls it |
|---|---|---|
| Creation and modification date | Info (CreationDate, ModDate) and XMP (CreateDate, ModifyDate, MetadataDate) |
Clock injected into PdfAInvoiceGenerator |
| File identifier | /ID in the trailer |
Reproducible.fixId (below) |
Font subset prefix (ABCDEF+DejaVuSans) |
Font name | PDFBox derives it from the glyphs used: it's stable |
| Collection iteration order | Object order | Lists and LinkedHashMap/TreeMap, never HashSet for anything that gets written |
| Real time in the content | Texts such as "Generated on..." | Don't write the real time; use the clock |
The Reproducible class (in the com.invoicelab.pdf package) fixes the /ID from a seed:
public final class Reproducible {
public static void fixId(PDDocument document, String seed) {
byte[] digest;
try {
digest = MessageDigest.getInstance("MD5").digest(seed.getBytes(StandardCharsets.UTF_8));
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException("MD5 is always available in Java", e);
}
COSArray id = new COSArray();
id.add(new COSString(digest)); // permanent identifier
id.add(new COSString(digest)); // identifier of this version
document.getDocument().setDocumentID(id);
}
}And in PdfAInvoiceGenerator.generate, just before saving, we add one line:
PdfAConverter.apply(document, level);
Reproducible.fixId(document, invoice.number() + "|" + invoice.total() + "|" + level);
return PdfAConverter.save(document, level);- The standard asks for the
/IDto identify the file; deriving it from the content (number, total, level) serves that purpose: two different invoices will have different/IDs. - MD5 has no security role here, it's just a 16-byte "digest", which is the usual size of the
/ID. - Don't do this with documents you'll modify with incremental saves without changing the second string: the second part of the
/IDshould change with each version.PdfSignersaves incrementally and PDFBox keeps the existing/ID; for InvoiceLab that's acceptable, but bear it in mind.
The test:
class ReproducibleTest {
@Test
void sameInvoiceSameClock_sameBytes() throws Exception {
byte[] a = Fixtures.pdfAInvoice(SampleData.invoice(30), PdfALevel.PDF_A_3B);
Thread.sleep(1100); // in case anything depended on the real time
byte[] b = Fixtures.pdfAInvoice(SampleData.invoice(30), PdfALevel.PDF_A_3B);
assertThat(sha256(b)).isEqualTo(sha256(a));
}
static String sha256(byte[] data) throws Exception {
return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256").digest(data));
}
}With reproducible output you could even store the expected SHA-256 of each template and compare against it. But any harmless change (a new PDFBox version that compresses differently) would break those tests without anything looking different. To detect changes that matter, the right tool is visual comparison.
Visual regression with reference PDFs
A visual regression test compares the appearance of the current PDF with that of an approved reference version (golden). We use VisualComparator (06-04), which renders both documents and counts the different pixels.
What do we store as the reference, PNG images or PDFs? We store PDFs: that way both documents are rendered with the same PDFBox version at test time, and an improvement to the renderer doesn't break every test. What we detect are changes in generation, which is what we care about.
/**
* Compares each template with its reference ("golden") PDF in src/test/resources/references.
* To accept an intentional visual change: mvn test -Dinvoicelab.updateReferences=true
*/
class VisualRegressionTest {
static final Path REFERENCES = Path.of("src/test/resources/references");
static final Path DIFFERENCES = Path.of("target/visual-differences");
static final float DPI = 72;
static final int TOLERANCE = 16; // absorbs small anti-aliasing differences
static final double MAX_PERCENTAGE = 0.0;
static Stream<Arguments> templates() {
return Stream.of(
Arguments.of("invoice-12-lines", SampleData.invoice(12)),
Arguments.of("invoice-30-lines", SampleData.invoice(30)));
}
@ParameterizedTest(name = "{0}")
@MethodSource("templates")
void matchesTheReference(String name, Invoice invoice) throws IOException {
byte[] pdf = Fixtures.pdfAInvoice(invoice, PdfALevel.PDF_A_2B);
Path reference = REFERENCES.resolve(name + ".pdf");
Path actual = Files.createDirectories(DIFFERENCES.resolve(name)).resolve("actual.pdf");
Files.write(actual, pdf);
if (Boolean.getBoolean("invoicelab.updateReferences") || Files.notExists(reference)) {
Files.createDirectories(REFERENCES);
Files.write(reference, pdf);
fail("Reference " + reference + " created or updated: review it by hand, commit it to "
+ "version control and run the tests again");
}
List<VisualComparator.Result> results = VisualComparator.compare(reference, actual, DPI, TOLERANCE,
DIFFERENCES.resolve(name));
for (VisualComparator.Result r : results) {
assertThat(r.percentage())
.as("Page %d of %s: %d different pixels (map in %s)", r.page(), name, r.different(), r.map())
.isLessThanOrEqualTo(MAX_PERCENTAGE);
}
}
}The design decisions:
- Controlled updates. References are never updated on their own. If a reference is missing, or an update is requested with
-Dinvoicelab.updateReferences=true, the test writes it and fails on purpose, to force a person to review it (open the PDF, look at it) and commit it to version control. In code review, the change to the reference PDF is visible and open to discussion. - Tolerance.
TOLERANCE = 16(per channel, from 0 to 255) ignores minimal anti-aliasing variations; the maximum percentage of different pixels is 0. If your tests run on machines with different JVMs and anti-aliasing differences appear, raise the percentage slightly (for example, to 0.01%) rather than the tolerance: a high tolerance lets real colour changes through. - Resolution. At 72 dpi the test is fast and detects one-point shifts. Go up to 150 dpi if you need to detect finer changes, at the cost of time.
- Artifacts for diagnosis. The current PDF and the difference maps (different pixels in red, 06-04) are left in
target/visual-differences/, which the CI system will publish when the test fails.
Does it work? To check, we introduced a small change: in TotalsBlock we subtracted Measures.mm(1) from xBlock, that is, we moved the totals block 1 mm to the left. Both tests fail and leave their difference maps behind:
[Page 1 of invoice-12-lines: 5002 different pixels (map in target/visual-differences/invoice-12-lines/differences-01.png)]
[Page 2 of invoice-30-lines: 5170 different pixels (map in target/visual-differences/invoice-30-lines/differences-02.png)]
Expecting actual:
1.03318378481
to be less than or equal to:
0.0A one-millimetre shift changes just over 1% of the page's pixels: the orange box, the breakdown and the amounts. The map shows in red exactly what has moved.
If the change is intentional, the reference is updated with the property, reviewed and committed.
Parameterised and property tests
The tests with SampleData.invoice(30) check one case. But bugs appear at the extremes: extremely long descriptions, characters the font doesn't have, invoices with one line or five hundred. A property test checks something that must hold for any valid input, and we feed it extreme cases:
class InvoicePropertiesTest {
static InvoiceLine line(String description) {
return new InvoiceLine("REF-1", description, BigDecimal.ONE, new BigDecimal("10.00"), new BigDecimal("21"));
}
static Stream<Invoice> extremeInvoices() {
Invoice base = SampleData.invoice(1);
return Stream.of(
Fixtures.withLines(base, List.of(line("Very long description, ".repeat(40)))),
Fixtures.withLines(base, List.of(line("Service for Tomáš Dvořák · Łódź · Ærøskøbing"))),
Fixtures.withLines(base, List.of(line("Text with emoji 🙂 and ideograms 日本語"))),
Fixtures.withLines(base, List.of(line("Tab\tand line\nbreak"))),
SampleData.invoice(500));
}
@ParameterizedTest
@MethodSource("extremeInvoices")
void anyValidInvoiceProducesAReadablePdfWithItsTotal(Invoice invoice) throws Exception {
byte[] pdf = Fixtures.GENERATOR.generate(invoice);
assertThat(new String(pdf, 0, 5, StandardCharsets.ISO_8859_1)).isEqualTo("%PDF-");
try (PDDocument doc = Loader.loadPDF(pdf)) {
assertThat(doc.getNumberOfPages()).isPositive();
String text = PdfText.normalize(PdfText.text(doc));
assertThat(text).contains(PdfText.normalize(Formats.euros(invoice.total())));
}
}
@ParameterizedTest
@ValueSource(ints = { 1, 7, 33, 120, 500 })
void everyPageShowsPageXofN(int lines) throws Exception {
try (PDDocument doc = Loader.loadPDF(Fixtures.invoice(lines))) {
int n = doc.getNumberOfPages();
List<String> pages = PdfText.byPage(doc);
for (int p = 1; p <= n; p++) {
assertThat(pages.get(p - 1)).contains("Page " + p + " of " + n);
}
}
}
@Test
void noLinesNoInvoice() {
Invoice base = SampleData.invoice(1);
assertThatThrownBy(() -> Fixtures.withLines(base, List.of()))
.isInstanceOf(IllegalArgumentException.class)
.hasMessageContaining("at least one line");
}
}| Case | What could fail | What protects against it |
|---|---|---|
| 920-character description | Overflowing the cell, infinite loop when splitting lines | TextMetrics.splitIntoLines / truncateWithEllipsis (02-04) |
| Czech, Polish, Danish | Glyphs missing from the font | Embedded DejaVu (02-03) |
| Emoji and ideograms | IllegalArgumentException in showText |
InvoiceLabFonts.sanitize replaces them with "?" |
| Tab and line break | showText doesn't accept control characters |
sanitize turns them into spaces |
| 500 lines | Pagination, "Carried forward", "X of N" numbering | Paginator, PageFooter.numberPages (03-02) |
| 0 lines | Impossible invoice | The Invoice constructor rejects it: the test documents this |
Note the 0-line test: it doesn't even generate a PDF, because the model prevents the invoice from being created. It's a level 1 test, in the right place. The properties we check are general (starts with %PDF-, can be read, contains its total, every page says "Page p of n"), so adding a new extreme case means adding one line to the Stream.
To go further, there are property-based testing libraries for Java such as jqwik, which generate hundreds of random inputs within given bounds and, when one fails, shrink it to the minimal case that reproduces the error.
The QR code gets tested too
In 03-03 we promised that the QR code wouldn't be considered good just because "it shows up": it has to be read. We render the last page with PDFRenderer (06-04) and decode it with ZXing:
package com.invoicelab.generator; // same package: access to verificationUrl
class QrCodeTest {
@Test
void lastPageQrIsReadableAndPointsToVerification() throws Exception {
Invoice invoice = SampleData.invoice(30);
byte[] pdf = new InvoiceGenerator(Theme.nebula()).generate(invoice);
try (PDDocument doc = Loader.loadPDF(pdf)) {
BufferedImage page = new PDFRenderer(doc)
.renderImageWithDPI(doc.getNumberOfPages() - 1, 200, ImageType.GRAY);
String decoded = new MultiFormatReader().decode(new BinaryBitmap(new HybridBinarizer(
new BufferedImageLuminanceSource(page)))).getText();
assertThat(decoded).isEqualTo(InvoiceGenerator.verificationUrl(invoice)); // package-private
}
}
}- The test lives in
src/test/java/com/invoicelab/generator: by sharing a package withInvoiceGenerator, it can callverificationUrl, which is package-private. That way we compare against the URL the generator meant to encode, without duplicating its logic. - 200 dpi in greyscale is enough for ZXing to read the QR code from 03-03 reliably. If
decodefinds no code, it throwsNotFoundExceptionand the test fails.
Continuous integration
All these tests run with mvn test thanks to Maven Surefire. Some useful settings in pom.xml:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<argLine>-Djava.awt.headless=true -Dfile.encoding=UTF-8</argLine>
<systemPropertyVariables>
<user.language>en</user.language>
<user.country>GB</user.country>
</systemPropertyVariables>
</configuration>
</plugin>java.awt.headless=true: CI servers have no display, andPDFRendererandVisualComparatoruse AWT.- Fixed language and encoding: validation messages (08-04) and some formats depend on the JVM's
Locale; fixing it avoids tests that pass on a laptop and fail on the server.
A typical CI pipeline (for example, in GitHub Actions or GitLab CI) has these steps:
flowchart LR
A["Clone"] --> B["Install JDK 17<br/>and ~/.m2 cache"]
B --> C["Inject secrets<br/>INVOICELAB_P12_NEBULA<br/>+ test certificate"]
C --> D["mvn -B verify"]
D -->|"fails"| E["Publish artifacts<br/>target/surefire-reports<br/>target/visual-differences"]
D -->|"passes"| F["Package and deploy<br/>(08-04)"]
- Difference artifacts: when a visual test fails in CI, nobody can open the PDF on the CI machine. Configure the system to publish
target/visual-differences/(the current PDFs and the red maps) and the Surefire reports as downloadable artifacts. - Secrets: the test certificate's password is stored as a CI system secret and exposed as an environment variable only in this step. The test certificate can live in the CI repository or in a separate store; the real one, never.
- Time: on our machine, the 31 tests in this lesson (including veraPDF validation of the four levels, the signatures and the visual regression) run in about 6 seconds, plus Maven's start-up. If it grows a lot, separate the level 3 tests with
@Tag("slow")and run them in a later stage.
Common Mistakes and Tips
- Comparing PDFs byte for byte without controlling dates and the
/ID. It will always fail. Either make the output reproducible or compare text and appearance. - Typing the expected values by hand ("4.193,94 €") instead of calculating them with the model and the same formatters. The test breaks when the data changes, not when there's a bug.
- Updating visual references automatically when they fail. A reference that updates itself protects you from nothing. Explicit, reviewed updates.
- Overly generous tolerances in visual comparison or in positions. Start strict and relax only with a measured reason.
- Tests that depend on execution order or on files in
output/generated by another program. Each test generates what it needs, preferably in memory or in@TempDir. - Not closing
PDDocuments in tests. It will work, but it will eat memory and file descriptors in large test suites. Try-with-resources here too. - Disabling the signature tests "because they fail in CI". If they fail because the secret is missing,
@EnabledIfEnvironmentVariable; if they fail for any other reason, it's a bug you need to understand. - Tip: when a bug turns up in production with a specific PDF, first turn it into a failing test (adding that case to
extremeInvoicesor as a visual reference) and only then fix it.
Exercises
Exercise 1. Write a test that checks that the invoice number appears in the header of every page of an 80-line invoice, and that the text "INVOICE TOTAL" appears only on the last one.
Exercise 2. Write a test for the accessible invoice from 08-02 (AccessibleInvoice) that validates it with veraPDF as PDF/UA-1. To be able to reuse the code, first turn the example's generation into a static byte[] generate(Invoice f) method.
Exercise 3. Write a test that checks that the PDF/A-3b carries the attached XML, that the total in the XML matches invoice.total() and that the attachment has /AFRelationship /Alternative.
Solutions
Solution 1.
@Test
void numberOnEveryPageAndTotalOnlyOnTheLast() throws IOException {
try (PDDocument doc = Loader.loadPDF(Fixtures.invoice(80))) {
List<String> pages = PdfText.byPage(doc);
assertThat(pages).hasSize(4).allSatisfy(p -> assertThat(p).contains("F-2026-0001"));
for (int i = 0; i < pages.size() - 1; i++) {
assertThat(pages.get(i)).as("page %d", i + 1).doesNotContain("INVOICE TOTAL");
}
assertThat(pages.get(pages.size() - 1)).contains("INVOICE TOTAL");
}
}allSatisfy checks every page and reports which ones fail. Careful: the invoice number also appears in the footer ("Invoice F-2026-0001", footerText), so this test can't tell the header from the footer. To check the header specifically, use TextLocator and require the word to be at the top of the page (for example, y < Measures.mm(50) in reading coordinates).
Solution 2.
// In AccessibleInvoice: main calls generate(SampleData.invoice(8)) and writes the result.
@Test
void accessibleInvoiceMeetsPdfUa(@TempDir Path folder) throws Exception {
Path pdf = folder.resolve("accessible.pdf");
Files.write(pdf, AccessibleInvoice.generate(SampleData.invoice(8)));
PdfAValidator.Report report = PdfAValidator.veraPdf(pdf, PDFAFlavour.PDFUA_1);
assertThat(report.errors()).isEmpty();
}After refactoring, generation returns a byte[] (saving to a ByteArrayOutputStream) and main just writes the file: the same pattern as DocumentGenerator (03-04). Now any change to Tagger that breaks accessibility (a rule not marked as an artifact, for example) will make the build fail.
Solution 3.
@Test
void pdfA3CarriesTheXmlWithTheSameTotal() throws IOException {
Invoice invoice = SampleData.invoice(30);
try (PDDocument doc = Loader.loadPDF(Fixtures.pdfAInvoice(invoice, PdfALevel.PDF_A_3B))) {
PDComplexFileSpecification fs = doc.getDocumentCatalog().getNames().getEmbeddedFiles().getNames()
.get("invoice-" + invoice.number() + ".xml");
assertThat(fs).isNotNull();
assertThat(fs.getCOSObject().getNameAsString(COSName.AF_RELATIONSHIP)).isEqualTo("Alternative");
String xml = new String(fs.getEmbeddedFile().toByteArray(), StandardCharsets.UTF_8);
assertThat(xml).contains("total=\"" + invoice.total().toPlainString() + "\"");
}
}We compare with toPlainString(), the same format InvoiceXml uses, instead of typing the amount by hand. For a real XML format (Facturae, Factur-X), also validate the XML against its XSD schema with javax.xml.validation.
Conclusion
Every InvoiceLab PDF now goes through a safety net of tests organised in levels: the model, without a PDF; the layout, with PdfText, TextLocator and ResourceInventory; and the complete document, with veraPDF, SignatureVerifier and VisualComparator's visual regression against reference PDFs that are only updated explicitly and after review. You've learnt how to make the output reproducible (injected clock and fixed /ID), how to hunt for bugs at the extremes with property tests, how to actually read the QR code and how to take all of it into continuous integration with its secrets and diagnostic artifacts.
This safety net has an immediate use: it's exactly what you need before upgrading an important dependency. In the last lesson of the course we'll use it for the most common case, migrating code from PDFBox 2.x to 3.x, and we'll close with a list of best practices and a review of the whole journey.
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
