InvoiceLab was born on PDFBox 3, but the real world wasn't: there's a good chance your company has a project on PDFBox 2.0 somewhere, and half the examples you'll find on the Internet use PDDocument.load or PDType1Font.HELVETICA, which no longer exist. This final lesson has two parts. In the first, you'll learn to migrate code from PDFBox 2.x to 3.x: what has changed, what the same program looks like before and after, which pitfalls compile without errors but fail at runtime, and in what order the migration is best done. In the second, we'll gather everything we've learnt into an InvoiceLab best-practice checklist, review the whole course journey with the project's final architecture and look at where to go next.

Contents

  1. Why migrate and what to expect
  2. Table of changes from 2.x to 3.x
  3. The same program, before and after
  4. Pitfalls that compile
  5. A step-by-step migration strategy
  6. InvoiceLab best-practice checklist
  7. The course journey and the final architecture
  8. Next steps

Why migrate and what to expect

PDFBox 3.0 (released in 2023) is a major version: it breaks API compatibility to clean out ten years of deprecated methods and rework input/output. The reasons to migrate:

  • New features and most improvements go into the 3.x branch; 2.0 mainly receives fixes.
  • Less memory when loading: 3.x parses the document on demand and no longer uses scratch files for reading.
  • Smaller files: it saves with object streams and a compressed xref by default (we saw this in 01-05).
  • More robust forms: getAcroForm() applies fixes that mimic Adobe Reader (05-01).
  • Third-party dependencies (Apache Tika, signing libraries...) are gradually moving to 3.x, and mixing both versions on the same classpath doesn't work (01-02).

What to expect: most of the changes are mechanical (the compiler points them out to you one by one), but a few compile without errors and change behaviour. Those are the dangerous ones, and we'll look at them separately.

Table of changes from 2.x to 3.x

We checked every change in this table by comparing the classes in pdfbox-2.0.27.jar and pdfbox-3.0.8.jar, and they match the official migration guide (Migration to PDFBox 3.0, on the project's website):

Topic PDFBox 2.0.x PDFBox 3.0.x
Minimum Java Java 6 Java 8
Modules pdfbox, fontbox... New pdfbox-io module with the I/O classes
Loading a PDF PDDocument.load(File / byte[] / InputStream) (16 overloads) Loader.loadPDF(...); PDDocument no longer has load methods
Loading FDF/XFDF FDFDocument.load Loader.loadFDF, Loader.loadXFDF
Random access reading RandomAccessBuffer, RandomAccessBufferedFileInputStream RandomAccessReadBuffer, RandomAccessReadBufferedFile, RandomAccessReadMemoryMappedFile
From an InputStream PDDocument.load(InputStream) Loader.loadPDF(new RandomAccessReadBuffer(input)) (reads it all into memory)
Memory and temporary files MemoryUsageSetting in load, mergeDocuments, Splitter StreamCacheCreateFunction: IOUtils.createMemoryOnlyStreamCache() / createTempFileOnlyStreamCache() (or MemoryUsageSetting...streamCache)
Splitter setMemoryUsageSetting setStreamCacheCreateFunction
Standard 14 fonts Constants PDType1Font.HELVETICA... new PDType1Font(Standard14Fonts.FontName.HELVETICA) (no longer singletons)
Writing text drawString (deprecated) Removed: showText
Opening an existing content stream new PDPageContentStream(doc, page, boolean append, boolean compress) new PDPageContentStream(doc, page, AppendMode.APPEND, boolean compress[, boolean resetContext])
Colours as integers setNonStrokingColor(int r, int g, int b) (0-255) Removed; the float (0-1) or java.awt.Color versions remain
Incremental save Manually mark every object with setNeedToBeUpdated(true) COSUpdateState records changes automatically (04-01)
Compression on save No object streams (PDF 1.4) Object streams by default (1.6); CompressParameters.NO_COMPRESSION to turn them off
Saving over the source file Worked (sometimes) Forbidden: it corrupts the file, because parts are read while saving
PDFTextStripper() throws IOException No checked exception
Markup annotations new PDAnnotationTextMarkup(subtype) Concrete subclasses: PDAnnotationHighlight, PDAnnotationUnderline...
org.apache.pdfbox.util.Charsets Existed Removed: java.nio.charset.StandardCharsets
Forms getAcroForm() without fixes getAcroForm() applies fix-ups; getAcroForm(null) to avoid them (05-01)
All objects COSDocument.getObjects() getXrefTable().keySet() + getObjectFromPool(key)
Command line java -jar pdfbox-app-2.x.jar ExtractText file.pdf Subcommands with options: java -jar pdfbox-app-3.x.jar export:text -i=file.pdf (01-05)
Preflight PreflightParser + parse() + getPreflightDocument().validate() Shortcut PreflightParser.validate(File) (08-01)
2.x deprecated methods Available with a warning Almost all removed (those in PDPageContentStream are kept, marked for internal use)

A detail about incremental saving: in 3.0.8, COSDictionary still has setNeedToBeUpdated (as a default method of COSUpdateInfo), so old code compiles. But it's no longer needed: PDFBox knows what has changed.

The same program, before and after

This PDFBox 2.0 program is typical of what you'll find in older projects: it creates a PDF with Helvetica, loads it with little memory, extracts its text, changes the title with an incremental save and merges two files. It compiles and works with 2.0.27:

// PDFBox 2.0.x
try (PDDocument doc = new PDDocument()) {
    PDPage page = new PDPage(PDRectangle.A4);
    doc.addPage(page);
    try (PDPageContentStream cs = new PDPageContentStream(doc, page, true, true)) {
        cs.setNonStrokingColor(31, 58, 95);
        cs.beginText();
        cs.setFont(PDType1Font.HELVETICA_BOLD, 18);
        cs.newLineAtOffset(57, 780);
        cs.drawString("Invoice F-2026-0001");
        cs.endText();
    }
    doc.save("output/invoice.pdf");
}
try (PDDocument doc = PDDocument.load(new File("output/invoice.pdf"), MemoryUsageSetting.setupTempFileOnly())) {
    System.out.println("Text: " + new PDFTextStripper().getText(doc).trim());
    doc.getDocumentInformation().setTitle("Invoice F-2026-0001");
    doc.getDocumentInformation().getCOSObject().setNeedToBeUpdated(true);   // mark by hand...
    doc.getDocumentCatalog().getCOSObject().setNeedToBeUpdated(true);       // ...the whole path
    try (OutputStream output = new FileOutputStream("output/invoice-title.pdf")) {
        doc.saveIncremental(output);
    }
}
PDFMergerUtility merger = new PDFMergerUtility();
merger.addSource(new File("output/invoice.pdf"));
merger.addSource(new File("output/invoice-title.pdf"));
ByteArrayOutputStream merged = new ByteArrayOutputStream();
merger.setDestinationStream(merged);
merger.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly());
try (PDDocument doc = PDDocument.load(merged.toByteArray())) {
    System.out.println("Merged: " + doc.getNumberOfPages() + " pages");
}

When you switch the dependency to 3.0.8 and compile, javac responds with six errors, which make up the migration to-do list:

Migration.java:23: error: incompatible types: boolean cannot be converted to AppendMode
Migration.java:26: error: cannot find symbol            (PDType1Font.HELVETICA_BOLD)
Migration.java:28: error: cannot find symbol            (drawString)
Migration.java:34: error: cannot find symbol            (PDDocument.load)
Migration.java:50: error: incompatible types: MemoryUsageSetting cannot be converted to StreamCacheCreateFunction
Migration.java:51: error: cannot find symbol            (PDDocument.load)

Notice what doesn't appear: line 24, setNonStrokingColor(31, 58, 95), compiles. We'll come back to it shortly. The migrated version:

// PDFBox 3.0.x
try (PDDocument doc = new PDDocument()) {
    PDPage page = new PDPage(PDRectangle.A4);
    doc.addPage(page);
    try (PDPageContentStream cs = new PDPageContentStream(doc, page,
            PDPageContentStream.AppendMode.APPEND, true)) {
        cs.setNonStrokingColor(new Color(31, 58, 95));                // java.awt.Color
        cs.beginText();
        cs.setFont(new PDType1Font(Standard14Fonts.FontName.HELVETICA_BOLD), 18);
        cs.newLineAtOffset(57, 780);
        cs.showText("Invoice F-2026-0001");
        cs.endText();
    }
    doc.save("output/invoice.pdf");
}
try (PDDocument doc = Loader.loadPDF(new File("output/invoice.pdf"), IOUtils.createTempFileOnlyStreamCache())) {
    System.out.println("Text: " + new PDFTextStripper().getText(doc).trim());
    doc.getDocumentInformation().setTitle("Invoice F-2026-0001");    // 3.x records the change by itself
    try (OutputStream output = new FileOutputStream("output/invoice-title.pdf")) {
        doc.saveIncremental(output);
    }
}
PDFMergerUtility merger = new PDFMergerUtility();
merger.addSource(new File("output/invoice.pdf"));
merger.addSource(new File("output/invoice-title.pdf"));
ByteArrayOutputStream merged = new ByteArrayOutputStream();
merger.setDestinationStream(merged);
merger.mergeDocuments(IOUtils.createMemoryOnlyStreamCache());
try (PDDocument doc = Loader.loadPDF(merged.toByteArray())) {
    System.out.println("Merged: " + doc.getNumberOfPages() + " pages");
}
Text: Invoice F-2026-0001
Merged: 2 pages
Title after the incremental save: Invoice F-2026-0001

The changes, line by line:

  • true (append) becomes AppendMode.APPEND; the second boolean (compress) stays.
  • Integer colours become java.awt.Color, which is what InvoiceLab has used since 02-05 (NebulaColors).
  • PDType1Font.HELVETICA_BOLD becomes a new PDType1Font(...). If you use it a lot, keep it in a variable yourself (per document).
  • drawString becomes showText.
  • PDDocument.load becomes Loader.loadPDF, and MemoryUsageSetting.setupTempFileOnly() becomes IOUtils.createTempFileOnlyStreamCache().
  • The two setNeedToBeUpdated lines disappear: the title still shows up after the incremental save.

Pitfalls that compile

These changes don't produce compilation errors; you'll discover them in testing or, worse, in production:

Pitfall Symptom in 3.x Solution
setNonStrokingColor(31, 58, 95) with integers Compiles (the float version is used) and throws IllegalArgumentException: Parameters must be within 0..1, but are (31.00,58.00,95.00) new Color(31, 58, 95) or divide by 255
Default compression with object streams PDF/A-1b files stop validating (/XRef cross reference streams are not allowed); old tools that look for objects with regular expressions fail CompressParameters.NO_COMPRESSION where needed (08-01)
getAcroForm() with fix-ups Appearances change, /DR appears, NeedAppearances becomes false getAcroForm(null) if you need the form as is (05-01)
Saving over the source file Corrupt file or exception; 3.0.8 warns: You are overwriting the existing file ..., this will produce a corrupted file if you're also reading from it Save to a temporary file and rename, like PdfEditor (04-01)
Using the document after close() Wrong results, not always an exception Try-with-resources and don't let PD* objects escape
Ligatures (GSUB) when writing with TrueType fonts The text "fi" appears as a ligature; position-based extraction changes (06-02) Normalise when extracting, or TrueTypeFont.setEnableGsub(false)
Shared system font cache 2.x and 3.x use the same ~/.pdfbox.cache in different formats: each version invalidates the other's and rebuilds it (2603 new font files found, font cache will be re-built) Separate them with -Dpdfbox.fontcache=<folder> per application (08-03)

A step-by-step migration strategy

flowchart TD
    A["1. Inventory<br/>mvn dependency:tree, grep for 2.x APIs"] --> B["2. Safety net<br/>tests and reference PDFs generated with 2.x"]
    B --> C["3. Change dependencies<br/>pdfbox, fontbox, pdfbox-io, xmpbox, preflight to 3.x"]
    C --> D["4. Fix compilation errors<br/>table of changes"]
    D --> E["5. Review pitfalls that compile<br/>colours, compression, AcroForm, saving"]
    E --> F["6. Compare results<br/>text, structure and VisualComparator"]
    F --> G{"Differences<br/>explained?"}
    G -- no --> E
    G -- yes --> H["7. Deploy and monitor<br/>memory, times, font cache"]
  1. Inventory. mvn dependency:tree | grep pdfbox to find out what's pulling in PDFBox 2 (01-02), and a search of the code for the known patterns: PDDocument.load, PDType1Font\.[A-Z], drawString, MemoryUsageSetting, setNeedToBeUpdated, setNonStrokingColor( and setStrokingColor( with three integers, new PDPageContentStream( with booleans.
  2. Safety net before touching anything. Generate the reference PDFs for each template with version 2.x and write the tests from lesson 08-05 (text, structure, visual regression). They're what will tell you whether the migration has changed anything.
  3. Change all the dependencies at once. Every PDFBox piece at the same version (${pdfbox.version}), and nothing from 2.x on the classpath.
  4. Fix the compilation errors with the table of changes. They're usually mechanical and quick.
  5. Review the pitfalls in the previous table by searching for them explicitly in the code.
  6. Compare. Run the tests. Byte differences are normal (compression, /ID, dates); text or pixel differences have to be understood one by one.
  7. Deploy with metrics (08-04): times, memory and file sizes, compared with the previous version.

InvoiceLab best-practice checklist

This list sums up the decisions we've made throughout the course. Use it to review your own code.

Resources and lifecycle

  • [ ] Every PDDocument in a try-with-resources; no PD* object outlives its document (01-04).
  • [ ] Source documents (importPage, Overlay, merges, templates) are closed after the target has been saved (04-04).
  • [ ] Never save over the input file: temporary file + ATOMIC_MOVE (PdfEditor, DocumentGenerator.generate(T, Path)).
  • [ ] One PDDocument per thread; generators keep no state between calls (08-03).
  • [ ] Disk stream cache for large documents or those of unknown origin (08-03, 08-04).

Fonts and text

  • [ ] TrueType fonts embedded as subsets, loaded from resources, never from the system (02-03, 08-04).
  • [ ] PDType0Font once per document; the font bytes, once per application (InvoiceLabFonts).
  • [ ] All text goes through sanitize before showText (02-03).
  • [ ] No Standard 14 fonts in documents that are archived or delivered (02-02, 08-01).

Coordinates and layout

  • [ ] Measurements in millimetres with Measures, a y cursor that moves down, content boxes (ContentBox) (02-01).
  • [ ] Blocks that return the height they consumed, and pagination centralised in Paginator (03-02, 03-04).
  • [ ] Graphics state always balanced (saveGraphicsState/restoreGraphicsState) and resetContext when adding content to existing pages (04-02).
  • [ ] Pages with /Rotate or an offset CropBox handled with Stamper.visibleMatrix (04-02).

Modification and saving

  • [ ] Incremental save for every document that is or may be signed; full save only for our own unsigned documents (04-01, 07-04).
  • [ ] Metadata with Metadata.forInvoice: Info as the source of truth, XMP in sync, /Lang and title (04-06).
  • [ ] Before publishing, Metadata.clean and a full save (04-06).

Security

  • [ ] Passwords and keys only in environment variables or a secrets manager (Secrets); test certificates kept out of Git (07-01).
  • [ ] AES-256 encryption and the accessibility permission always granted (07-01).
  • [ ] Sign as the last step, with an incremental save, and verify with SignatureVerifier (07-03, 07-04).
  • [ ] Every PDF received is untrusted: check the header, size and page limits, temporary cache and controlled errors (08-04).

Archiving and accessibility

  • [ ] Invoices archived as PDF/A-2b or 3b with an sRGB profile and XMP with pdfaid, validated with veraPDF (08-01).
  • [ ] Order: generate → PDF/A → validate → sign (08-01).
  • [ ] Public documents tagged: structure, artifacts, /Alt, language and PDF/UA validation (08-02).

Testing and production

  • [ ] Structure, content, position, signature and PDF/A tests on every build (08-05).
  • [ ] Visual regression against reference images, deterministic output (fixed clock, fixed /ID) and controlled updates (08-05).
  • [ ] Duration and size metrics; concurrency limits; java.awt.headless=true on servers (08-04).

The course journey and the final architecture

You've built InvoiceLab step by step, module by module:

Module What you learnt What InvoiceLab gained
1. Fundamentals The PDF format from the inside: COS objects, catalog, pages; the PDDocument lifecycle; tools HelloInvoiceLab, PdfInfo, PDFDebugger
2. Generating content Coordinates, text, Unicode fonts, layout, graphics, images pdf package: Measures, InvoiceLabFonts, TextMetrics, Shapes, Images
3. Business documents Tables, pagination, QR codes, reusable generators model and generator: BaseGenerator, blocks, InvoiceGenerator
4. Modifying PDFs Full and incremental saves, stamps, pages, merging and splitting, layers, metadata editing: PdfEditor, Stamper, InvoiceBatches, Metadata
5. Forms AcroForm: reading, filling, creating, appearances and flattening forms: PdfFields, RegistrationFormFiller, RegistrationIntake
6. Extraction Text, positions, images, rendering, bookmarks and annotations extraction: PdfText, TextLocator, VisualComparator
7. Security Encryption, digital signatures, timestamps, verification security: PdfSigner, SignatureVerifier
8. Production PDF/A, accessibility, performance, REST service, testing, migration archive, accessibility, service, automated tests

The final architecture, with the dependencies between packages (each arrow means "uses"):

flowchart BT
    model["model<br/>Invoice, Customer, InvoiceLine, InvoiceBatch"]
    pdf["pdf<br/>Measures, InvoiceLabFonts, TextMetrics,<br/>Table, Paginator, Images, PreencodedImage"]
    generator["generator<br/>DocumentGenerator, BaseGenerator, Block,<br/>InvoiceGenerator, DeliveryNoteGenerator"]
    editing["editing<br/>PdfEditor, Stamper, Pages,<br/>InvoiceBatches, Splitting, Layers, Metadata"]
    forms["forms<br/>PdfFields, RegistrationFormFiller, RegistrationIntake"]
    extraction["extraction<br/>PdfText, TextLocator, ResourceInventory,<br/>Thumbnails, VisualComparator, BatchNavigation"]
    security["security<br/>Protection, KeyVault, PdfSigner,<br/>SignatureVerifier, SignatureAppearance"]
    archive["archive<br/>PdfALevel, PdfAConverter,<br/>PdfAInvoiceGenerator, PdfAValidator"]
    accessibility["accessibility<br/>Tagger, TaggedBlock"]
    service["service (Spring Boot)<br/>InvoiceController, MergeController,<br/>PdfService, ErrorHandler"]
    tests["tests (JUnit 5)<br/>structure, content, positions,<br/>signatures, PDF/A, visual regression"]

    pdf --> model
    generator --> pdf
    generator --> model
    editing --> generator
    forms --> editing
    extraction --> editing
    security --> editing
    archive --> extraction
    archive --> editing
    accessibility --> generator
    accessibility --> editing
    service --> generator
    service --> security
    tests --> archive
    tests --> security
    tests --> extraction
    tests --> forms

Notice two properties we've looked after since module 3:

  • Dependencies point in one direction only, from the specific to the general. model knows nothing about PDF; pdf knows nothing about invoices; the REST service only knows DocumentGenerator<Invoice> and PdfSigner.
  • The pieces are combined without being modified: PdfAInvoiceGenerator decorates InvoiceGenerator, TaggedBlock decorates any Block, and the REST service uses the same generator as the command-line program from module 3.

Next steps

InvoiceLab covers the essentials, but the PDF ecosystem is vast. Some directions for further learning:

Direction What it is When it's of interest
veraPDF in depth Reference PDF/A and PDF/UA validator, with a CLI, a REST service and custom profiles To integrate validation into your deployment pipeline or to validate third-party documents
OpenHTMLtoPDF Converts HTML+CSS to PDF using PDFBox under the hood; supports PDF/A and PDF/UA When the design is done by a web team or the document is very text-heavy (contracts, reports)
OCR with Tesseract (for example, with Tess4J) Recognises text in images For the scanned supplier invoices that PdfText.pagesWithoutText detected in module 6
Advanced signatures (PAdES B-LT/B-LTA, for example with the DSS library) Signatures with revocation information and archive timestamps When a signature must remain verifiable for decades
Structured e-invoicing Facturae, Factur-X/ZUGFeRD, UBL When the attached XML (08-01) stops being "for teaching purposes"; always check the current regulations
Contributing to PDFBox An Apache Software Foundation project: users' mailing list, issues in the project's JIRA, code on GitHub When you find a bug: a minimal reproducible case with its PDF is the best contribution

And, above all, the tool you'll use most: PDFDebugger (01-05). Whenever a PDF behaves strangely, open the file and look at its structure. After this course, you know how to read it.

Common Mistakes and Tips

  • Migrating "blind", fixing only the compilation errors. The pitfalls that compile (colours, compression, AcroForm) are the ones that reach production. Prepare the tests and reference PDFs first.
  • Leaving 2.x modules on the classpath (an old transitive dependency). It causes NoSuchMethodError or ClassNotFoundException at runtime. Check mvn dependency:tree.
  • Copying examples from the Internet without checking the version. If you see PDDocument.load, it's 2.x code; adapt it with the table.
  • Comparing 2.x and 3.x PDFs byte for byte. They'll always be different (compression, /ID, object order). Compare text, structure and appearance.
  • Reintroducing setNeedToBeUpdated "just in case". In 3.x it's superfluous and confuses whoever reads the code.
  • Tip: if the project is large, migrate by functional area (generation first, then editing, then signatures), but without mixing versions: do each step on a branch and deploy only when everything is on 3.x.

Exercises

Exercise 1. Migrate this 2.0 fragment to PDFBox 3.x. It splits a PDF into single pages with little memory and extracts the text of each one:

PDDocument doc = PDDocument.load(new File("batch.pdf"), MemoryUsageSetting.setupTempFileOnly());
Splitter splitter = new Splitter();
splitter.setMemoryUsageSetting(MemoryUsageSetting.setupTempFileOnly());
List<PDDocument> pages = splitter.split(doc);
PDFTextStripper stripper = new PDFTextStripper();
for (int i = 0; i < pages.size(); i++) {
    System.out.println(i + 1 + ": " + stripper.getText(pages.get(i)).length() + " characters");
    pages.get(i).close();
}
doc.close();

Exercise 2. Write a FindApis2x program that walks through a source code directory (.java) and reports, for each file, the lines that use PDFBox 2.x APIs that have changed: PDDocument.load, PDType1Font.<CONSTANT>, drawString, MemoryUsageSetting, setNeedToBeUpdated and set(Non)StrokingColor with three literal integer arguments.

Exercise 3. Go through the best-practice checklist with the code of MergeController (08-04). Which points does it meet? Are there any that don't apply?

Solutions

Solution 1.

try (PDDocument doc = Loader.loadPDF(new File("batch.pdf"), IOUtils.createTempFileOnlyStreamCache())) {
    Splitter splitter = new Splitter();
    splitter.setStreamCacheCreateFunction(IOUtils.createTempFileOnlyStreamCache());
    List<PDDocument> pages = splitter.split(doc);
    PDFTextStripper stripper = new PDFTextStripper();                 // no longer throws IOException
    for (int i = 0; i < pages.size(); i++) {
        try (PDDocument page = pages.get(i)) {
            System.out.println(i + 1 + ": " + stripper.getText(page).length() + " characters");
        }
    }
}

Besides the mechanical changes (Loader.loadPDF, setStreamCacheCreateFunction, IOUtils), take the opportunity to fix what the original did wrong: if getText failed, neither the page nor the document was closed. With try-with-resources, everything is closed whatever happens. The documents returned by split share resources with the original, so they must be closed before it, as here.

Solution 2.

public class FindApis2x {

    private static final Map<String, Pattern> PATTERNS = new LinkedHashMap<>();
    static {
        PATTERNS.put("PDDocument.load → Loader.loadPDF", Pattern.compile("PDDocument\\.load\\s*\\("));
        PATTERNS.put("Static Standard 14 font", Pattern.compile("PDType1Font\\.[A-Z_]+\\b"));
        PATTERNS.put("drawString → showText", Pattern.compile("\\.drawString\\s*\\("));
        PATTERNS.put("MemoryUsageSetting → StreamCacheCreateFunction", Pattern.compile("MemoryUsageSetting"));
        PATTERNS.put("setNeedToBeUpdated: unnecessary in 3.x", Pattern.compile("setNeedToBeUpdated"));
        PATTERNS.put("Colour with 3 integers: fails at runtime", Pattern.compile(
                "set(Non)?StrokingColor\\s*\\(\\s*\\d+\\s*,\\s*\\d+\\s*,\\s*\\d+\\s*\\)"));
    }

    public static void main(String[] args) throws IOException {
        try (Stream<Path> files = Files.walk(Path.of(args[0]))) {
            for (Path f : files.filter(p -> p.toString().endsWith(".java")).sorted().toList()) {
                List<String> lines = Files.readAllLines(f);
                for (int i = 0; i < lines.size(); i++) {
                    for (Map.Entry<String, Pattern> e : PATTERNS.entrySet()) {
                        if (e.getValue().matcher(lines.get(i)).find()) {
                            System.out.printf("%s:%d  %s%n", f, i + 1, e.getKey());
                        }
                    }
                }
            }
        }
    }
}

With this lesson's 2.x program it reports lines 6 (the MemoryUsageSetting import), 24 (colour), 26 (font), 28 (drawString), 34 (load and MemoryUsageSetting), 38-39 (setNeedToBeUpdated), 50 (MemoryUsageSetting) and 51 (load). It's a textual search: it doesn't understand the code (it won't detect, for example, colours passed in integer variables), but it gives you a first to-do list in minutes. The compiler will find the PDPageContentStream constructor with booleans.

Solution 3. MergeController meets these points: every document is closed (in the body's finally or in the validation's catch); the sources are closed after the target has been saved; it uses a disk stream cache for documents of unknown origin; it treats what it receives as untrusted (%PDF- header, number of files, total pages, encryption, parsing errors turned into 422s); it saves nothing over the input files. The points about fonts, layout, signatures and PDF/A don't apply, because it doesn't generate new content. One point for improvement: unlike PdfService, it has no concurrency limit of its own; with many large merges at once, it would be worth adding a semaphore.

Conclusion

Migrating from PDFBox 2.x to 3.x is, for the most part, mechanical work guided by the compiler: Loader.loadPDF instead of PDDocument.load, Standard14Fonts.FontName, showText, AppendMode, StreamCacheCreateFunction and an incremental save that no longer needs manual marking. The delicate part is the changes that compile without errors, which is why the migration starts with a safety net of tests and reference PDFs, not with the pom.xml.

This lesson brings the course to an end. You started by opening a PDF to see that, inside, it's nothing more than a tree of objects, and you've finished with InvoiceLab: an application that generates paginated invoices with tables and QR codes, modifies them with stamps and incremental saves, fills in and creates forms, extracts information from supplier documents, encrypts and signs, archives as PDF/A, produces accessible documents, generates thousands of PDFs a minute, serves them over HTTP and checks everything with automated tests. Along the way you've learnt something that goes beyond PDFBox: to separate the model from the drawing, to design small pieces that combine, to measure before optimising and never to take anything as correct without verifying it. Those habits will serve you with any format and any library. Now it's your turn: pick a real document from your work and build it with what you've learnt.

PDF Generation and Editing with Apache PDFBox

Module 1: PDF and PDFBox Fundamentals

Module 2: Generating Content

Module 3: Business Documents

Module 4: Editing Existing PDFs

Module 5: AcroForm Forms

Module 6: Extraction and Analysis

Module 7: Security and Digital Signatures

Module 8: PDFBox in Production

© Copyright 2026. All rights reserved