In the previous lesson we took an inventory of Nebula Distribution's customer registration form: we know what each field is called (customer.taxId, payment.method, terms.privacy…), what type it is and where it sits. Now we're going to use that knowledge in both directions. Filling in: the sales department wants to send newly acquired customers the registration form already prefilled with the details it knows, so that all they have to do is review it, tick the boxes and sign. Reading: when the form comes back, InvoiceLab has to extract its data, check that it's complete and well formed, and turn it into a model Customer. Along the way we'll run into the quirks of each field type, a classic font problem (the customer called Dvořák) and the difference between generating appearances and leaving it to the viewer. All the mapping will live in the RegistrationFormFiller class.
Contents
- The basic flow: load, locate, assign and save
- Locating fields safely
- Filling in each field type
- The
RegistrationRequestmodel and theRegistrationFormFillerclass - Reading a received registration and turning it into a
Customer - Validating the received data
- Characters the form's font doesn't support
- Appearances:
setValue,refreshAppearancesandNeedAppearances - Batch filling: a hundred prefilled forms
- Exchanging data without the PDF: FDF and XFDF
The basic flow: load, locate, assign and save
Filling in a form with PDFBox always follows the same pattern:
try (PDDocument document = Loader.loadPDF(new File("output/registration-form.pdf"))) {
PDAcroForm form = document.getDocumentCatalog().getAcroForm(null); // 1) the form
PDField field = form.getField("customer.companyName"); // 2) the field
field.setValue("Example Hardware Co."); // 3) the value
document.save(new File("output/registrations/test.pdf")); // 4) save
}- Get the
PDAcroFormfrom the catalog (without automatic fixups, as we saw in 05-01). - Locate the field by its fully qualified name.
- Assign the value with
setValue(String). This method does two things: it stores the value in/Vand, for text fields and lists, it generates the widget's appearance using the/DAfont, so the value is visible in any viewer. - Save. As always, to a file other than the source (or using the temporary-file technique from
PdfEditor, lesson 04-01).
Locating fields safely
getField returns null if the name doesn't exist, and otherwise a generic PDField that you have to cast to the specific type. If the form changes (someone renames a field or turns a checkbox into a drop-down), the code will fail far from the source of the problem with a NullPointerException or a ClassCastException. That's why RegistrationFormFiller centralises access in a method that checks both things and gives a clear message:
/** Looks up a field by its full name and checks its type: fails with a clear message if it doesn't match. */
static <T extends PDField> T field(PDAcroForm form, String name, Class<T> type) {
PDField field = form.getField(name);
if (field == null) {
throw new IllegalStateException("The form has no field " + name);
}
if (!type.isInstance(field)) {
throw new IllegalStateException("Field " + name + " is " + field.getClass().getSimpleName()
+ " but " + type.getSimpleName() + " was expected");
}
return type.cast(field);
}<T extends PDField>makes it a generic method: it returns exactly the type you ask for.type.isInstance(field)is equivalent tofield instanceof T, which Java doesn't let you write with a generic type.type.cast(field)performs the cast without compiler warnings.
Usage: PDCheckBox checkbox = field(form, "terms.privacy", PDCheckBox.class);.
Filling in each field type
Every field has setValue(String), but the meaning of the text changes with the type. These are the behaviours we've verified with PDFBox 3.0.8 on the registration form:
| Type | What you pass to setValue |
Specific methods | What happens with a wrong value |
|---|---|---|---|
PDTextField |
The text | setMultiline, getMaxLen, isComb |
Almost anything is accepted (see below) |
PDCheckBox |
The PDF's on state or Off |
check(), unCheck(), isChecked(), getOnValue() |
IllegalArgumentException |
PDRadioButton |
The on state of one of its widgets, or Off |
getOnValues(), getSelectedIndex() |
IllegalArgumentException |
PDComboBox |
The option's export value | getOptionsExportValues(), getOptionsDisplayValues() |
Accepted without checking |
PDListBox |
Same as the combo box; accepts several via setValue(List<String>) if it's multi-select |
setMultiSelect, getSelectedOptionsIndex() |
— |
Text fields
PDTextField company = field(form, "customer.companyName", PDTextField.class);
company.setValue("Example Hardware Co.");
PDTextField notes = field(form, "notes", PDTextField.class);
notes.setValue("Morning deliveries only.\nLoading dock at the rear."); // multiline: \nThere are three surprises worth knowing about:
MaxLenisn't enforced on the value. We assigned"5000123"to the postal code (MaxLen5, comb) and PDFBox stored all seven characters in/V; the comb appearance, however, only drew the first five boxes. What you see and what you read when extracting don't match: validate the length yourself.- ReadOnly doesn't protect against PDFBox.
internal.registrationNumberis read-only, andsetValue("ALTA-1")works without complaint. ReadOnly prevents writing in the viewer, not in your program (we'll take advantage of this in 05-04 to number the registrations). - In a single-line field, line breaks aren't drawn as new lines: if the text might contain them, use a multiline field or strip them first.
Checkboxes
The value of a ticked checkbox isn't "true", and it isn't necessarily "Yes": it's the name of the on state chosen by whoever designed the form. In our registration form it happens to be Yes; in other forms you'll see On, 1, X or even Si. If you guess wrong, PDFBox rejects it:
java.lang.IllegalArgumentException: value 'On' is not a valid option for the field
terms.accepted, valid values are: [Yes] and OffThe robust solution is not to write the value by hand:
PDCheckBox privacy = field(form, "terms.privacy", PDCheckBox.class);
System.out.println(privacy.getOnValue()); // "Yes": the on state of THIS form
privacy.check(); // ticks it using that value, whatever it is
privacy.unCheck(); // equivalent to setValue("Off")
boolean ticked = privacy.isChecked();Radio buttons
A radio group is one field with several widgets, and each widget has its own on state. getOnValues() returns all of them:
PDRadioButton method = field(form, "payment.method", PDRadioButton.class);
System.out.println(method.getOnValues()); // [Transfer, DirectDebit, PromissoryNote]
method.setValue("PromissoryNote");
System.out.println(method.getValue()); // PromissoryNote
System.out.println(method.getSelectedIndex()); // 2 (position of the chosen widget)When you assign PromissoryNote, PDFBox sets /V /PromissoryNote on the field and adjusts the /AS state of every widget: PromissoryNote on the third and Off on the other two. That way the viewer shows only one selected button. Notice that the values contain no spaces or accents (DirectDebit, PromissoryNote): they're PDF names, and form designers usually avoid special characters in them; what the user sees is the label printed next to each button.
Drop-down lists: export and display values
An option in a PDComboBox can have two texts: the display text (what the user sees: "Zaragoza") and the export value (what's stored in /V: "50", the province code). In our registration form:
PDComboBox province = field(form, "customer.address.province", PDComboBox.class);
province.getOptionsExportValues(); // [08, 22, 26, 25, 28, 31, 42, 43, 44, 46, 50]
province.getOptionsDisplayValues(); // [Barcelona, Huesca, La Rioja, Lleida, Madrid, ...]
province.setValue("50"); // pass the EXPORT value
province.getValue(); // [50] ← a listWhen generating the appearance, PDFBox draws the display text ("Zaragoza"), which is what the user expects. However, in PDFBox 3.0.8 a combo box's setValue doesn't check that the value is one of the options. We tried setValue("Zaragoza") (the display text instead of the code) and even setValue("Atlantis"), and both were accepted without error. That's why RegistrationFormFiller validates against getOptionsExportValues() before assigning.
The RegistrationRequest model and the RegistrationFormFiller class
We now know the pieces; let's organise them. The model's Customer (lesson 03-01) has a company name, VAT ID, address, postal code, city and email. The registration form contains more (province, contact, payment method, consents), so we create a record in the com.invoicelab.forms package that wraps the Customer:
package com.invoicelab.forms;
import com.invoicelab.model.Customer;
/** What a registration form contains: the InvoiceLab Customer plus the registration-specific data. */
public record RegistrationRequest(Customer customer, String provinceCode, String contactPerson, String phone,
PaymentMethod paymentMethod, String iban, boolean acceptsTerms,
boolean acceptsPrivacy, boolean acceptsMarketing, String notes) {
/** Payment methods, with the exact value used by the PDF form (name of the radio's "on" state). */
public enum PaymentMethod {
TRANSFER("Transfer"), DIRECT_DEBIT("DirectDebit"), PROMISSORY_NOTE("PromissoryNote");
private final String pdfValue;
PaymentMethod(String pdfValue) {
this.pdfValue = pdfValue;
}
public String pdfValue() {
return pdfValue;
}
/** Translates the value read from the PDF; null if no option was selected ("Off"). */
public static PaymentMethod fromPdfValue(String value) {
for (PaymentMethod method : values()) {
if (method.pdfValue.equals(value)) {
return method;
}
}
return null;
}
}
}The enum shields the rest of InvoiceLab from the PDF's internal names: business code works with PaymentMethod.DIRECT_DEBIT, and only the enum knows that in the form it's called DirectDebit.
RegistrationFormFiller starts by declaring the field names as constants. They're the contract with the form: if a version with different names is published tomorrow, this is the only place you have to touch.
package com.invoicelab.forms;
import com.invoicelab.forms.RegistrationRequest.PaymentMethod;
import com.invoicelab.model.Customer;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;
import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDResources;
import org.apache.pdfbox.pdmodel.font.PDType0Font;
import org.apache.pdfbox.pdmodel.interactive.form.PDAcroForm;
import org.apache.pdfbox.pdmodel.interactive.form.PDCheckBox;
import org.apache.pdfbox.pdmodel.interactive.form.PDComboBox;
import org.apache.pdfbox.pdmodel.interactive.form.PDField;
import org.apache.pdfbox.pdmodel.interactive.form.PDNonTerminalField;
import org.apache.pdfbox.pdmodel.interactive.form.PDRadioButton;
import org.apache.pdfbox.pdmodel.interactive.form.PDTextField;
import org.apache.pdfbox.pdmodel.interactive.form.PDVariableText;
/** Mapping between the RegistrationRequest model and the fields of the registration form PDF. */
public final class RegistrationFormFiller {
// Fully qualified names: they're the "contract" with the PDF form
public static final String COMPANY_NAME = "customer.companyName";
public static final String TAX_ID = "customer.taxId";
public static final String STREET = "customer.address.street";
public static final String POSTAL_CODE = "customer.address.postalCode";
public static final String CITY = "customer.address.city";
public static final String PROVINCE = "customer.address.province";
public static final String CONTACT = "contact.name";
public static final String PHONE = "contact.phone";
public static final String EMAIL = "contact.email";
public static final String PAYMENT_METHOD = "payment.method";
public static final String IBAN = "payment.iban";
public static final String NOTES = "notes";
public static final String TERMS = "terms.accepted";
public static final String PRIVACY = "terms.privacy";
public static final String MARKETING = "terms.marketing";
/** Spanish tax ID of an individual (DNI/NIE) or an entity. Only checks the format, not the check character. */
private static final Pattern TAX_ID_FORMAT =
Pattern.compile("[0-9XYZ][0-9]{7}[A-Z]|[ABCDEFGHJNPQRSUVW][0-9]{7}[0-9A-J]");
private RegistrationFormFiller() {
}The writing part maps each piece of model data to its field:
/** Writes the request into the form. Null values leave the field as it is. */
public static void fill(PDAcroForm form, RegistrationRequest r) throws IOException {
Customer c = r.customer();
text(form, COMPANY_NAME, c.companyName());
text(form, TAX_ID, c.taxId());
text(form, STREET, c.address());
text(form, POSTAL_CODE, c.postalCode());
text(form, CITY, c.city());
text(form, EMAIL, c.email());
text(form, CONTACT, r.contactPerson());
text(form, PHONE, r.phone());
text(form, IBAN, r.iban());
text(form, NOTES, r.notes());
if (r.provinceCode() != null) {
PDComboBox province = field(form, PROVINCE, PDComboBox.class);
// PDFBox doesn't check that the value is one of the combo's options: we do it ourselves
if (!province.getOptionsExportValues().contains(r.provinceCode())) {
throw new IllegalArgumentException("Unknown province code: " + r.provinceCode());
}
province.setValue(r.provinceCode()); // the EXPORT value is stored ("22")
}
if (r.paymentMethod() != null) {
field(form, PAYMENT_METHOD, PDRadioButton.class).setValue(r.paymentMethod().pdfValue());
}
checkbox(form, TERMS, r.acceptsTerms());
checkbox(form, PRIVACY, r.acceptsPrivacy());
checkbox(form, MARKETING, r.acceptsMarketing());
}
private static void text(PDAcroForm form, String name, String value) throws IOException {
if (value != null) {
field(form, name, PDTextField.class).setValue(value);
}
}
private static void checkbox(PDAcroForm form, String name, boolean ticked) throws IOException {
PDCheckBox checkbox = field(form, name, PDCheckBox.class);
if (ticked) {
checkbox.check(); // uses the PDF's own "on" value (here "Yes"), whatever it is
} else {
checkbox.unCheck(); // "Off"
}
}nullvalues don't clear anything: that way you can prefill just part of the form (we'll use this in the batch).- The
field(...)method from the previous section completes the class (it goes at the end of the file).
A test program, com.invoicelab.examples.FillRegistrationForm, simulates two customers sending back the form: Example Hardware, with everything correct, and Test Workshops, with several errors (an incomplete VAT ID, the privacy box unticked, direct debit without an IBAN) and a contact person with special characters:
public static void main(String[] args) throws IOException {
Path template = Path.of("output/registration-form.pdf");
Path folder = Files.createDirectories(Path.of("output/registrations"));
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.\nLoading dock at the rear.");
save(template, hardware, false, folder.resolve("registration-hardware.pdf"));
RegistrationRequest workshops = new RegistrationRequest(
new Customer("Test Workshops Inc.", "A2222", "3 Invented Street", "44001", "Teruel",
"[email protected]"),
"44", "Tomáš Dvořák", null, PaymentMethod.DIRECT_DEBIT, null,
true, false, true, null);
save(template, workshops, true, folder.resolve("registration-workshops.pdf"));
}
static void save(Path template, RegistrationRequest registration, boolean unicode, Path target) throws IOException {
try (PDDocument document = Loader.loadPDF(template.toFile())) {
PDAcroForm form = document.getDocumentCatalog().getAcroForm(null);
if (unicode) {
RegistrationFormFiller.useUnicodeFont(document, form); // section 7
}
RegistrationFormFiller.fill(form, registration);
document.save(target.toFile());
}
System.out.printf("%-48s %,d bytes%n", target, Files.size(target));
}output/registrations/registration-hardware.pdf 33,544 bytes
output/registrations/registration-workshops.pdf 426,892 bytesThere's a reason for the difference in size, and we'll see it in section 7.
Reading a received registration and turning it into a Customer
Reading is the reverse path. getValueAsString() works with any field and is the most convenient way to get the text; for checkboxes, radio buttons and lists we use their specific methods:
/** Reads a received registration. It doesn't validate: that's what validate() is for. */
public static RegistrationRequest read(PDAcroForm form) {
Customer customer = new Customer(
value(form, COMPANY_NAME), value(form, TAX_ID).toUpperCase(),
value(form, STREET), value(form, POSTAL_CODE), value(form, CITY),
emptyToNull(value(form, EMAIL)));
PDComboBox province = field(form, PROVINCE, PDComboBox.class);
String code = province.getValue().isEmpty() ? null : province.getValue().get(0);
String method = field(form, PAYMENT_METHOD, PDRadioButton.class).getValue(); // "Off" if none
return new RegistrationRequest(customer, code,
emptyToNull(value(form, CONTACT)), emptyToNull(value(form, PHONE)),
PaymentMethod.fromPdfValue(method), emptyToNull(value(form, IBAN)),
field(form, TERMS, PDCheckBox.class).isChecked(),
field(form, PRIVACY, PDCheckBox.class).isChecked(),
field(form, MARKETING, PDCheckBox.class).isChecked(),
emptyToNull(value(form, NOTES)));
}
/** A field's value as text, with surrounding whitespace removed ("" if it's empty). */
private static String value(PDAcroForm form, String name) {
return field(form, name, PDField.class).getValueAsString().strip();
}
private static String emptyToNull(String text) {
return text.isEmpty() ? null : text;
}strip(): users very often leave spaces at the beginning or end.toUpperCase()on the VAT ID: "j00000000" and "J00000000" must be treated the same.- The combo box's
getValue()returns a list: empty if nothing was chosen, or containing the export value ("22"). - The radio group returns
"Off"if no option was selected;PaymentMethod.fromPdfValueturns it intonull. readdoesn't validate: if the company name is missing, theCustomerconstructor will receive an empty string (notnull), so it won't fail. That's why you have to validate before reading.
Validating the received data
A form that comes back from a customer may be incomplete or filled in incorrectly: Required flags are only checked by the viewer if the form has a submit button, and in a PDF that's saved and attached to an email nobody checks them. Validation has two parts:
/** Returns the list of problems found (empty if the registration is correct). */
public static List<String> validate(PDAcroForm form) {
List<String> errors = new ArrayList<>();
// 1) Generic rule: every field marked as Required must have a value
for (PDField field : form.getFieldTree()) {
if (field instanceof PDNonTerminalField || !field.isRequired()) {
continue;
}
String value = field.getValueAsString().strip();
if (value.isEmpty() || value.equals("Off") || value.equals("[]")) {
errors.add("Missing required field " + field.getFullyQualifiedName());
}
}
// 2) Business-specific rules
String taxId = value(form, TAX_ID).toUpperCase();
if (!taxId.isEmpty() && !TAX_ID_FORMAT.matcher(taxId).matches()) {
errors.add("The VAT ID '" + taxId + "' is not in a valid format");
}
String postalCode = value(form, POSTAL_CODE);
if (!postalCode.isEmpty() && !postalCode.matches("[0-9]{5}")) {
errors.add("The postal code '" + postalCode + "' must have 5 digits");
}
PDComboBox province = field(form, PROVINCE, PDComboBox.class);
if (!province.getValue().isEmpty()
&& !province.getOptionsExportValues().contains(province.getValue().get(0))) {
errors.add("Unknown province: " + province.getValue().get(0));
}
String method = field(form, PAYMENT_METHOD, PDRadioButton.class).getValue();
if (PaymentMethod.fromPdfValue(method) == PaymentMethod.DIRECT_DEBIT && value(form, IBAN).isEmpty()) {
errors.add("Direct debit requires an IBAN");
}
return errors;
}- Generic rule: walks the tree and, for each terminal field with Required set, treats as empty an empty text, the
Offof checkboxes and radio groups, and the[]of a list with nothing selected. It's independent of this particular form: if a required field is added tomorrow, it gets validated without touching the code. - Business rules: what the form can't express. The
TAX_ID_FORMATregular expression accepts a DNI (8 digits + letter), an NIE (X, Y or Z + 7 digits + letter) or an entity tax ID (entity-type letter + 7 digits + check character); these are the Spanish formats, since the customers are Spanish companies. It only checks the format; calculating the check digit is left as an exercise. We also check the length of the postal code (remember thatMaxLendoesn't guarantee it), that the province is a valid option, and a conditional rule: direct debit requires an IBAN.
Returning a list of errors rather than throwing an exception on the first one lets you reply to the customer with all the problems at once. The ReadReceivedRegistrations program walks the folder, validates and, if everything is correct, builds the customer:
try (DirectoryStream<Path> pdfs = Files.newDirectoryStream(Path.of("output/registrations"), "registration-*.pdf")) {
for (Path pdf : pdfs) {
try (PDDocument document = Loader.loadPDF(pdf.toFile())) {
PDAcroForm form = document.getDocumentCatalog().getAcroForm(null);
if (form == null) {
System.out.println(pdf.getFileName() + ": not a form");
continue;
}
List<String> errors = RegistrationFormFiller.validate(form);
System.out.println("== " + pdf.getFileName() + (errors.isEmpty() ? ": ACCEPTED" : ": REJECTED"));
errors.forEach(e -> System.out.println(" - " + e));
if (errors.isEmpty()) {
RegistrationRequest registration = RegistrationFormFiller.read(form);
System.out.println(" " + registration.customer());
System.out.println(" Province " + registration.provinceCode() + ", payment " + registration.paymentMethod()
+ ", marketing: " + (registration.acceptsMarketing() ? "yes" : "no"));
}
}
}
}== 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: ACCEPTED
Customer[companyName=Example Hardware Co., taxId=J00000000, address=45 Test Avenue, Unit 2, postalCode=22001, city=Huesca, [email protected]]
Province 22, payment TRANSFER, marketing: noAbout consents: the terms, data protection and marketing communications checkboxes have legal consequences. The wording in our form consists of fictional examples for the course. In a real form, the wording of the data protection notice (GDPR), the separation between mandatory and optional consents and the way they're kept as evidence must be reviewed by a professional (legal counsel or a data protection officer). What is the program's responsibility is never to treat something as accepted when it isn't: that's why
acceptsMarketingis read from its own checkbox and never inferred from the others.
Characters the form's font doesn't support
If we try to put "Tomáš Dvořák" into the original form, PDFBox throws:
java.lang.IllegalArgumentException: U+0159 ('rcaron') is not available in the font Helvetica,
encoding: WinAnsiEncodingThe cause is in /DA: the field uses /Helv, a standard font with WinAnsi encoding, which covers the characters of Spanish and almost all of Western Europe (á, ñ, ü, €…) but not the Czech ř, the Polish ł or, of course, non-Latin alphabets (lesson 02-02). Since setValue generates the appearance with that font, it fails. What's more, the exception leaves the appearance stream half-written and PDFBox logs a warning along the lines of "You did not call endText()": if you see that warning while filling in forms, look for an encoding exception nearby.
The solution is to give the form a Unicode font: add a PDType0Font to /DR and change the fields' /DA so they use it. It's the last method in RegistrationFormFiller:
/**
* Adds the FULL DejaVu Sans font to /DR and makes every text field and list use it,
* so that characters Helvetica (WinAnsi) lacks can be written. Call BEFORE setValue.
*/
public static void useUnicodeFont(PDDocument document, PDAcroForm form) throws IOException {
PDType0Font dejaVu;
try (InputStream in = RegistrationFormFiller.class.getResourceAsStream("/fonts/DejaVuSans.ttf")) {
dejaVu = PDType0Font.load(document, in, false); // false: no subsetting (see explanation)
}
PDResources dr = form.getDefaultResources();
if (dr == null) {
dr = new PDResources();
form.setDefaultResources(dr);
}
COSName name = COSName.getPDFName("DejaVu");
dr.put(name, dejaVu);
for (PDField field : form.getFieldTree()) {
if (field instanceof PDVariableText text) {
// Keeps the original DA size (e.g. "/Helv 10 Tf 0 g" → "/DejaVu 10 Tf 0 g")
String da = text.getDefaultAppearance();
text.setDefaultAppearance(da.replaceFirst("/\\S+\\s+", "/" + name.getName() + " "));
}
}
}Step by step:
PDType0Font.load(document, in, false): we load DejaVu Sans, the same font as in module 2, but this time without subsetting (false). We don't useInvoiceLabFonts.regular()precisely because that class embeds subsets.dr.put(name, dejaVu): we register it in/DRunder a name of our choosing,/DejaVu.- The loop: we change the
/DAof everyPDVariableText(text fields and lists).getDefaultAppearance()returns the effective/DA, including the one inherited from the form. The regular expression replaces only the font name (the first/Somethingfollowed by whitespace) and keeps the size and colour. - It must be called before
setValue, becausesetValueis where the appearance is generated.
Why no subsetting? With a subset, the embedded font only contains the glyphs used at save time. If the form is going to stay live (the customer will open it and type into it), their viewer needs glyphs for any character they type, and a subset doesn't guarantee them: depending on the viewer, it will substitute the font or show gaps. The price of the full font is size: 426,892 bytes versus 33,544 for the form with Helvetica. In a test with subsetting, the same form took up 41,511 bytes. Rule of thumb:
| Situation | Font in /DR |
|---|---|
| Only WinAnsi characters (Spanish, Catalan, English…) | Keep the form's Helvetica |
| The form is filled in and then flattened (05-04) | Subset: nobody will type into it again |
| The prefilled form is sent out for others to complete | Full font |
A good compromise is to detect whether the data actually needs Unicode and only then change the font (exercise 2).
Appearances: setValue, refreshAppearances and NeedAppearances
We already know that setValue generates the appearance of text fields and lists, and that checkboxes and radio buttons simply switch state (/AS) between appearances that are already drawn. When do you need anything else?
| Tool | What it does | When to use it |
|---|---|---|
field.setValue(...) |
Stores /V and regenerates the appearance of that field |
Whenever you fill in: it's the normal case |
form.refreshAppearances() |
Regenerates the appearances of all text fields and lists | If you changed /DA, /DR or /V by other means (direct COS access, import) |
form.refreshAppearances(list) |
The same, only for the given fields | To exclude fields PDFBox can't draw |
form.setNeedAppearances(true) |
Draws nothing: asks the viewer to regenerate on opening | Last resort, when PDFBox can't produce an acceptable appearance |
Some observations we've verified:
refreshAppearances()on the whole form also attempts the signature field and logs the warning "Appearance generation for signature fields not implemented here": PDFBox doesn't draw signatures (that's for module 7). For a form with a signature, use the list variant and pass only thePDVariableTextfields.NeedAppearancesdelegates to the viewer, but not every viewer honours it: PDFBox's renderer, for example, ignores the flag and draws the stored appearance; if there isn't one, the field comes out empty even though it has a value. On top of that, Acrobat regenerates on opening and then asks to save changes on closing.- Remember that
getAcroForm()(withoutnull) regenerates appearances and turns offNeedAppearancesautomatically (05-01). It's convenient, but it should be a conscious decision.
The recommendation for InvoiceLab is simple: always fill in with setValue and leave NeedAppearances set to false. That way the result looks the same in any viewer, including PDFBox itself when we convert pages to images in module 6. In lesson 05-04 we'll go deeper into appearances.
Batch filling: a hundred prefilled forms
The sales department has a list of companies it met at a trade fair and wants to send them the registration form with their details already filled in. BatchRegistrations generates a hundred forms (with fictional customers):
public static void main(String[] args) throws IOException {
byte[] template = Files.readAllBytes(Path.of("output/registration-form.pdf")); // read ONCE
Path folder = Files.createDirectories(Path.of("output/prefilled"));
long start = System.nanoTime();
int generated = 0;
for (Customer customer : fictionalCustomers(100)) {
RegistrationRequest data = new RegistrationRequest(customer, "50", null, null, null, null,
false, false, false, null); // the customer ticks the boxes
try (PDDocument document = Loader.loadPDF(template)) { // a NEW document per customer
PDAcroForm form = document.getDocumentCatalog().getAcroForm(null);
RegistrationFormFiller.fill(form, data);
form.getField(RegistrationFormFiller.TAX_ID).setReadOnly(true); // the VAT ID is locked
document.save(folder.resolve("registration-" + customer.taxId() + ".pdf").toFile());
generated++;
}
}
System.out.printf("%d forms in %d ms%n", generated, (System.nanoTime() - start) / 1_000_000);
}
static List<Customer> fictionalCustomers(int count) {
List<Customer> customers = new ArrayList<>();
for (int i = 1; i <= count; i++) {
customers.add(new Customer(String.format("Fictional Customer %03d Ltd.", i),
String.format("B%08d", i), i + " Test Street", "50001", "Zaragoza", null));
}
return customers;
}The key points:
- The template is read once into a
byte[]and loaded withLoader.loadPDF(byte[])on each iteration. Reading from disk a hundred times would be slower, and reusing the samePDDocumentis impossible: once filled in, it's no longer blank. - A new document per customer, closed in its own
try: memory doesn't grow with the number of forms. - The checkboxes are left unticked (
false): consent must be given by the customer, never by the program. setReadOnly(true)on the VAT ID: the customer won't be able to change it in their viewer. It's a convenience, not a guarantee (any PDF editor can remove the flag), so we'll still validate when the registration comes back.
On our machine: 100 forms in 820 ms, about 33 KB each. The time will depend on your hardware; what matters is that it grows linearly and memory stays stable. For batches of thousands of documents we'll talk about memory and parallelism in module 8.
Exchanging data without the PDF: FDF and XFDF
Sometimes you don't want to move the whole PDF around, but only the data: to save a draft, to send the answers to another system or to fill in several versions of the same form. Two formats exist for this:
- FDF (Forms Data Format): PDF syntax, mixed binary/text, very compact.
- XFDF: the XML version of FDF, readable and easy to process with any tool.
PDFBox handles them with FDFDocument. XfdfExchange exports the data from the hardware store's registration and imports it into a blank form:
Path xfdf = Path.of("output/registrations/hardware.xfdf");
// 1) Export: only the data, no pages or fonts
try (PDDocument registration = Loader.loadPDF(Path.of("output/registrations/registration-hardware.pdf").toFile());
FDFDocument fdf = registration.getDocumentCatalog().getAcroForm(null).exportFDF()) {
fdf.saveXFDF(xfdf.toFile()); // or fdf.save(...) for FDF
}
// 2) Import into a blank template
try (PDDocument blank = Loader.loadPDF(Path.of("output/registration-form.pdf").toFile());
FDFDocument fdf = Loader.loadXFDF(xfdf.toFile())) { // or Loader.loadFDF(...)
PDAcroForm form = blank.getDocumentCatalog().getAcroForm(null);
form.importFDF(fdf);
blank.save("output/registrations/imported-xfdf.pdf");
}A fragment of the generated XFDF shows that the name hierarchy is preserved as nested elements:
<field name="customer">
<field name="companyName">
<value>Example Hardware Co.</value>
</field>
<field name="taxId">
<value>J00000000</value>
</field>
...
</field>Two details we've verified: importFDF fills in the values and generates their appearances, and exportFDF also includes fields marked NoExport (internal.registrationNumber shows up). The NoExport flag is honoured by viewers when they run a submit action, not by this PDFBox export; if a field mustn't go out, remove it from the result yourself.
Common Mistakes and Tips
- Guessing a checkbox's value. It isn't
"Yes"by rule: usecheck()/unCheck()or look it up withgetOnValue(). - Passing the display text to a combo box. The export value is what gets stored ("50", not "Zaragoza"). And since PDFBox doesn't check it, validate against
getOptionsExportValues(). - Relying on
MaxLen, ReadOnly or Required. None of them is enforced when you program with PDFBox. Validate lengths and required fields in your code. - Calling
useUnicodeFontaftersetValue. The appearance has already been generated with the old font (or has failed). Font first, values second. - Using subsets in forms that others will fill in. Embed the full font, or check first whether Unicode is needed.
- Turning on
NeedAppearances"just in case". It delegates to the viewer, and not all of them honour it. Generate the appearances withsetValue. - Reusing the same
PDDocumentin a batch. Load the template again (from abyte[]) for each form. - Saving over the source file. PDFBox warns you with "You are overwriting the existing file…"; use a different target or
PdfEditor. - Tip: validate before reading.
readbuilds the model from whatever is there;validateis what decides whether the registration is accepted.
Exercises
Exercise 1. The TAX_ID_FORMAT pattern doesn't check the control letter. Write boolean isDniLetterValid(String taxId) which, for a DNI or NIE (8 numeric characters after replacing X, Y, Z with 0, 1, 2), computes the letter from the remainder of dividing by 23, using the table TRWAGMYFPDXBNJZSQVHLCKE. For an entity tax ID it must return true (the rule doesn't apply). Test it with 12345678Z (correct), 12345678A (incorrect) and X0000000T (correct).
Exercise 2. Write boolean needsUnicode(RegistrationRequest registration) that returns true if any text in the request can't be represented with Helvetica, so that you only call useUnicodeFont when it's needed. Hint: InvoiceLabFonts.canRender(PDFont, String) from module 2 and new PDType1Font(Standard14Fonts.FontName.HELVETICA).
Exercise 3. Write int exportCsv(Path folder, Path csv) that walks through the registration-*.pdf registrations in a folder, skips those that don't validate and writes a CSV (; separator, UTF-8, quoted values) with the VAT ID, company name, postal code, city, province, payment method and email. It returns the number of rows written.
Solutions
Solution 1.
private static final String LETTERS = "TRWAGMYFPDXBNJZSQVHLCKE";
static boolean isDniLetterValid(String taxId) {
if (!taxId.matches("[0-9XYZ][0-9]{7}[A-Z]")) {
return true; // not a DNI/NIE: this rule doesn't apply
}
String number = "XYZ".indexOf(taxId.charAt(0)) >= 0
? "XYZ".indexOf(taxId.charAt(0)) + taxId.substring(1, 8) // X→0, Y→1, Z→2
: taxId.substring(0, 8);
return LETTERS.charAt(Integer.parseInt(number) % 23) == taxId.charAt(8);
}"XYZ".indexOf(c) returns 0, 1 or 2 for X, Y or Z (and -1 for a digit), which handles the NIE substitution in a single line. The three test cases give true, false and true. In validate you'd add: if (!isDniLetterValid(taxId)) errors.add("The VAT ID check letter is incorrect");. Entity tax IDs have their own, longer check algorithm; the structure would be the same.
Solution 2.
static boolean needsUnicode(RegistrationRequest registration) throws IOException {
PDFont helvetica = new PDType1Font(Standard14Fonts.FontName.HELVETICA);
Customer c = registration.customer();
for (String text : Arrays.asList(c.companyName(), c.address(), c.city(), c.email(),
registration.contactPerson(), registration.phone(), registration.notes())) {
if (text != null && !InvoiceLabFonts.canRender(helvetica, text.replace("\n", ""))) {
return true;
}
}
return false;
}We use Arrays.asList rather than List.of because List.of doesn't accept null elements, and several pieces of data are optional. We remove the \n characters because the notes are multiline and a line break isn't a character that gets drawn. For the hardware store it returns false; for Test Workshops, true (because of "Dvořák"). In FillRegistrationForm.save, the unicode parameter would be replaced by if (needsUnicode(registration)).
Solution 3.
static int exportCsv(Path folder, Path csv) throws IOException {
int rows = 0;
try (BufferedWriter out = Files.newBufferedWriter(csv, StandardCharsets.UTF_8);
DirectoryStream<Path> pdfs = Files.newDirectoryStream(folder, "registration-*.pdf")) {
out.write("tax_id;company_name;postal_code;city;province;payment_method;email\n");
for (Path pdf : pdfs) {
try (PDDocument document = Loader.loadPDF(pdf.toFile())) {
PDAcroForm form = document.getDocumentCatalog().getAcroForm(null);
if (form == null || !RegistrationFormFiller.validate(form).isEmpty()) {
continue; // not a form, or doesn't validate
}
RegistrationRequest r = RegistrationFormFiller.read(form);
List<String> fields = new ArrayList<>(List.of(r.customer().taxId(), r.customer().companyName(),
r.customer().postalCode(), r.customer().city(), r.provinceCode(),
r.paymentMethod().name(), Objects.toString(r.customer().email(), "")));
fields.replaceAll(v -> '"' + v.replace("\"", "\"\"") + '"'); // CSV escaping
out.write(String.join(";", fields) + "\n");
rows++;
}
}
}
return rows;
}With the registrations from this lesson it writes one row (the hardware store). Some details: in a valid registration the province and payment method can't be null (they're Required), but the email could be if it weren't mandatory, hence Objects.toString(..., ""); double quotes inside a value are doubled, which is the CSV escaping rule; and the registration-*.pdf filter avoids processing other PDFs in the folder, such as imported-xfdf.pdf, which would duplicate the row.
Conclusion
You now know how to fill in and read forms with PDFBox: locating fields safely by their full name, assigning values to each type (text, checkboxes with their on state, radio buttons with getOnValues, combo boxes with export and display values), turning a received registration into a Customer, and validating both the required fields and the business rules the form can't express. You've seen that MaxLen, ReadOnly and Required protect nothing against a program, how to handle characters Helvetica doesn't support by adding a Unicode font to /DR, why generating appearances with setValue is preferable to NeedAppearances, how to prefill forms in batches, and how to exchange just the data with FDF and XFDF. All of this lives in RegistrationFormFiller and RegistrationRequest.
So far we've worked with a form that was handed to us. In the next lesson we'll switch sides: we'll learn to create forms programmatically, field by field, with their widgets, borders, checkboxes, radio groups, drop-downs and the signature space, and we'll finally study the complete code of GenerateRegistrationForm.
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
