In the two previous lessons we worked with a registration form that already existed: we inspected it, filled it in and read it. Now we're going to build it. Creating a form with PDFBox takes more effort than filling one in, because nothing happens by itself: you have to create the AcroForm dictionary with its resources, each field with its name and flags, each widget with its rectangle, page and look and, for checkboxes and radio buttons, draw by hand their checked and unchecked appearances. In return, the form comes out exactly the way we want and integrates with everything we learned in modules 2 and 3: labels, lines and boxes are drawn with InvoiceLabFonts, Shapes, ContentBox and the corporate Theme. We'll wrap the repetitive part in a field factory, PdfFields, and finish with the complete code of GenerateRegistrationForm, the class we've been using as a black box since lesson 05-01.
Contents
- What needs to be built
- The empty form:
PDAcroForm,/DRand/DA - Hierarchical names: attaching fields to their parents
- The widget: rectangle, page, colours and border
- Text fields: single-line, multiline, maximum length and comb
- Checkboxes: on and off appearances
- Radio button groups
- Drop-down lists
- The empty signature field
- Tab order
GenerateRegistrationForm: the complete form- JavaScript in forms: just a mention
What needs to be built
For each field in the form you have to produce these objects (go back to lesson 05-01 if any of them doesn't ring a bell):
flowchart TD
A["1. PDAcroForm in the catalog<br/>/DR with fonts, default /DA"] --> B["2. Field (PDTextField, PDCheckBox...)<br/>partial name, flags, value"]
B --> C["3. Attach it to the tree<br/>/Fields (root) or its parent's /Kids"]
C --> D["4. Widget<br/>/Rect, /P, /MK, /BS, /F Print"]
D --> E["5. Add the widget to the page's /Annots"]
E --> F["6. /AP appearances<br/>text: generated by PDFBox<br/>buttons: drawn by us"]
On top of that, there's the page content: title, sections, a label for each field and the legal text. The fields are interactive, but everything around them is ordinary content drawn with a PDPageContentStream.
The empty form: PDAcroForm, /DR and /DA
PdfFields receives the document and prepares the form in its constructor:
package com.invoicelab.forms;
import com.invoicelab.pdf.NebulaColors;
import java.awt.Color;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.pdfbox.cos.COSDictionary;
import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.pdmodel.PDAppearanceContentStream;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDResources;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import org.apache.pdfbox.pdmodel.font.Standard14Fonts;
import org.apache.pdfbox.pdmodel.graphics.color.PDColor;
import org.apache.pdfbox.pdmodel.graphics.color.PDDeviceRGB;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationWidget;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAppearanceCharacteristicsDictionary;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAppearanceDictionary;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAppearanceEntry;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAppearanceStream;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDBorderStyleDictionary;
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.PDSignatureField;
import org.apache.pdfbox.pdmodel.interactive.form.PDTerminalField;
import org.apache.pdfbox.pdmodel.interactive.form.PDTextField;
/** AcroForm field factory: creates fields with hierarchical names ("customer.address.postalCode") and their widgets. */
public final class PdfFields {
/** Default appearance for text: font /Helv from /DR, 10 points, black (0 g). */
public static final String TEXT_DA = "/Helv 10 Tf 0 g";
/** One option in a radio group: its export value and where it's drawn. */
public record RadioOption(String value, PDRectangle rectangle) {
}
private final PDDocument document;
private final PDAcroForm form;
private final Map<String, PDNonTerminalField> groups = new HashMap<>();
private final List<PDField> roots = new ArrayList<>();
private Color border = NebulaColors.BLUE;
private Color background = new Color(0xF4, 0xF7, 0xFB);
public PdfFields(PDDocument document) {
this.document = document;
this.form = new PDAcroForm(document);
document.getDocumentCatalog().setAcroForm(form);
// Default resources (/DR): the fonts viewers will use when regenerating appearances
PDResources dr = new PDResources();
dr.put(COSName.HELV, new PDType1Font(Standard14Fonts.FontName.HELVETICA));
dr.put(COSName.ZA_DB, new PDType1Font(Standard14Fonts.FontName.ZAPF_DINGBATS));
form.setDefaultResources(dr);
form.setDefaultAppearance(TEXT_DA); // the form's /DA, inherited by the fields
}
public PDAcroForm form() {
return form;
}
/** Changes the border and background colours of widgets created from now on. */
public PdfFields colors(Color border, Color background) {
this.border = border;
this.background = background;
return this;
}new PDAcroForm(document)+setAcroForm: creates the dictionary and hooks it into the catalog. Without this link, the fields would exist as loose objects that no viewer would ever find./DRwith two fonts:/Helv(Helvetica) for text and/ZaDb(ZapfDingbats) for the checkbox and radio symbols. The namesCOSName.HELVandCOSName.ZA_DBare the ones Acrobat and most tools use by convention. Being standard fonts, they aren't embedded: the form stays lightweight, at the cost of being limited to WinAnsi (lesson 05-02).- The form's
/DA:"/Helv 10 Tf 0 g". Fields inherit it if they don't define their own; even so, each text field will declare its own explicitly, because some viewers only look at the field's. groupsandroots: internal state for building the name tree (next section).colors(...): lets you change the look of widgets created afterwards; it returnsthisso calls can be chained.
Hierarchical names: attaching fields to their parents
We want to be able to write fields.text("customer.address.postalCode", ...) and have the factory create the customer and customer.address nodes if they don't exist. PDFBox has no setParent method for fields, so we link the objects in both directions: the child points to its parent with /Parent, and the parent includes the child in /Kids.
/** Attaches the field to its parent based on the full name; parents are created on the fly. */
private void attach(PDField field, String fullName) {
int dot = fullName.lastIndexOf('.');
field.setPartialName(fullName.substring(dot + 1));
if (dot < 0) {
addRoot(field);
} else {
addChild(group(fullName.substring(0, dot)), field);
}
}
/** Returns (creating it if needed) the non-terminal field "customer.address"... */
private PDNonTerminalField group(String path) {
PDNonTerminalField existing = groups.get(path);
if (existing != null) {
return existing;
}
PDNonTerminalField created = new PDNonTerminalField(form);
attach(created, path); // recursive: also creates its ancestors
groups.put(path, created);
return created;
}
private void addRoot(PDField field) {
roots.add(field);
form.setFields(roots); // /Fields only contains the root fields
}
private static void addChild(PDNonTerminalField parent, PDField child) {
child.getCOSObject().setItem(COSName.PARENT, parent); // child → parent
List<PDField> children = new ArrayList<>(parent.getChildren());
children.add(child);
parent.setChildren(children); // parent → children (/Kids)
}Let's follow customer.address.postalCode:
attach(postalCode, "customer.address.postalCode"): the partial name ispostalCodeand the parent iscustomer.address.group("customer.address")doesn't exist: it creates aPDNonTerminalFieldand callsattach(created, "customer.address"), which in turn asks forgroup("customer").group("customer")doesn't exist: it creates it and attaches it as a root (there's no dot).- On the way back out of the recursion, each node is added to its parent's
/Kids. Thegroupsmap preventscustomerfrom being created twice whencustomer.taxIdcomes along.
One detail: parent.getChildren() builds a new list from /Kids; that's why we copy it, add the child and assign it back with setChildren.
The widget: rectangle, page, colours and border
All field types share the widget setup:
private void prepareWidget(PDAnnotationWidget widget, PDPage page, PDRectangle rect)
throws IOException {
widget.setRectangle(rect);
widget.setPage(page);
widget.setPrinted(true); // so it shows up when printed
PDAppearanceCharacteristicsDictionary mk =
new PDAppearanceCharacteristicsDictionary(new COSDictionary());
mk.setBorderColour(color(border));
mk.setBackground(color(background));
widget.setAppearanceCharacteristics(mk);
PDBorderStyleDictionary style = new PDBorderStyleDictionary();
style.setWidth(0.75f);
widget.setBorderStyle(style);
page.getAnnotations().add(widget); // creation order = order in /Annots
}
private static PDColor color(Color c) {
return new PDColor(c.getRGBColorComponents(null), PDDeviceRGB.INSTANCE);
}
/** Helper for creating widget rectangles: x, y (bottom-left corner), width, height. */
public static PDRectangle rect(float x, float y, float width, float height) {
return new PDRectangle(x, y, width, height);
}| Element | PDF key | What it's for |
|---|---|---|
setRectangle |
/Rect |
Position and size on the page, in points, origin at the bottom left |
setPage |
/P |
The widget's page (optional in the standard, but useful, as we saw in FormInspector) |
setPrinted(true) |
/F 4 |
Without this flag, many viewers don't print the field |
PDAppearanceCharacteristicsDictionary |
/MK |
Border (/BC) and background (/BG) colours, checkbox symbol (/CA). PDFBox and viewers use them when generating appearances |
PDBorderStyleDictionary |
/BS |
Border width (and style: solid, dashed, bevelled…) |
getAnnotations().add |
/Annots |
Without this, the widget isn't drawn on the page |
The /MK colours are expressed as PDColor, not as java.awt.Color; the color helper method does the conversion to RGB.
Text fields: single-line, multiline, maximum length and comb
/** Single-line text field with its widget. */
public PDTextField text(String name, PDPage page, PDRectangle rect) throws IOException {
PDTextField field = new PDTextField(form);
attach(field, name);
field.setDefaultAppearance(TEXT_DA);
prepareWidget(field.getWidgets().get(0), page, rect);
return field;
}new PDTextField(form) creates a field with a merged widget: getWidgets().get(0) returns the field's own dictionary viewed as a widget. Variants are configured on the returned field:
PDTextField notes = fields.text("notes", page, rect(x, y - 44, width, 44));
notes.setMultiline(true); // allows several lines; the viewer wraps the text
PDTextField taxId = fields.text("customer.taxId", page, rect(x, y, 9 * 14, 16));
taxId.setMaxLen(9); // at most 9 characters when typing
taxId.setComb(true); // one box per character: requires MaxLen
taxId.setRequired(true);- Multiline: the rectangle has to be tall enough for several lines; here 44 points, about 3–4 lines at 10 points.
MaxLenlimits what the user can type in the viewer (you already know PDFBox doesn't enforce it withsetValue).- Comb divides the width into
MaxLenequal boxes and draws one character in each. That's why the VAT ID field measures9 * 14points: 14 points per character. It's very handy for VAT IDs, postal codes or IBANs, because it guides the user and stops them typing too much. - Other flags available:
setPassword(hides what's typed),setDoNotSpellCheck,setDoNotScroll(prevents typing more than fits).
Checkboxes: on and off appearances
A checkbox needs two appearances inside /AP /N: one for its on state (with whatever name we choose, here Yes) and another for /Off. Which state is shown is given by /AS. PDFBox doesn't draw them for us: without them, the checkbox would have no valid states and setValue("Yes") would fail.
/** Checkbox: onValue is the name of its "on" state (e.g. "Yes"). */
public PDCheckBox checkbox(String name, PDPage page, PDRectangle rect, String onValue)
throws IOException {
PDCheckBox field = new PDCheckBox(form);
attach(field, name);
PDAnnotationWidget widget = field.getWidgets().get(0);
prepareWidget(widget, page, rect);
widget.getAppearanceCharacteristics().setNormalCaption("4"); // 4 = ✓ in ZapfDingbats
onOffAppearances(widget, onValue, false);
field.setValue("Off"); // starts unticked
return field;
}
/** /AP /N with two states: the on value and /Off. */
private void onOffAppearances(PDAnnotationWidget widget, String onValue, boolean round)
throws IOException {
PDRectangle rect = widget.getRectangle();
COSDictionary normal = new COSDictionary();
normal.setItem(COSName.getPDFName(onValue), appearance(rect, onValue, true, round));
normal.setItem(COSName.Off, appearance(rect, null, true, round));
PDAppearanceDictionary ap = new PDAppearanceDictionary();
ap.setNormalAppearance(new PDAppearanceEntry(normal));
widget.setAppearance(ap);
widget.setAppearanceState("Off"); // /AS: the state being shown
}setNormalCaption("4")stores in/MK /CAthe ZapfDingbats character that represents the mark (the "4" in that font is ✓). We don't use it for drawing, but viewers that regenerate appearances need it to paint the same mark.- The
normalsubdictionary has two keys:/Yesand/Off, each with its own appearance stream. COSName.Off, notCOSName.OFF: they're two different constants (/Offand/OFF). If you use the second one, the value"OFF"isn't valid and PDFBox throws "value 'OFF' is not a valid option… valid values are: [Yes] and Off". We found this out the hard way while writing this class.- The standard also allows
/D(down, while being pressed) and/R(rollover, with the mouse over it) appearances. They're optional and we don't create them.
Each appearance is drawn as a small content stream with its own coordinate system:
/** Draws an appearance: background + border and, if checked, a ✓ mark or a dot. */
private PDAppearanceStream appearance(PDRectangle rect, String checked, boolean withFrame, boolean round)
throws IOException {
float w = rect.getWidth();
float h = rect.getHeight();
PDAppearanceStream stream = new PDAppearanceStream(document);
stream.setBBox(new PDRectangle(w, h)); // local coordinates: (0,0)-(w,h)
stream.setResources(new PDResources());
try (PDAppearanceContentStream cs = new PDAppearanceContentStream(stream)) {
if (withFrame) {
cs.setNonStrokingColor(background);
cs.setStrokingColor(border);
cs.setLineWidth(0.75f);
if (round) {
circle(cs, w / 2, h / 2, Math.min(w, h) / 2 - 0.5f);
} else {
cs.addRect(0.5f, 0.5f, w - 1, h - 1);
}
cs.fillAndStroke();
}
if (checked != null) {
cs.setNonStrokingColor(border);
cs.setStrokingColor(border);
if (round) {
circle(cs, w / 2, h / 2, Math.min(w, h) / 4);
cs.fill();
} else { // ✓ drawn with two strokes
cs.setLineWidth(1.6f);
cs.moveTo(w * 0.2f, h * 0.5f);
cs.lineTo(w * 0.42f, h * 0.25f);
cs.lineTo(w * 0.8f, h * 0.78f);
cs.stroke();
}
}
}
return stream;
}
/** Approximates a circle with four Bézier curves. */
private static void circle(PDAppearanceContentStream cs, float cx, float cy, float r) throws IOException {
float k = 0.5523f * r;
cs.moveTo(cx + r, cy);
cs.curveTo(cx + r, cy + k, cx + k, cy + r, cx, cy + r);
cs.curveTo(cx - k, cy + r, cx - r, cy + k, cx - r, cy);
cs.curveTo(cx - r, cy - k, cx - k, cy - r, cx, cy - r);
cs.curveTo(cx + k, cy - r, cx + r, cy - k, cx + r, cy);
cs.closePath();
}PDAppearanceStreamis a form XObject (lesson 04-05) associated with the annotation. ItsBBoxruns from(0, 0)to(width, height): inside the appearance you don't have to think about the position on the page; the viewer places it at/Rect.PDAppearanceContentStream(packageorg.apache.pdfbox.pdmodel) is the equivalent ofPDPageContentStreamfor appearances, with the same drawing methods you already know from module 2.- The box is drawn 0.5 points in from the edge so that the 0.75-point line isn't clipped by the
BBox. - The ✓ mark is vector-based (two segments), so we don't depend on how each viewer encodes ZapfDingbats. The radio buttons' circle is approximated with four Bézier curves;
0.5523is the classic constant that makes it look like a perfect circle. withFrame = falseproduces an empty appearance: we'll use it for the signature.
Radio button groups
A radio group is one field with several widgets, one per option. Unlike the other types, here we create the widgets ourselves and link them to the field:
/** Radio button group: a single field with one widget per option. */
public PDRadioButton radioGroup(String name, PDPage page, List<RadioOption> options)
throws IOException {
PDRadioButton field = new PDRadioButton(form);
attach(field, name);
List<PDAnnotationWidget> widgets = new ArrayList<>();
for (RadioOption option : options) {
PDAnnotationWidget widget = new PDAnnotationWidget();
widget.setParent(field); // /Parent → the field
prepareWidget(widget, page, option.rectangle());
widget.getAppearanceCharacteristics().setNormalCaption("l"); // l = ● in ZapfDingbats
onOffAppearances(widget, option.value(), true);
widgets.add(widget);
}
field.setWidgets(widgets); // the field's /Kids = the widgets
return field;
}- Each widget has a different on state (
Transfer,DirectDebit,PromissoryNote): that's where thegetOnValues()list we used in 05-02 comes from. widget.setParent(field)andfield.setWidgets(widgets)create the link in both directions (/Parentand/Kids).new PDRadioButton(form)already sets the Radio flag. If you don't want the user to be able to deselect the chosen option by clicking it again, there's the NoToggleToOff flag; we haven't set it.- The text for each option ("Direct debit") is drawn on the page, next to the button. The internal value has no spaces or accents; the label can have whatever it needs.
Drop-down lists
/** Drop-down list with export values (what gets stored) and display values (what's shown). */
public PDComboBox dropDown(String name, PDPage page, PDRectangle rect,
List<String> exportValues, List<String> displayValues) throws IOException {
PDComboBox field = new PDComboBox(form);
attach(field, name);
field.setDefaultAppearance(TEXT_DA);
field.setOptions(exportValues, displayValues);
prepareWidget(field.getWidgets().get(0), page, rect);
return field;
}setOptions(exportValues, displayValues) stores [export display] pairs in /Opt; both lists must be the same size. With setOptions(list) (a single argument) both values are the same. Other combo box options: setEdit(true) lets the user type a value that isn't in the list, and setSort(true) asks the viewer to sort the options. For a visible list with multiple selection you use PDListBox (exercise 1).
The empty signature field
The registration form must be signed by the customer's representative. We reserve the space with a PDSignatureField without a signature: in module 7 we'll learn to sign precisely in this field.
/** Empty signature field: reserves the space that will be filled in when signing (module 7). */
public PDSignatureField signature(String name, PDPage page, PDRectangle rect) throws IOException {
PDSignatureField field = new PDSignatureField(form);
attach(field, name);
PDAnnotationWidget widget = field.getWidgets().get(0);
prepareWidget(widget, page, rect);
// Empty appearance: the space is visible thanks to the box drawn on the page
PDAppearanceDictionary ap = new PDAppearanceDictionary();
ap.setNormalAppearance(appearance(rect, null, false, false));
widget.setAppearance(ap);
return field;
}
/** Makes a terminal field neither exportable nor editable (internal use). */
public static void internalOnly(PDTerminalField field) {
field.setReadOnly(true);
field.setNoExport(true);
}
}PDFBox doesn't generate appearances for signatures (it warns you with "Appearance generation for signature fields not implemented here"), so we give it an empty appearance and draw the box in the page content. The last method, internalOnly, marks a field as ReadOnly and NoExport: we'll use it for the registration number assigned by Nebula Distribution.
Tab order
When the user presses Tab, the viewer jumps to the next field. The order is determined by two things:
- The order of the widgets in
/Annots.prepareWidgetadds them in the order they're created, so all you need to do is create them in a logical order: top to bottom and left to right. - The page's
/Tabskey:/R(by rows),/C(by columns) or/S(following the tag structure, which we'll see in lesson 08-02). If it's missing, the standard doesn't fix the order and each viewer does what it sees fit; many follow/Annots, but not all.
PDFBox 3 doesn't offer a specific method, so you write it directly into the page's COS dictionary:
In a multi-column form where you want to go through a whole column first, use "C".
GenerateRegistrationForm: the complete form
With the factory ready, the class that generates the registration form is all about layout: it moves a vertical y cursor down from the top of the ContentBox, draws titles and labels with the Theme fonts and colours, and places each field below its label. Here's the complete code:
package com.invoicelab.forms;
import static com.invoicelab.forms.PdfFields.rect;
import com.invoicelab.generator.Theme;
import com.invoicelab.pdf.Alignment;
import com.invoicelab.pdf.ContentBox;
import com.invoicelab.pdf.InvoiceLabFonts;
import com.invoicelab.pdf.Shapes;
import com.invoicelab.pdf.TextMetrics;
import java.awt.Color;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.font.PDFont;
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.PDTextField;
import org.apache.pdfbox.pdmodel.interactive.form.PDVariableText;
/** Generates output/registration-form.pdf: Nebula Distribution's fillable customer registration form. */
public final class GenerateRegistrationForm {
private static final float FIELD_HEIGHT = 16; // height of a single-line field (points)
private static final float LABEL_GAP = 10; // space between a label and its field
private final PDPage page;
private final PDPageContentStream cs;
private final PdfFields fields;
private final ContentBox box;
private final Theme theme = Theme.nebula();
private final PDFont regular;
private final PDFont bold;
private float y; // cursor: top line of whatever comes next
private GenerateRegistrationForm(PDDocument document, PDPage page, PDPageContentStream cs) throws IOException {
this.page = page;
this.cs = cs;
this.fields = new PdfFields(document);
this.box = ContentBox.invoice(page.getMediaBox());
InvoiceLabFonts fonts = new InvoiceLabFonts(document);
this.regular = fonts.regular();
this.bold = fonts.bold();
this.y = box.top();
}
public static void main(String[] args) throws IOException {
Path target = Path.of("output/registration-form.pdf");
Files.createDirectories(target.getParent());
Files.write(target, generate());
System.out.println("Form generated: " + target);
}
/** Creates the complete form and returns it as bytes. */
public static byte[] generate() throws IOException {
try (PDDocument document = new PDDocument()) {
PDPage page = new PDPage(PDRectangle.A4);
document.addPage(page);
page.getCOSObject().setName(COSName.getPDFName("Tabs"), "R"); // tab order by rows
try (PDPageContentStream cs = new PDPageContentStream(document, page)) {
new GenerateRegistrationForm(document, page, cs).draw();
}
document.getDocumentInformation().setTitle("Customer registration form");
ByteArrayOutputStream output = new ByteArrayOutputStream();
document.save(output);
return output.toByteArray();
}
}
private void draw() throws IOException {
header();
section("1. Company details");
float x = box.left();
float width = box.width();
required(text("customer.companyName", "Company name *", x, width));
moveDown();
PDTextField taxId = text("customer.taxId", "VAT ID *", x, 9 * 14);
taxId.setMaxLen(9);
taxId.setComb(true); // one box per character
required(taxId);
required(text("customer.address.street", "Address (street and number) *",
x + 9 * 14 + 12, width - 9 * 14 - 12));
moveDown();
PDTextField postalCode = text("customer.address.postalCode", "Postcode *", x, 5 * 14);
postalCode.setMaxLen(5);
postalCode.setComb(true);
required(postalCode);
required(text("customer.address.city", "Town/City *", x + 82, 220));
label("Province *", x + 314);
PDComboBox province = fields.dropDown("customer.address.province", page,
rect(x + 314, y - LABEL_GAP - FIELD_HEIGHT, width - 314, FIELD_HEIGHT),
List.of("08", "22", "26", "25", "28", "31", "42", "43", "44", "46", "50"),
List.of("Barcelona", "Huesca", "La Rioja", "Lleida", "Madrid", "Navarra",
"Soria", "Tarragona", "Teruel", "Valencia", "Zaragoza"));
required(province);
moveDown();
section("2. Contact person");
text("contact.name", "Full name", x, 300);
text("contact.phone", "Phone", x + 312, width - 312);
moveDown();
required(text("contact.email", "Email *", x, 300));
moveDown();
section("3. Payment method *");
float yRadio = y - 12;
String[][] options = { { "Transfer", "Bank transfer" },
{ "DirectDebit", "Direct debit" }, { "PromissoryNote", "Promissory note at 30 days" } };
List<PdfFields.RadioOption> radios = new ArrayList<>();
for (int i = 0; i < options.length; i++) {
float xo = x + i * 160;
radios.add(new PdfFields.RadioOption(options[i][0], rect(xo, yRadio, 11, 11)));
text(regular, 9, options[i][1], xo + 16, yRadio + 2.5f);
}
required(fields.radioGroup("payment.method", page, radios));
y = yRadio - 8;
PDTextField iban = text("payment.iban", "IBAN (direct debit only)", x, 300);
iban.setMaxLen(24);
moveDown();
section("4. Notes");
PDTextField notes = fields.text("notes", page, rect(x, y - 44, width, 44));
notes.setMultiline(true); // allows several lines (Enter)
y -= 44 + 8;
section("5. Terms and data protection");
required(checkbox("terms.accepted",
"I have read and accept the general terms and conditions of sale of Nebula Distribution Ltd. *"));
required(checkbox("terms.privacy",
"I have read the basic data protection information set out below *"));
y -= 3;
cs.setNonStrokingColor(theme.secondaryText());
for (String line : List.of(
"Controller: Nebula Distribution Ltd. Purpose: managing the business relationship and invoicing.",
"Rights: access, rectification, erasure and others, by writing to [email protected].",
"(Sample text for the course: real legal texts must be reviewed by a professional.)")) {
text(regular, 6.8f, line, x + 16, y);
y -= 8.5f;
}
y -= 4;
checkbox("terms.marketing", "I wish to receive marketing communications (optional)");
y -= 4;
section("6. Signature");
text("signature.placeDate", "Place and date", x, 200);
label("Signature of the legal representative", x + 230);
PDRectangle space = rect(x + 230, y - LABEL_GAP - 50, width - 230, 50);
Shapes.drawBox(cs, space.getLowerLeftX(), space.getLowerLeftY(), space.getWidth(),
space.getHeight(), 0, null, theme.lineColor(), 0.5f);
fields.signature("signature.customer", page, space);
y -= LABEL_GAP + 50 + 12;
// Internal area: read-only and excluded from export
Shapes.drawBox(cs, x, y - 30, width, 30, 0, theme.softBackground(), null, 0);
cs.setNonStrokingColor(theme.primary());
text(bold, 7.5f, "RESERVED FOR NEBULA DISTRIBUTION", x + 6, y - 11);
PDTextField number = fields.text("internal.registrationNumber", page, rect(x + 6, y - 27, 150, 12));
PdfFields.internalOnly(number);
TextMetrics.writeAligned(cs, regular, 6.5f, "* Required fields", box.right() - 6, y - 24,
Alignment.RIGHT);
// Without this, text fields and drop-downs have no appearance (/AP) until someone
// fills them in. The signature is excluded: PDFBox doesn't generate signature appearances (module 7).
List<PDField> withText = new ArrayList<>();
for (PDField field : fields.form().getFieldTree()) {
if (field instanceof PDVariableText) {
withText.add(field);
}
}
fields.form().refreshAppearances(withText);
}
// ------------------------------------------------------------------ layout pieces
private void header() throws IOException {
cs.setNonStrokingColor(theme.primary());
text(bold, 16, "Customer registration form", box.left(), y - 16);
cs.setNonStrokingColor(theme.secondaryText());
TextMetrics.writeAligned(cs, regular, 8, "Nebula Distribution Ltd. · VAT ID B00000000 · Zaragoza",
box.right(), y - 14, Alignment.RIGHT);
y -= 24;
Shapes.horizontalLine(cs, box.left(), box.right(), y, 1.5f, theme.accent());
y -= 14;
}
private void section(String title) throws IOException {
cs.setNonStrokingColor(theme.primary());
text(bold, 10, title, box.left(), y - 10);
y -= 14;
Shapes.horizontalLine(cs, box.left(), box.right(), y, 0.5f, theme.lineColor());
y -= 6;
}
private void label(String text, float x) throws IOException {
cs.setNonStrokingColor(theme.secondaryText());
text(regular, theme.labelSize(), text, x, y - 7);
}
/** Label + single-line text field in the current row (doesn't move the cursor). */
private PDTextField text(String name, String label, float x, float width) throws IOException {
label(label, x);
return fields.text(name, page, rect(x, y - LABEL_GAP - FIELD_HEIGHT, width, FIELD_HEIGHT));
}
private PDCheckBox checkbox(String name, String caption) throws IOException {
PDCheckBox checkbox = fields.checkbox(name, page, rect(box.left(), y - 11, 11, 11), "Yes");
cs.setNonStrokingColor(Color.BLACK);
text(regular, 8.5f, caption, box.left() + 16, y - 8.5f);
y -= 16;
return checkbox;
}
private void text(PDFont font, float size, String text, float x, float yBase) throws IOException {
TextMetrics.writeAligned(cs, font, size, text, x, yBase, Alignment.LEFT);
}
/** Moves on to the next row of fields. */
private void moveDown() {
y -= LABEL_GAP + FIELD_HEIGHT + 10;
}
private static <T extends PDField> T required(T field) {
field.setRequired(true);
return field;
}
}The key design ideas:
- Two layers that don't mix. Everything that's fixed text (title, sections, labels, clauses, the signature box) is drawn in the page's content stream with DejaVu (subset, as always in InvoiceLab). The fields are annotations placed on top, with their own fonts in
/DR. That's why the labels can contain any character even though the fields use Helvetica. - The
ycursor works just as in module 3: each row consumesLABEL_GAP + FIELD_HEIGHT + 10points. Thetext(name, label, x, width)methods draw the label and the field in the current row without moving the cursor, so you can put several fields on the same row before callingmoveDown(). required(...)is a generic method that sets Required and returns the same field, which lets you writerequired(text(...))on a single line.- The data protection text is a fictional example and says so explicitly: in a real form, the wording of the clauses and consents must be reviewed by a professional. Note that the marketing communications checkbox is independent and not required.
- The final refresh is essential. Freshly created, the text fields and the drop-down have no
/AP: in the first version of this class, when rendering the PDF with PDFBox the fields didn't even show up (no appearance means nothing to draw).refreshAppearances(list)generates the empty appearance for each one, with the/MKbackground and border, and the comb fields with their dividers. We pass only thePDVariableTextfields so as not to ask PDFBox for the signature's appearance. generate()returnsbyte[], like the generators in module 3 (DocumentGenerator): that way it can be written to disk, sent over HTTP (module 8) or loaded directly withLoader.loadPDF(bytes).
Running it produces output/registration-form.pdf with the 18 fields and 20 widgets we inventoried in 05-01.
JavaScript in forms: just a mention
AcroForm lets you attach JavaScript actions to fields (PDActionJavaScript in a field's PDFormFieldAdditionalActions): formatting an amount as it's typed (/F), validating a value when leaving the field (/V), calculating a total from other fields (/C, in the order given by /CO) or filtering keystrokes (/K). Technically PDFBox can write those actions, but in InvoiceLab we won't use them, for several reasons:
- Only some viewers (mainly Acrobat) run form JavaScript; browsers and mobile viewers ignore it completely or partially, so the form would behave differently depending on where it's opened.
- Many organisations disable JavaScript in PDFs for security reasons: it has historically been an attack vector, and a PDF with scripts may be blocked by email filters.
- PDFBox doesn't run JavaScript: a total calculated by a script won't be updated when filling in from Java.
- Client-side validation can be bypassed: the real validation is the one in
RegistrationFormFiller.validate(05-02), on the server.
If you receive forms from third parties, bear in mind that they may contain JavaScript and treat it as untrusted content.
Common Mistakes and Tips
- Forgetting
setAcroForm. The fields exist but no viewer finds them. Always check the result withFormInspector. - Not adding the widget to
/Annots. The field appears in the tree but not on the page. - Creating checkboxes without
/AP /N. Without appearances there are no valid states:setValuefails and the viewer doesn't know what to show. - Using
COSName.OFFinstead ofCOSName.Off. PDF is case-sensitive:/OFFisn't a button state. - Drawing appearances in page coordinates. Inside a
PDAppearanceStreamthe origin is the widget's own corner (BBoxfrom(0, 0)to(width, height)). - Not refreshing the appearances at the end. Empty fields don't show up in some viewers (in PDFBox, for example). Use
refreshAppearanceswith thePDVariableTextfields. - Forgetting
setPrinted(true). The form looks fine on screen, but the fields disappear when printed. - Using the same full name for two different fields. They'll be the same field and share a value.
- Tip: store the generated form as a versioned resource (for example,
registration-form-v1.pdf) rather than regenerating it on every request. Customers will send back forms from old versions, and it's worth knowing which one they filled in (exercise 3).
Exercises
Exercise 1. Add to PdfFields a method PDListBox listBox(String name, PDPage page, PDRectangle rect, List<String> exportValues, List<String> displayValues, boolean multiple) that creates a visible list with single or multiple selection. Test it with an order.days field containing the working days (MO, TU, WE, TH, FR) and select Monday and Wednesday with setValue(List.of("MO", "WE")).
Exercise 2. Write a program that turns registration-form.pdf into registration-form-unicode.pdf, a blank form whose fields use the full DejaVu Sans font, so that it can be filled in with "Tomáš Dvořák" without calling useUnicodeFont. Reuse PdfEditor (04-01) and RegistrationFormFiller.useUnicodeFont (05-02).
Exercise 3. Add to PdfFields a method PDTextField hidden(String name, PDPage page, String value) that creates an invisible, read-only field with a fixed value. Use it in GenerateRegistrationForm to store internal.version = "REG-FORM-1", so that InvoiceLab knows which version of the form each customer filled in.
Solutions
Solution 1.
/** Visible list, with single or multiple selection. */
public PDListBox listBox(String name, PDPage page, PDRectangle rect, List<String> exportValues,
List<String> displayValues, boolean multiple) throws IOException {
PDListBox field = new PDListBox(form);
attach(field, name);
field.setDefaultAppearance(TEXT_DA);
field.setOptions(exportValues, displayValues);
field.setMultiSelect(multiple); // MultiSelect flag
prepareWidget(field.getWidgets().get(0), page, rect);
return field;
}It's almost identical to dropDown; only the class and the multi-select flag change (add import ...form.PDListBox). The test:
PDListBox days = fields.listBox("order.days", page, PdfFields.rect(50, 600, 150, 70),
List.of("MO", "TU", "WE", "TH", "FR"), List.of("Monday", "Tuesday", "Wednesday", "Thursday", "Friday"), true);
days.setValue(List.of("MO", "WE"));After saving and reloading, getValueAsString() returns [MO, WE], and the appearance generated by PDFBox highlights "Monday" and "Wednesday". Make the rectangle tall enough (70 points for five options at 10 points); if they don't fit, the viewer will show a scroll bar. Just like the combo box, PDListBox.setValue accepts values that aren't among the options (we tried it with "Saturday"): validate before assigning.
Solution 2.
PdfEditor.edit(Path.of("output/registration-form.pdf"), Path.of("output/registration-form-unicode.pdf"),
PdfEditor.Mode.FULL, document -> {
PDAcroForm form = document.getDocumentCatalog().getAcroForm(null);
RegistrationFormFiller.useUnicodeFont(document, form); // /DR + each field's /DA
form.setDefaultAppearance("/DejaVu 10 Tf 0 g"); // the form's /DA
List<PDField> texts = new ArrayList<>();
for (PDField field : form.getFieldTree()) {
if (field instanceof PDVariableText) {
texts.add(field);
}
}
form.refreshAppearances(texts); // empty appearances with the new font
});The result is about 426 KB (the full font) and can be filled in with setValue("Tomáš Dvořák") directly. We also change the form's /DA so that any field added in the future inherits the new font. Why full mode? Because it's a new form we're going to distribute: there's no previous revision to preserve.
Solution 3.
/** Hidden, read-only field with a fixed value (e.g. the form version). */
public PDTextField hidden(String name, PDPage page, String value) throws IOException {
PDTextField field = text(name, page, rect(0, 0, 0, 0)); // empty rectangle
field.getWidgets().get(0).setHidden(true); // the widget's Hidden flag (/F)
field.setValue(value);
field.setReadOnly(true);
return field;
}In GenerateRegistrationForm.draw(), next to registrationNumber: fields.hidden("internal.version", page, "REG-FORM-1");. Note the difference: Hidden is a widget flag (the annotation's /F: it's neither shown nor printed), whereas ReadOnly is a field flag (/Ff). We assign the value before setting ReadOnly purely for clarity; as you know, PDFBox would write it anyway. When a registration comes in, RegistrationFormFiller can check getField("internal.version"): if it's null, the customer filled in a form older than this version; if it doesn't match the expected one, apply the corresponding mapping.
Conclusion
You now know how to create AcroForm forms from scratch: setting up the PDAcroForm with its resources (/DR) and default appearance (/DA), building the name tree by linking parents and children, configuring each widget (rectangle, page, print flag, /MK colours and /BS border), creating text fields with multiline, maximum length and comb, drawing the on/off appearances of checkboxes and radio buttons, defining drop-downs with export and display values, reserving an empty signature field and controlling the tab order. PdfFields wraps all of this, and GenerateRegistrationForm shows how to combine it with the layout techniques from modules 2 and 3.
There's one word that has come up again and again in this module: appearance. Checkboxes have their own, text fields need someone to generate them, and a value without an appearance may not be visible. In the last lesson of the module we'll study appearances in depth, why a form can look different in each viewer and how to flatten a form to turn its fields into fixed content; with that we'll close the full loop for the registration form: receive it, validate it, flatten it, stamp it and archive it.
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
