Throughout this module the word appearance has come up again and again: checkboxes need their on and off appearances, setValue generates the appearance of text fields, GenerateRegistrationForm has to refresh them at the end… In this last lesson of the module we're going to understand in depth what an appearance is, why a form with correct values can show up empty in some viewers, and what PDFBox can and can't do to prevent it. Then we'll learn to flatten forms: turning the fields into fixed page content, so that the document can no longer be edited and looks the same everywhere. With all this we'll close the loop on Nebula Distribution's customer registration form: receive it, validate it, number it, flatten it, stamp it as "RECEIVED" and archive it, with special handling for forms that arrive already signed.
Contents
- Value and appearance: two different things
- The appearance dictionary:
/N,/D,/Rand the/ASstate - Why a value might not be visible
- Which appearances PDFBox generates and which it doesn't
- Flattening a whole form
flatten(List, boolean)and the parent-field trap- Flattening only some fields
- The alternative: read-only fields
- The complete flow:
RegistrationIntake
Value and appearance: two different things
Remember the distinction from lesson 05-01: the field stores the value (/V) and the widget stores the appearance (/AP). They're two independent pieces of data:
flowchart LR
V["Field<br/>/V (Example Hardware Co.)"] -.->|"setValue generates"| AP["Widget<br/>/AP /N: stream with<br/>BT /Helv 10 Tf ... (Example Hardware...) Tj ET"]
AP -->|"what the viewer DRAWS"| Screen["Screen / print"]
V -->|"what a program READS"| Data["getValueAsString()"]
- A viewer draws the appearance; it normally doesn't recalculate it from the value.
- A program (or the viewer itself when it exports data) reads the value.
If the two are in sync, all is well. If they aren't, you get the most baffling form problems: a PDF that says one thing on screen and another when you extract its data, or a field that "has a value" but looks empty. We already saw one case in 05-02: a postal code with MaxLen 5 to which we assigned seven characters; the value held seven and the comb appearance showed five.
The appearance dictionary: /N, /D, /R and the /AS state
A widget's /AP dictionary can have up to three entries:
| Key | Name | When it's shown | Required |
|---|---|---|---|
/N |
Normal | Always, except in the following cases | Yes (in practice) |
/D |
Down | While the user holds the mouse button down on the widget | No |
/R |
Rollover | While the pointer is over it | No |
And each entry can take one of two forms:
- A single stream: the usual case for text fields, lists and signatures. We've checked it: in
customer.companyName,/AP /Nis a stream directly. - A subdictionary of streams, one per state: the usual case for checkboxes and radio buttons. In
terms.accepted,/AP /Ncontains/Yesand/Off, and there's no/D.
When there's a subdictionary, the widget says which one to show with /AS (appearance state). In a ticked checkbox, /V /Yes on the field and /AS /Yes on the widget; if someone changed only one of the two, we'd once again have value and appearance out of sync. PDFBox keeps both up to date when you use setValue, check() or unCheck().
In PDFBox:
PDAnnotationWidget widget = field.getWidgets().get(0);
PDAppearanceDictionary ap = widget.getAppearance(); // /AP (may be null)
PDAppearanceEntry normal = ap.getNormalAppearance(); // /N
if (normal.isSubDictionary()) {
Map<COSName, PDAppearanceStream> states = normal.getSubDictionary(); // {Yes=..., Off=...}
COSName shown = widget.getAppearanceState(); // /AS
} else {
PDAppearanceStream single = normal.getAppearanceStream();
}
PDAppearanceEntry down = ap.getDownAppearance(); // /D (null if there isn't one)Why a value might not be visible
Let's run an experiment that reproduces what some tools produce: they write the value into /V without touching the appearance and, to compensate, they turn on NeedAppearances:
try (PDDocument document = Loader.loadPDF(new File("output/registration-form.pdf"))) {
PDAcroForm form = document.getDocumentCatalog().getAcroForm(null);
// We write /V directly into the COS dictionary: no appearance gets updated
form.getField("customer.companyName").getCOSObject()
.setString(COSName.V, "Value Without Appearance Ltd.");
form.setNeedAppearances(true); // "viewer: regenerate the appearances yourself"
document.save("output/no-ap.pdf");
}What happens with no-ap.pdf?
| Who opens it | Result |
|---|---|
A viewer that honours NeedAppearances (Acrobat and others) |
Regenerates the appearance and shows the value. On closing, asks to save changes |
| A viewer that doesn't honour it, or the PDFBox renderer (we'll use it in 06-04) | Draws the stored appearance, which is empty: the field looks blank |
A program that reads data (getValueAsString()) |
Gets "Value Without Appearance Ltd." |
PDFBox's getAcroForm(), with its automatic fixups |
Generates the appearances and sets NeedAppearances to false (lesson 05-01) |
We rendered no-ap.pdf with PDFBox and, sure enough, the company name appears empty. The typical causes of a "value you can't see" are:
- Missing or outdated appearance with
NeedAppearancesset totrue, in a viewer that doesn't honour it. /ASstate inconsistent with/Vin checkboxes and radio buttons.- Font without the necessary glyphs: a subset font that lacks the new characters (05-02).
- Widget hidden or off the page: Hidden flag,
/Rectoutside theCropBox, or widget missing from/Annots. - Non-printable widget: visible on screen but doesn't come out on paper (the Print flag is missing, lesson 05-03).
The moral for InvoiceLab: documents that leave our system must carry their generated appearances with NeedAppearances set to false, and documents that come in may arrive in any state, so before archiving them we'll regenerate the appearances ourselves.
Which appearances PDFBox generates and which it doesn't
PDFBox includes an appearance generator (it runs in setValue, refreshAppearances and flatten(..., true)). It's worth knowing its scope:
| Field type | Does PDFBox generate the appearance? | Details |
|---|---|---|
| Single-line text | Yes | Uses /DA, the /MK background and border, and the alignment (/Q) |
| Multiline text | Yes | Wraps lines at word boundaries; with size 0 (automatic) it applies a default size |
| Comb text | Yes | One cell per character, with dividers |
| Drop-down and list | Yes | Draws the option's display text; in lists, highlights the selected ones |
| Checkbox and radio button | Doesn't create them | Only switches /AS between existing appearances; if they're missing, there are no valid states |
| Push button | No | Its appearances must already be there |
| Signature | No | Warns: "Appearance generation for signature fields not implemented here" (module 7) |
| Rich text | No | Doesn't interpret the formatting: draws the value as plain text |
And its practical limits:
- It can only use the fonts in
/DR, with whatever characters they have: Helvetica and WinAnsi, unless you add a Unicode font (05-02). - It doesn't run JavaScript: an amount format or a total calculated by a script won't be applied (05-03).
- The result isn't identical to Acrobat's: margins, automatic sizing or line breaks may differ slightly. If the design is very tight, check the result visually.
Flattening a whole form
Flattening means turning each widget into fixed page content and removing the fields. The result is no longer a form: it's an ordinary document that looks exactly the way the filled-in form looked. It's what you do before archiving or forwarding a form whose content must not change any more.
try (PDDocument document = Loader.loadPDF(new File("output/registrations/registration-hardware.pdf"))) {
PDAcroForm form = document.getDocumentCatalog().getAcroForm(null);
form.flatten();
document.save("output/fully-flattened.pdf");
}Under the hood, flatten() takes the /N appearance (the /AS state for buttons) of each widget, embeds it in the page content as a form XObject, removes the widget from /Annots and deletes the field from the tree. We checked it on registration-hardware.pdf: the page goes from 20 annotations to 0 and the form from 18 fields to none. The /AcroForm dictionary still exists in the catalog, but empty: if you run FormInspector on the result, you'll see its /DA and a table with no rows.
Two important warnings:
flatten()uses whatever appearances are there; it doesn't regenerate them. If the form hadNeedAppearances = true, PDFBox warns: "acroForm.getNeedAppearances() returns true, visual field appearances may not have been set" and "call acroForm.refreshAppearances() or use the flatten() method with refreshAppearances parameter". We tried it withno-ap.pdf: afterflatten()the company name was left blank for good, because there's no longer a field to regenerate it from.- Flattening is irreversible: the data can no longer be read with
getField. Before flattening, extract whatever you need (RegistrationFormFiller.read). Recovering the text from a flattened PDF requires the extraction techniques of module 6.
The safe way to flatten a form of unknown origin is to regenerate first. The two following variants worked with no-ap.pdf and showed the company name:
// Variant A: regenerate, then flatten
form.refreshAppearances();
form.flatten();
// Variant B: flatten and ask for regeneration (list of TERMINAL fields, see next section)
form.flatten(terminals(form), true);flatten(List, boolean) and the parent-field trap
The second variant of flatten takes the list of fields to flatten and a refreshAppearances flag. It seems natural to pass it form.getFields(), but remember that those are only the roots (customer, contact, payment…), which in a hierarchical form are intermediate nodes without widgets. The result, verified:
form.flatten(form.getFields(), true); // NO!
// → the form ends up with 0 fields... but the page keeps 19 orphan widgetsThe fields disappear from the tree, but their widgets remain on the page as annotations without a field, and since they haven't been regenerated, the company name still isn't visible. The same happens if you pass a specific intermediate node: flatten(List.of(getField("terms")), true) removed the three checkboxes from the tree, but all 20 annotations stayed on the page. By contrast, passing the children (the terminal fields), the three checkboxes were flattened correctly (20 → 17 annotations) and the terms node disappeared along with them.
The rule: always pass terminal fields. RegistrationIntake includes a method to get them:
/** All fields with widgets (the "leaves" of the tree). */
static List<PDField> terminals(PDAcroForm form) {
List<PDField> list = new ArrayList<>();
for (PDField field : form.getFieldTree()) {
if (field instanceof PDTerminalField) {
list.add(field);
}
}
return list;
}Flattening only some fields
Partial flattening is useful when part of the form must be fixed and another part must stay live. For example, locking the data Nebula Distribution has validated and leaving open whatever the customer still has to complete:
List<PDField> toLock = List.of(
form.getField("customer.taxId"),
form.getField("terms.accepted"),
form.getField("terms.privacy"));
form.flatten(toLock, true);In our test, 15 fields and 17 annotations remained: the three given fields became page content and the rest stayed editable. Partial flattening can leave empty intermediate nodes in the tree (for example customer, if all its descendants are flattened): they're harmless, but don't be surprised if FormInspector shows fewer fields than you expected while getField("customer") still returns something.
The alternative: read-only fields
Instead of flattening, you can mark the fields as ReadOnly. The document is still a form, but the viewer won't let anyone change it. Which should you choose?
| Criterion | Flatten | Mark ReadOnly |
|---|---|---|
| Can it be edited in a viewer? | No: there are no fields any more | No, unless an editor removes the flag |
Can the data be extracted with getField? |
No (only by extracting text, module 6) | Yes |
| Does it look the same in every viewer? | Yes: it's fixed page content | Depends on the appearances and on each viewer |
| Is it reversible? | No | Yes: just remove the flag |
| Compatible with an existing signature? | No: it changes the page content | Yes, with an incremental save (module 7) |
| File size | Similar; the field dictionaries disappear | The same (+ incremental revision) |
| Typical use | Final archive, customer copy, printing | Document that other systems must be able to read |
Neither option is cryptographic protection: a flattened PDF can be edited with a PDF editor, just as a ReadOnly flag can be removed. What guarantees that a document hasn't changed is a digital signature (module 7).
The complete flow: RegistrationIntake
We now have all the pieces to automate the intake of registration forms. This is the flow:
flowchart TD
A["PDF received"] --> B{"Does it have a form?"}
B -->|No| R["REJECTED"]
B -->|Yes| C{"validate()<br/>(05-02)"}
C -->|Errors| R
C -->|OK| D{"Is it signed?"}
D -->|Yes| E["INCREMENTAL save:<br/>only write the registration number<br/>(no flattening, no stamp)"]
D -->|No| F["Registration number<br/>→ flatten (regenerating)<br/>→ «RECEIVED» stamp"]
F --> G["FULL save<br/>into the archive"]
E --> H["ARCHIVED_SIGNED"]
G --> I["ARCHIVED"]
The case of a signed registration form deserves an explanation. A digital signature protects the exact bytes of the document at the moment of signing. If we rewrite the file (full save) or change the page content (flattening, stamping), the signature is no longer valid. That's why, with a signed form, we make only a minimal change, filling in the registration number, and add it as an incremental revision (lesson 04-01), which leaves the original bytes untouched. Which later changes a signature allows without being considered tampered with depends on how it was signed; we'll study that in module 7.
The code, in the com.invoicelab.forms package, reuses PdfEditor and Stamper from module 4 and RegistrationFormFiller from 05-02:
package com.invoicelab.forms;
import com.invoicelab.editing.PdfEditor;
import com.invoicelab.editing.Stamper;
import com.invoicelab.pdf.Alignment;
import com.invoicelab.pdf.InvoiceLabFonts;
import com.invoicelab.pdf.Shapes;
import com.invoicelab.pdf.Measures;
import com.invoicelab.pdf.TextMetrics;
import java.awt.Color;
import java.io.IOException;
import java.nio.file.Path;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import org.apache.pdfbox.Loader;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPageContentStream.AppendMode;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.interactive.form.PDAcroForm;
import org.apache.pdfbox.pdmodel.interactive.form.PDField;
import org.apache.pdfbox.pdmodel.interactive.form.PDTerminalField;
/** Intake flow for registrations: validate → number → flatten → stamp «RECEIVED» → archive. */
public final class RegistrationIntake {
public static final String REGISTRATION_NUMBER = "internal.registrationNumber";
private static final Color RECEIVED_BLUE = new Color(0x1F, 0x3A, 0x5F);
private static final DateTimeFormatter DATE_TIME = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm");
public enum Status { ARCHIVED, ARCHIVED_SIGNED, REJECTED }
public record Result(Status status, List<String> errors, Path archivedFile) {
}
private RegistrationIntake() {
}
public static Result process(Path received, Path archiveFolder, String registrationNumber,
LocalDateTime moment) throws IOException {
// 1) Read-only inspection: is it a form? is it valid? is it signed?
boolean signed;
try (PDDocument document = Loader.loadPDF(received.toFile())) {
PDAcroForm form = document.getDocumentCatalog().getAcroForm(null);
if (form == null) {
return new Result(Status.REJECTED, List.of("The PDF doesn't contain a form"), null);
}
List<String> errors = RegistrationFormFiller.validate(form);
if (!errors.isEmpty()) {
return new Result(Status.REJECTED, errors, null);
}
signed = !document.getSignatureDictionaries().isEmpty();
}
Path target = archiveFolder.resolve(registrationNumber + ".pdf");
// 2a) Signed: any rewrite would invalidate the signature → incremental save only (module 7)
if (signed) {
PdfEditor.edit(received, target, PdfEditor.Mode.INCREMENTAL, document ->
document.getDocumentCatalog().getAcroForm(null).getField(REGISTRATION_NUMBER).setValue(registrationNumber));
return new Result(Status.ARCHIVED_SIGNED, List.of(), target);
}
// 2b) Unsigned: number, flatten and stamp, in a single full edit
PdfEditor.edit(received, target, PdfEditor.Mode.FULL, document -> {
PDAcroForm form = document.getDocumentCatalog().getAcroForm(null);
form.getField(REGISTRATION_NUMBER).setValue(registrationNumber);
form.flatten(terminals(form), true); // regenerates appearances and flattens
receivedStamp(document, registrationNumber, moment);
});
return new Result(Status.ARCHIVED, List.of(), target);
}Let's go through the process method:
- Phase 1, read-only. We open the document, check that it has a form, validate it with
RegistrationFormFiller.validateand find out whether it's signed withgetSignatureDictionaries(), which returns the existing signatures (an empty signature field, like the one in our form, doesn't count). Then we close it:PdfEditorwill open it again. It's the module 4 rule: don't edit a file you have open. - A
Resultinstead of exceptions. A rejected registration isn't a program error: it's a normal outcome that gets communicated to the customer along with its list of problems. - Signed →
INCREMENTAL: only the registration number is written. The field is ReadOnly for the viewer but, as we know, PDFBox can write to it. In our test with an unsigned form, this kind of save went from 33,542 to 34,503 bytes: the original revision stays intact and the new one is appended at the end. - Unsigned →
FULL, in a single edit: registration number, flattening with regeneration (passing the terminal fields, as we've learned) and stamp. When flattening you'll see PDFBox's warning about signature appearances in the log: it's the empty signature field, which gets flattened without drawing anything (the box is already in the page content). - Order matters: the number is written before flattening, so that it becomes part of the fixed content.
The stamp uses Stamper.stamp (lesson 04-02), which takes care of "as displayed" coordinates even if the page has a shifted CropBox or /Rotate:
/** «RECEIVED» stamp with the registration number, bottom right of the first page. */
private static void receivedStamp(PDDocument document, String registrationNumber, LocalDateTime moment)
throws IOException {
InvoiceLabFonts fonts = new InvoiceLabFonts(document);
PDFont bold = fonts.bold();
PDFont regular = fonts.regular();
String detail = registrationNumber + " · " + DATE_TIME.format(moment);
new Stamper(document).stamp(document.getPage(0), AppendMode.APPEND, (cs, visible) -> {
float width = Measures.mm(62);
float height = Measures.mm(17);
float x = visible.getWidth() - Measures.mm(18) - width;
float y = Measures.mm(16);
Shapes.drawBox(cs, x, y, width, height, Measures.mm(2), null, RECEIVED_BLUE, 1.8f);
cs.setNonStrokingColor(RECEIVED_BLUE);
TextMetrics.writeAligned(cs, bold, 18, "RECEIVED", x + width / 2, y + Measures.mm(7.5f),
Alignment.CENTER);
TextMetrics.writeAligned(cs, regular, 8, detail, x + width / 2, y + Measures.mm(2.5f),
Alignment.CENTER);
});
}
}The lambda receives the content stream already positioned and the visible size of the page; we draw a rounded box and two centred lines in the free area at the bottom right, below the reserved section. The fonts are loaded after flattening, in the same document, as the InvoiceLabFonts rule requires (one instance per document).
Finally, ProcessRegistrations empties the "inbox" of received registrations and numbers the accepted ones:
public static void main(String[] args) throws IOException {
Path archive = Files.createDirectories(Path.of("output/registration-archive"));
int next = 1;
try (DirectoryStream<Path> inbox = Files.newDirectoryStream(Path.of("output/registrations"), "registration-*.pdf")) {
for (Path received : inbox) {
String number = String.format("ALTA-2026-%04d", next);
RegistrationIntake.Result r = RegistrationIntake.process(received, archive, number,
LocalDateTime.of(2026, 11, 27, 10, 15));
System.out.println(received.getFileName() + " → " + r.status()
+ (r.archivedFile() != null ? " " + r.archivedFile() : ""));
r.errors().forEach(e -> System.out.println(" - " + e));
if (r.archivedFile() != null) {
next++; // a number is only used up if the form is archived
}
}
}
}registration-workshops.pdf → REJECTED
- Missing required field terms.privacy
- The VAT ID 'A2222' is not in a valid format
- Direct debit requires an IBAN
registration-hardware.pdf → ARCHIVED output/registration-archive/ALTA-2026-0001.pdfALTA-2026-0001.pdf is now a one-page document with no fields at all, with all the hardware store's data printed in place, the registration number in the reserved area and the stamp "RECEIVED · ALTA-2026-0001 · 27/11/2026 10:15" in the bottom right corner. The sequential number and the fixed date are a simplification for the example: in production they would come from a database and the system clock.
Common Mistakes and Tips
- Flattening without regenerating a form of unknown origin. If the appearances are missing or outdated, the value is lost for good. Use
flatten(terminals, true)or callrefreshAppearances()first. - Passing parent fields to
flatten(List, boolean). It leaves orphan widgets on the page. Always pass terminal fields. - Flattening before reading. Afterwards there are no fields left: extract the data first.
- Flattening or stamping a signed document. It invalidates the signature. Detect signatures with
getSignatureDictionaries()and limit changes to an incremental save. - Relying on
NeedAppearancesfor the documents InvoiceLab generates. Not all viewers honour it; generate the appearances. - Thinking that flattening or ReadOnly protects the document. Only a digital signature guarantees that it hasn't been modified.
- Tip: store the values you read (
RegistrationFormFiller.read) in a database as well as the flattened PDF. The PDF is the proof; the database is the data source for every other process. That way you'll never have to extract text from your own archive.
Exercises
Exercise 1. Nebula Distribution wants to send the customer a copy of their registration with all the data locked, but with the signature still pending. Write flattenExcept(PDAcroForm form, Set<String> keep) that flattens every terminal field except the given ones, and use it with Set.of("signature.customer") on registration-hardware.pdf. Check which fields remain in the tree.
Exercise 2. Write int lock(PDAcroForm form), which marks as ReadOnly every terminal field that isn't already, and returns how many it changed. Apply it to registration-hardware.pdf with PdfEditor in incremental mode and compare the size with the original.
Exercise 3. Complete the archive: after processing a registration, add the document metadata to ALTA-2026-0001.pdf (title "Customer registration ALTA-2026-0001", author = the customer's company name, InvoiceLab creator and producer, custom keys RegistrationNumber and CustomerVatId, synced XMP and language en-GB), reusing what you learned in lesson 04-06.
Solutions
Solution 1.
static void flattenExcept(PDAcroForm form, Set<String> keep) throws IOException {
List<PDField> toFlatten = new ArrayList<>();
for (PDField field : form.getFieldTree()) {
if (field instanceof PDTerminalField && !keep.contains(field.getFullyQualifiedName())) {
toFlatten.add(field);
}
}
form.flatten(toFlatten, true);
}
PdfEditor.edit(Path.of("output/registrations/registration-hardware.pdf"), Path.of("output/registration-hardware-to-sign.pdf"),
PdfEditor.Mode.FULL,
doc -> flattenExcept(doc.getDocumentCatalog().getAcroForm(null), Set.of("signature.customer")));We collect the list first and flatten afterwards: modifying the tree while walking it with getFieldTree() would give unpredictable results. When you reload the result, the tree contains customer (an empty intermediate node, as we warned), signature and signature.customer; the page has one annotation, the signature widget, and document.getSignatureFields() returns one field. The customer can open it and sign in the space provided, but can no longer change their data with an ordinary viewer. We use full mode because there's no signature to preserve yet.
Solution 2.
static int lock(PDAcroForm form) {
int changed = 0;
for (PDField field : form.getFieldTree()) {
if (field instanceof PDTerminalField && !field.isReadOnly()) {
field.setReadOnly(true);
changed++;
}
}
return changed;
}
int[] counter = new int[1];
PdfEditor.edit(Path.of("output/registrations/registration-hardware.pdf"), Path.of("output/registration-hardware-locked.pdf"),
PdfEditor.Mode.INCREMENTAL, doc -> counter[0] = lock(doc.getDocumentCatalog().getAcroForm(null)));It returns 17: the 18 terminal fields minus internal.registrationNumber, which was already read-only. The file goes from 33,544 to 38,003 bytes: the incremental revision appends the modified objects at the end, including the field dictionaries with their new /Ff. The int[] counter trick exists because a lambda can only use effectively final local variables; a one-element array is final even though its content changes. Remember that the data can still be read with getField, which is the big difference from flattening.
Solution 3.
PdfEditor.edit(Path.of("output/registration-archive/ALTA-2026-0001.pdf"),
Path.of("output/registration-archive/ALTA-2026-0001.pdf"), PdfEditor.Mode.FULL, doc -> {
PDDocumentInformation info = doc.getDocumentInformation();
info.setTitle("Customer registration ALTA-2026-0001");
info.setAuthor("Example Hardware Co.");
info.setCreator(Metadata.CREATOR);
info.setProducer(Metadata.PRODUCER);
info.setCustomMetadataValue("RegistrationNumber", "ALTA-2026-0001");
info.setCustomMetadataValue("CustomerVatId", "J00000000");
Metadata.syncXmp(doc); // Info is the source of truth (04-06)
doc.getDocumentCatalog().setLanguage("en-GB");
});Source and target are the same: PdfEditor allows it thanks to the temporary file and the rename. When you reload it, the title and CustomerVatId are read correctly and Metadata.readXmp returns the XMP metadata. In RegistrationIntake the natural thing would be to do this inside the same edit in which the document is flattened and stamped (with the data from RegistrationFormFiller.read, read before flattening), so the file is written only once. With the metadata in place, Nebula's document management system will be able to find the registration by the customer's VAT ID without opening it.
Conclusion
With this lesson you complete module 5. You know that value and appearance are independent pieces of data that must be kept in sync, you know the structure of /AP (/N, /D, /R and the /AS state), why a value might not be visible (missing appearances, NeedAppearances in viewers that don't honour it, inconsistent states, fonts without the glyphs) and how far PDFBox's appearance generator goes. You've learned to flatten forms fully or partially, to avoid the parent-field trap in flatten(List, boolean), to choose between flattening and marking fields ReadOnly, and to respect signed documents by using incremental saves. Throughout the module you've built the com.invoicelab.forms package: FormInspector for getting to know any form, RegistrationRequest and RegistrationFormFiller for reading, validating and filling it in, PdfFields and GenerateRegistrationForm for creating it, and RegistrationIntake to close the loop: validate, number, flatten, stamp and archive.
Forms are the convenient way to receive structured data in PDF, but most of the PDFs that reach a company have no fields: supplier invoices, for example, arrive as ordinary documents in which the number, the date and the total are simply text drawn on the page. In module 6 we'll learn to extract text and information from any PDF, starting with PDFTextStripper, so that InvoiceLab can read those supplier invoices and locate the data it needs in them.
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
