So far InvoiceLab has only created documents from scratch. But in a real company most PDF work consists of touching documents that already exist: marking as paid an invoice issued a month ago, adding a receipt stamp to a delivery note sent by a supplier, attaching general terms and conditions or fixing the metadata of a batch. In this lesson you'll learn what PDFBox really does when it loads a PDF, how the in-memory model is modified and, above all, the two ways of saving the result: the full save, which rewrites the entire file, and the incremental save, which leaves the original untouched and appends the changes at the end. We'll build the PdfEditor utility, the first class of the new com.invoicelab.editing package, and use it to mark invoice F-2026-0001 as paid in both ways.

Contents

  1. What happens when a PDF is loaded
  2. Modifying the document in memory
  3. Full save with save
  4. Incremental save with saveIncremental
  5. How PDFBox knows what has changed: COSUpdateInfo and COSUpdateState
  6. Don't overwrite the file that is open: the PdfEditor utility
  7. InvoiceLab example: marking F-2026-0001 as paid
  8. Viewing the section appended by the incremental save
  9. Damaged PDFs: the lenient parser
  10. Documents with an owner password

What happens when a PDF is loaded

In lesson 01-04 you saw that Loader.loadPDF(...) accepts a File, a byte[] or a RandomAccessRead. Now it's worth knowing what it does internally, because the memory you consume and what you can do afterwards both depend on it.

flowchart LR
    A["PDF file<br/>(RandomAccessRead)"] --> B["1. Header<br/>%PDF-1.x"]
    B --> C["2. End of file:<br/>startxref → xref table"]
    C --> D["3. Trailer:<br/>/Root, /Info, /ID, /Encrypt"]
    D --> E["4. COSDocument with<br/>unresolved objects"]
    E -->|"getPage(0), getTitle()..."| F["5. Only the requested<br/>object is read and parsed"]

Step by step:

  1. Read source. Everything is read through a RandomAccessRead (the pdfbox-io module). With a File, PDFBox uses RandomAccessReadBufferedFile, which reads chunks from disk on demand; with a byte[], the whole document is already in memory.
  2. It starts at the end. The parser looks for startxref at the end of the file, jumps to the cross-reference table (xref) and reads the trailer. The xref is an index: "object 12 is at byte 4,318".
  3. Lazy loading. When loadPDF returns, most objects have not been parsed yet: they are COSObject instances, references that only know where the real object is. The first time you ask for something (getPage(0), a resource, the text of a stream), PDFBox jumps to that position and parses it.
  4. The file stays open. Because objects are read when they are needed, the PDDocument keeps the source open until you call close(). This has an important consequence that we'll look at in section 6.
Load source Memory when opening File locked while open
Loader.loadPDF(File) Low: only indexes and the objects used Yes
Loader.loadPDF(byte[]) The whole PDF in memory No (there is no file)
Loader.loadPDF(RandomAccessRead) Depends on the implementation Depends

For very large documents there are overloads such as Loader.loadPDF(File, StreamCacheCreateFunction), which control where temporary data is stored. We'll look at them in lesson 08-03.

Modifying the document in memory

Once loaded, the document is exactly the same model you used to create invoices: PDDocument, PDPage, PDPageContentStream, COSDictionary dictionaries… The difference is that some of the objects now come from the file.

  • Nothing is written to disk until you call save or saveIncremental. You can make a hundred changes and discard them all by closing the document without saving.
  • You can work at the PD level (document.getDocumentInformation().setTitle(...), page.setRotation(90)) or at the COS level (catalog.getCOSObject().setItem(...)), as you saw in lesson 01-03.
  • Objects you don't touch are never parsed: if you only modify the catalog, the images on page 3 are copied as they are when saving.

Full save with save

save(...) is the method you already know. When you call it on a loaded document, PDFBox:

  1. Walks through every object reachable from the trailer (catalog, pages, resources…).
  2. Renumbers them and writes them out again, one after another.
  3. Generates a new xref and a new trailer.

The result is a clean and compact PDF: orphan objects disappear, PDFBox 3's compression and object streams are applied (version 1.6, as you saw in 01-05) and the file ends up with a single revision. In exchange, the bytes of the original no longer exist: the new file is a different file.

Incremental save with saveIncremental

The PDF specification allows another way of saving: leave the original file as it is and append an "incremental update" containing only the modified objects, a new xref pointing to them and a trailer with /Prev pointing to the previous xref.

flowchart TB
    subgraph R1["Revision 1 (original bytes, untouched)"]
        H["%PDF-1.6"] --> O1["Objects 1..37"] --> X1["xref + trailer"] --> E1["startxref 51993<br/>%%EOF"]
    end
    subgraph R2["Incremental update (appended at the end)"]
        O2["Object 38 (new)<br/>Object 1 (modified catalog)"] --> X2["xref: only objects 0, 1, 38, 39<br/>trailer /Prev 51993"] --> E2["startxref 52562<br/>%%EOF"]
    end
    R1 --> R2

A PDF reader starts from the last startxref, finds there the new version of the changed objects and, for everything else, follows the /Prev chain back to the previous revision.

try (PDDocument document = Loader.loadPDF(new File("output/F-2026-0001.pdf"));
     OutputStream output = new FileOutputStream("output/F-2026-0001-incremental.pdf")) {
    // ... changes ...
    document.saveIncremental(output);   // writes: original + update
}
  • saveIncremental only accepts an OutputStream: there is no version taking a File or a String.
  • It only works with documents loaded from a file or a stream. On a new PDDocument() it throws IllegalStateException: document was not loaded from a file or a stream.
  • It first copies the original bytes to the OutputStream and then appends the update.

Why would you want a larger file instead of a compact one?

Reason Explanation
Digital signatures A signature protects a specific range of bytes. If you rewrite the file, the signature is no longer valid; if you append at the end, the signed revision remains intact. We'll cover this in depth in module 7.
Auditing Every previous revision can be reconstructed: just cut the file after its %%EOF. You know what the invoice said before the «PAID» stamp.
Speed with large files Changing a metadata entry in a 300 MB PDF only writes a few hundred new bytes (plus the copy of the original).
Fidelity What you don't touch is neither reinterpreted nor rewritten: useful with third-party documents produced by quirky tools.
save (full) saveIncremental
Original revision Disappears Preserved byte for byte
Size Minimal Original + changes
Orphan objects Removed Remain in old revisions
Existing signatures Invalidated Preserved (if the change is allowed)
New document (new PDDocument()) Yes No
Target File, String or OutputStream OutputStream only

How PDFBox knows what has changed: COSUpdateInfo and COSUpdateState

To write only what has been modified, PDFBox needs to know which objects have changed. The COS objects that can change (COSDictionary, COSArray, COSObject, COSStream) implement the COSUpdateInfo interface:

public interface COSUpdateInfo extends COSObjectable {
    default boolean isNeedToBeUpdated() { ... }       // must it be written in the update?
    default void setNeedToBeUpdated(boolean flag) { ... }
    COSUpdateState getUpdateState();                   // update state (new in 3.x)
}

This is where the big difference between versions lies:

PDFBox 2.x PDFBox 3.x
Marking modified objects Manual: setNeedToBeUpdated(true) on every changed object and on the whole chain up to the catalog Automatic: every object has a COSUpdateState; any setItem, add, remove… after loading marks it
Forgetting a mark The change doesn't appear in the update (silent failure) Rarely needed
Forcing specific objects There was no direct way saveIncremental(OutputStream, Set<COSDictionary>)

In PDFBox 3, while parsing, the document is in the "parsing" state (COSDocumentState) and changes don't count; once loading has finished, any modification marks the object. You can check it:

COSDictionary catalog = document.getDocumentCatalog().getCOSObject();
System.out.println(catalog.isNeedToBeUpdated());   // false: just loaded
catalog.setString(COSName.getPDFName("Test"), "x");
System.out.println(catalog.isNeedToBeUpdated());   // true: marked automatically

When do you still need to step in?

  • Non-flat page trees. If a third-party document has intermediate /Pages nodes and you modify a page, the PDFBox documentation recommends also marking the chain of parents:
COSDictionary parent = page.getCOSObject().getCOSDictionary(COSName.PARENT);
while (parent != null) {
    parent.setNeedToBeUpdated(true);           // ensures a path of updated objects
    parent = parent.getCOSDictionary(COSName.PARENT);
}
  • Forcing a dictionary to be included even when there is no marked path leading to it: document.saveIncremental(output, Set.of(dictionary)). This is a tool for advanced users (mostly for signatures); always check the result with an editor or PDFDebugger.
  • Legacy 2.x code: calls to setNeedToBeUpdated(true) still compile and do no harm.

Don't overwrite the file that is open: the PdfEditor utility

Remember that a document loaded from a File keeps reading from the file while it is open. If you save over the same file:

  • With save, PDFBox may need to read an object from the original just when you've already truncated it: the result is a corrupted PDF.
  • With saveIncremental it's even worse: it first copies the original… from a file you are overwriting. The documentation warns about this explicitly: the target must never be the source file.
  • PDFBox 3's save(File) and save(String) log a warning every time the target already exists (You are overwriting the existing file ..., this will produce a corrupted file if you're also reading from it), but they only warn: they don't prevent it. Saving to a new temporary file also avoids that warning.

The solution is the same idea as DocumentGenerator.generate(T, Path) from module 3 (write to a temporary file and rename it), with one subtlety: the document must be closed before renaming, so that the source is no longer in use (on Windows, an open file cannot be replaced).

package com.invoicelab.editing;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;

import org.apache.pdfbox.Loader;
import org.apache.pdfbox.pdmodel.PDDocument;

/** Opens an existing PDF, applies a change to it and saves it safely (temporary file + rename). */
public final class PdfEditor {

    /** How the result is written. */
    public enum Mode {
        /** Rewrites the whole document (more compact; the original revision disappears). */
        FULL,
        /** Appends only what was modified (the original revision stays intact byte for byte). */
        INCREMENTAL
    }

    /** A change applied to the open document. */
    @FunctionalInterface
    public interface Change {
        void apply(PDDocument document) throws IOException;
    }

    private PdfEditor() {
    }

    /**
     * Loads source, applies the change and writes the result to target.
     * target may be the same file as source: it is only replaced when everything has succeeded.
     */
    public static void edit(Path source, Path target, Mode mode, Change change) throws IOException {
        Path folder = target.toAbsolutePath().getParent();
        Files.createDirectories(folder);
        Path temporary = Files.createTempFile(folder, "invoicelab-", ".tmp");
        try {
            try (PDDocument document = Loader.loadPDF(source.toFile());
                 OutputStream output = new BufferedOutputStream(Files.newOutputStream(temporary))) {
                change.apply(document);
                if (mode == Mode.INCREMENTAL) {
                    document.saveIncremental(output);
                } else {
                    document.save(output);
                }
            } // at this point the document is closed: the source file is no longer in use
            Files.move(temporary, target, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE);
        } finally {
            Files.deleteIfExists(temporary);
        }
    }
}

How it works:

  • Change is a functional interface: the caller passes a lambda with what it wants to do (document -> {...}). PdfEditor takes care of opening, saving and closing; the business code only describes the change. We'll use this pattern throughout the module.
  • The temporary file is created in the same folder as the target, because ATOMIC_MOVE only works within the same file system.
  • The inner try has two resources. Java closes them in reverse order: first the OutputStream (the bytes are flushed to the temporary file) and then the PDDocument (the source is released).
  • Only when both are closed does Files.move run. If change.apply or the save throws an exception, the move is never reached: the target file (which may be the source itself) remains intact, and the finally deletes the temporary file.
  • BufferedOutputStream groups PDFBox's small writes into large blocks: saving is noticeably faster.
  • Thanks to all this, edit(p, p, ...), with the same source and target, is safe.

InvoiceLab example: marking F-2026-0001 as paid

We're going to record the payment of the invoice inside the PDF itself using a private key in the catalog, just as we did with /InvoiceLabRef in lesson 01-03. It will be an /InvoiceLabStatus dictionary with two entries: the status (a PDF name) and the payment date. It isn't visible when you open the document (the visible stamp arrives in lesson 04-02), but any program can read it.

package com.invoicelab.examples;

import com.invoicelab.editing.PdfEditor;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;

import org.apache.pdfbox.Loader;
import org.apache.pdfbox.cos.COSDictionary;
import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.pdmodel.PDDocument;

public class MarkInvoiceStatus {

    private static final COSName STATUS = COSName.getPDFName("InvoiceLabStatus");

    public static void main(String[] args) throws IOException {
        Path original = Path.of("output/F-2026-0001.pdf");
        Path full = Path.of("output/F-2026-0001-full.pdf");
        Path incremental = Path.of("output/F-2026-0001-incremental.pdf");

        PdfEditor.Change markPaid = document -> {
            COSDictionary status = new COSDictionary();
            status.setName(COSName.getPDFName("Status"), "Paid");
            status.setString(COSName.getPDFName("PaymentDate"), "2026-02-10");
            document.getDocumentCatalog().getCOSObject().setItem(STATUS, status);
        };

        PdfEditor.edit(original, full, PdfEditor.Mode.FULL, markPaid);
        PdfEditor.edit(original, incremental, PdfEditor.Mode.INCREMENTAL, markPaid);

        byte[] originalBytes = Files.readAllBytes(original);
        byte[] incrementalBytes = Files.readAllBytes(incremental);
        System.out.printf("Original:    %,d bytes%n", originalBytes.length);
        System.out.printf("Full:        %,d bytes%n", Files.size(full));
        System.out.printf("Incremental: %,d bytes (+%,d)%n", incrementalBytes.length,
                incrementalBytes.length - originalBytes.length);

        // Does the incremental file start with exactly the bytes of the original?
        boolean intact = Arrays.equals(originalBytes,
                Arrays.copyOf(incrementalBytes, originalBytes.length));
        System.out.println("Original revision intact inside the incremental file: " + intact);

        for (Path p : new Path[] { full, incremental }) {
            try (PDDocument document = Loader.loadPDF(p.toFile())) {
                System.out.println(p.getFileName() + " → " + document.getDocumentCatalog()
                        .getCOSObject().getCOSDictionary(STATUS));
            }
        }
    }
}

Explanation:

  • The markPaid lambda is defined once and reused for both modes: that way we compare exactly the same change.
  • setName stores a PDF name (/Paid), suitable for values from a closed list; setString stores a string ((2026-02-10)), suitable for free text. We use the ISO format for the date because it is unambiguous and sortable.
  • setItem(STATUS, status) hangs the new dictionary from the catalog. In PDFBox 3 this call automatically marks the catalog as modified.
  • Arrays.copyOf(incrementalBytes, originalBytes.length) takes the first bytes of the incremental file to compare them with the original: it is the proof that revision 1 hasn't been touched.
  • Finally we reload both files to verify that each of them contains the status.

Output (with the 30-line invoice from module 3):

Original:    52,410 bytes
Full:        52,480 bytes
Incremental: 52,892 bytes (+482)
Original revision intact inside the incremental file: true
F-2026-0001-full.pdf → COSDictionary{COSName{Status}:COSName{Paid};COSName{PaymentDate}:COSString{2026-02-10};}
F-2026-0001-incremental.pdf → COSDictionary{COSName{Status}:COSName{Paid};COSName{PaymentDate}:COSString{2026-02-10};}
  • The full file barely grows (70 bytes): the new dictionary is compressed inside an object stream.
  • The incremental file grows by 482 bytes: the whole catalog rewritten, the new dictionary, an xref and a trailer, none of it compressed inside object streams. That fixed overhead is irrelevant in real documents.

Viewing the section appended by the incremental save

Because the update sits at the end of the file and its objects aren't compressed, you can read it with any text editor or from the terminal (strings filters out the binary bytes of the xref stream):

tail -c 560 output/F-2026-0001-incremental.pdf | strings

Output (abridged):

startxref
51993
%%EOF                       ← end of revision 1 (the original)
38 0 obj
/Status /Paid
/PaymentDate (2026-02-10)
endobj
1 0 obj                     ← the catalog, rewritten with the new key
/Type /Catalog
/Version /1.6
/Pages 2 0 R
/InvoiceLabStatus 38 0 R
endobj
39 0 obj                    ← xref stream of the update
/Root 1 0 R
/Prev 51993                 ← points to the xref of revision 1
/Type /XRef
/Index [0 2 38 2]           ← only describes objects 0-1 and 38-39
...
startxref
52562
%%EOF                       ← end of revision 2

Notice three details:

  • The catalog keeps its number (1 0 obj): an incremental update replaces objects by number; it doesn't renumber them.
  • The status dictionary is a new object (38), the next free number.
  • /Prev 51993 matches the startxref of the previous revision: that's how revisions are chained together.

Counting the occurrences of %%EOF (grep -ac "%%EOF" file.pdf) gives you a quick idea of the number of revisions: the full file has 1 and the incremental one has 2. You can also open it in PDFDebugger (lesson 01-05); and if you have qpdf installed, qpdf --show-xref shows the resulting reference table.

Damaged PDFs: the lenient parser

Third-party PDFs often arrive with defects: an xref with wrong offsets, a missing %%EOF because the download was cut off, badly closed objects. By default Loader.loadPDF uses a lenient parser: if the xref doesn't add up, it scans the whole file looking for objects (BruteForceParser) and rebuilds the index.

To see it in action, we deliberately break the invoice's startxref and compare with strict mode, which you get by creating the PDFParser directly:

byte[] bytes = Files.readAllBytes(Path.of("output/F-2026-0001.pdf"));
String text = new String(bytes, StandardCharsets.ISO_8859_1);
byte[] damaged = text.replace("startxref\n51993", "startxref\n40000")   // fake offset
        .getBytes(StandardCharsets.ISO_8859_1);

// Strict: fails as soon as something doesn't add up
try (PDDocument d = new PDFParser(new RandomAccessReadBuffer(damaged)).parse(false)) {
    System.out.println("Strict: " + d.getNumberOfPages() + " pages");
} catch (IOException e) {
    System.out.println("Strict: " + e.getMessage());
}

// Lenient (the one Loader uses): rebuilds the xref
try (PDDocument d = Loader.loadPDF(damaged)) {
    System.out.println("Lenient: " + d.getNumberOfPages() + " pages");
    d.save("output/repaired.pdf");   // a FULL save produces a healthy file
}
Strict: Error: Expected a long type at offset 40000, instead got ''
Lenient: 2 pages
  • ISO_8859_1 converts bytes to characters one to one, without losing anything, so we can use String.replace and turn the result back into bytes without damaging the binary content.
  • parse(false) disables leniency: useful in validations, when you want to reject defective files instead of silently accepting them.
  • A recovered document must be saved in full mode: an incremental save would copy the defective bytes as they are.
  • Leniency has its limits: if the file is so truncated that the page tree is missing, you'll see errors such as Page tree root must be a dictionary, and a file that isn't a PDF produces an IOException straight away. Always catch IOException when loading third-party documents.

Documents with an owner password

Many supplier PDFs arrive with an owner password (they open without asking for anything, but they restrict modifying or printing). Remember from lesson 01-04 that PDFBox opens them without a password. What happens when you save them?

  • document.isEncrypted() tells you whether it is encrypted and getCurrentAccessPermission() what it allows (for example, canModify()).
  • A full save of an encrypted document fails in PDFBox 3 with IllegalStateException: PDF contains an encryption dictionary, please remove it with setAllSecurityToBeRemoved() or set a protection policy with protect(). PDFBox forces you to decide: remove the encryption or apply a new one.
  • An incremental save does work and keeps the original encryption: the new objects are encrypted with the same key.
  • document.setAllSecurityToBeRemoved(true) makes the next full save be written without encryption. Only use it on documents you are entitled to do this with: bypassing restrictions set by the author may breach their terms of use.

Encryption and permissions are covered in detail in lesson 07-01.

Common Mistakes and Tips

  • Saving over the open file. document.save(source) or saveIncremental to the same file corrupts it. Use PdfEditor.edit, which writes to a temporary file, closes and renames.
  • IllegalStateException: document was not loaded from a file or a stream. You've called saveIncremental on a document created with new PDDocument(). An incremental save only makes sense if there is a previous revision.
  • Passing a FileOutputStream that is never closed. If you don't close (or flush) the stream, the file ends up truncated. Open the stream in the try-with-resources, as PdfEditor does.
  • Expecting the incremental file to be smaller. It is larger than the original (it contains all of it). Its advantage is preserving the revision, not size.
  • Copying PDFBox 2.x recipes full of setNeedToBeUpdated(true). In 3.x they do no harm, but they aren't needed in most cases; don't assume your change "isn't saved" because you didn't call it. If a change doesn't appear in the update, first check whether you modified an object that is actually in the document (and not a copy).
  • Silently accepting damaged PDFs. Lenient mode is convenient, but in an invoice intake process you might prefer to log the problem. You can load in strict mode first and, if that fails, raise a warning and retry in lenient mode.
  • Tip: generate your test invoices with compress = false and CompressParameters.NO_COMPRESSION (lesson 01-05) when you want to study the result of a full save in an editor.

Exercises

Exercise 1. Write a method static Optional<String> status(Path pdf) that returns the value of /Status from the catalog's /InvoiceLabStatus dictionary, or Optional.empty() if the invoice has no status. Try it with F-2026-0001.pdf and with F-2026-0001-incremental.pdf.

Exercise 2. Write static List<Integer> revisionEnds(byte[] pdf), which returns the position (in bytes) where each revision ends: right after each %%EOF and its line break. Use it to extract the first revision of F-2026-0001-incremental.pdf and check that it is identical to F-2026-0001.pdf.

Exercise 3. You want to generate an invoice and, in the same program, add an incremental revision to it with the document title. Write the code without touching the disk: generate a one-page PDF into a byte[], reload it, change the title with getDocumentInformation().setTitle(...) and save it incrementally into a ByteArrayOutputStream. Why can't you call saveIncremental directly on the newly created document?

Solutions

Solution 1.

public static Optional<String> status(Path pdf) throws IOException {
    try (PDDocument document = Loader.loadPDF(pdf.toFile())) {
        COSDictionary status = document.getDocumentCatalog().getCOSObject()
                .getCOSDictionary(COSName.getPDFName("InvoiceLabStatus"));
        if (status == null) {
            return Optional.empty();
        }
        return Optional.ofNullable(status.getNameAsString(COSName.getPDFName("Status")));
    }
}
  • getCOSDictionary returns null if the key doesn't exist or if its value isn't a dictionary, and it automatically resolves the indirect reference (38 0 R).
  • getNameAsString returns the name without the slash: "Paid".
  • Result: Optional[Paid] for the incremental file and Optional.empty for the original.

Solution 2.

public static List<Integer> revisionEnds(byte[] pdf) {
    String text = new String(pdf, StandardCharsets.ISO_8859_1);
    List<Integer> ends = new ArrayList<>();
    int from = 0;
    int pos;
    while ((pos = text.indexOf("%%EOF", from)) >= 0) {
        int end = pos + 5;                                       // length of "%%EOF"
        if (end < text.length() && text.charAt(end) == '\r') end++;
        if (end < text.length() && text.charAt(end) == '\n') end++;
        ends.add(end);
        from = end;
    }
    return ends;
}

// Usage
byte[] inc = Files.readAllBytes(Path.of("output/F-2026-0001-incremental.pdf"));
List<Integer> ends = revisionEnds(inc);                         // [52410, 52892]
byte[] first = Arrays.copyOf(inc, ends.get(0));
System.out.println(Arrays.equals(first, Files.readAllBytes(Path.of("output/F-2026-0001.pdf"))));  // true
  • The line ending after %%EOF may be \n, \r\n or missing altogether: the two if statements handle that.
  • It's an approximation: a %%EOF could appear inside a binary stream. For serious audits you follow the startxref//Prev chain; in module 7 you'll see that every signature states exactly its byte range (/ByteRange).

Solution 3.

byte[] bytes;
try (PDDocument created = new PDDocument()) {
    created.addPage(new PDPage());
    ByteArrayOutputStream b = new ByteArrayOutputStream();
    created.save(b);
    bytes = b.toByteArray();
}
try (PDDocument reloaded = Loader.loadPDF(bytes)) {
    reloaded.getDocumentInformation().setTitle("Revision 2");
    ByteArrayOutputStream b = new ByteArrayOutputStream();
    reloaded.saveIncremental(b);
    System.out.println(bytes.length + " → " + b.size() + " bytes");   // 594 → 979 bytes
}

A document created in memory has no previous revision to copy: saveIncremental needs the original source (pdfSource) to write its bytes before the update. That's why it is saved first (revision 1) and then reloaded. In practice, with InvoiceLab you would do Loader.loadPDF(generator.generate(invoice)).

Conclusion

You now understand the complete editing cycle: Loader.loadPDF reads the file's index and parses objects only when you need them; changes live in memory until you save; save rewrites a compact document with a single revision, whereas saveIncremental keeps the original intact and appends the changes at the end, something essential for the signatures in module 7 and very valuable for auditing. You know that in PDFBox 3 each object's COSUpdateState records modifications automatically, and when it's worth marking objects by hand. With PdfEditor you have a safe way to edit any PDF, even overwriting the original, and you know how damaged documents and documents protected with an owner password behave.

But the «paid» status we've added is invisible. In the next lesson we'll draw on the pages of existing documents: a «PAID» stamp with the payment date, watermarks and receipt stamps on third-party documents, using PDPageContentStream in APPEND and PREPEND mode and the Stamper class.

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