Over the last three lessons you've built some very capable pieces (Table, Paginator, PageFooter, PdfCodes), but every example repeated the same routine: create the PDDocument, create InvoiceLabFonts, load the logo, set up the paginator with its lambdas, close the paginator, number the footers, save... If tomorrow Nebula Distribution needs delivery notes, quotes and credit notes, copying and pasting that skeleton into each class would be the quickest route to chaos: a change to the margins or the footer would mean touching five places, and sooner or later one of them would be forgotten. In this lesson you're going to design the architecture of InvoiceLab's generator: separating model, layout and rendering; defining a common contract (DocumentGenerator<T>); gathering everything that belongs to a document into a context; centralising styles in a theme; and building documents as a sequence of composable blocks. To check that the architecture works, you'll use it to generate a new document, the delivery note, with very little code. You'll assemble the complete invoice in the next lesson.
Contents
- The problem: the repeated skeleton
- Separating responsibilities: model, layout and rendering
- The common contract:
DocumentGenerator<T> - A document's context:
PdfContext - Centralised styles: the
Theme - Composable blocks: the
Blockinterface - The first blocks
- The common skeleton:
BaseGeneratorand the template method pattern - Handling errors and resources
- Class diagram
- Reuse: the delivery note generator
The problem: the repeated skeleton
Look back at MultipageInvoice from lesson 03-02. Of all its lines, only a few are specific to an invoice (the columns, the rows, the "Carried forward"); the rest is infrastructure:
| Step | Specific to the document? |
|---|---|
Create the PDDocument with try-with-resources |
No |
Create InvoiceLabFonts and load the logo once |
No |
Create the Paginator with first-page and following-page headers |
Only which headers |
Call newPage() |
No |
| Draw the content | Yes |
| Close the paginator before saving | No |
Number the pages with PageFooter |
Only the footer text |
| Save | No (though: to disk? to memory? to an HTTP response?) |
The infrastructure is the same for every document, and it's also the delicate part: the closing order, one font per document, the open stream... It's exactly what you want to write only once.
Separating responsibilities: model, layout and rendering
A good generator separates three concerns, each in its own package:
| Layer | Package | Responsibility | It mustn't know... |
|---|---|---|---|
| Model | com.invoicelab.model |
Data and business rules: amounts, VAT, validations | ...anything about PDF |
| Layout | com.invoicelab.generator |
Which blocks make up each document and in what order; turning the model into text | ...how a line is drawn |
| Rendering | com.invoicelab.pdf |
Primitives: text, tables, graphics, codes, pages | ...what an invoice is (with one pragmatic exception: InvoiceHeader.Data.of) |
flowchart LR
M["model<br/>Invoice, DeliveryNote,<br/>Customer, InvoiceLine"] --> G["generator<br/>InvoiceGenerator, DeliveryNoteGenerator,<br/>Blocks, Theme, PdfContext"]
G --> P["pdf<br/>Table, Paginator, PageFooter,<br/>PdfCodes, TextBlock..."]
P --> B["PDFBox"]
The arrows indicate dependencies: the generator knows the model and the primitives; the primitives don't know the generator; the model knows nobody. That way you can test the VAT calculations without generating any PDF, and change the look of the tables without touching the model.
The common contract: DocumentGenerator<T>
Seen from outside, all generators do the same thing: they receive a model object and return a PDF. We express this with a generic interface:
package com.invoicelab.generator;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardCopyOption;
/** Turns a model object (invoice, delivery note...) into the bytes of a PDF. */
public interface DocumentGenerator<T> {
byte[] generate(T data) throws IOException;
/** Generates and writes to disk safely: first to a temporary file, which is then renamed. */
default void generate(T data, Path target) throws IOException {
byte[] pdf = generate(data); // if it fails, the disk hasn't been touched
Path folder = target.toAbsolutePath().getParent();
Files.createDirectories(folder);
Path temp = Files.createTempFile(folder, "invoicelab-", ".tmp");
try {
Files.write(temp, pdf);
Files.move(temp, target, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.ATOMIC_MOVE);
} finally {
Files.deleteIfExists(temp);
}
}
}Why return byte[] rather than writing straight to a file?
- The destination is none of the generator's business. The same PDF can go to disk, to a database, to an email or, in module 8, to an HTTP response from a REST service.
- Atomicity. If generation fails halfway, no half-written PDF is left on disk under its final name. The
defaultmethod takes advantage of this: it generates in memory, writes a temporary file in the same folder and renames it withATOMIC_MOVE; whoever opensF-2026-0001.pdfwill see either the previous version or the new one, never a mixture. - Ease of testing. A test can generate the bytes and load them with
Loader.loadPDF(bytes)without touching the disk.
An invoice takes up tens of KB, so holding it entirely in memory is no problem. For documents of hundreds of MB we'll look at alternatives in lesson 08-03.
A document's context: PdfContext
There are objects that belong to a document and that every block needs: the PDDocument, the fonts (one PDType0Font per document, lesson 02-03), the images (one PDImageXObject per document, lesson 02-06), the paginator and the theme. Instead of passing five parameters to every block, we group them:
package com.invoicelab.generator;
// imports: pdf (ContentBox, InvoiceLabFonts, Images, Paginator), java.io.IOException,
// java.util (HashMap, Map), PDFBox (PDDocument, PDPageContentStream, PDImageXObject)
/**
* Everything a block needs in order to draw itself in ONE specific document.
* It lives as long as the PDDocument: it's created when generation starts and discarded when it ends.
*/
public final class PdfContext {
private final PDDocument document;
private final InvoiceLabFonts fonts;
private final Theme theme;
private final Map<String, PDImageXObject> images = new HashMap<>();
private Paginator paginator;
public PdfContext(PDDocument document, Theme theme) {
this.document = document;
this.fonts = new InvoiceLabFonts(document); // fonts: once per document
this.theme = theme;
}
public PDDocument document() { return document; }
public InvoiceLabFonts fonts() { return fonts; }
public Theme theme() { return theme; }
/** Classpath image, loaded only once per document even if it's requested on every page. */
public PDImageXObject image(String path) throws IOException {
PDImageXObject image = images.get(path);
if (image == null) {
image = Images.loadResource(document, path);
images.put(path, image);
}
return image;
}
void usePaginator(Paginator paginator) { // package visibility: only BaseGenerator
this.paginator = paginator;
}
public Paginator paginator() {
if (paginator == null) {
throw new IllegalStateException("The paginator isn't available yet");
}
return paginator;
}
/** Shortcuts to the current page. */
public PDPageContentStream content() { return paginator().content(); }
public ContentBox box() { return paginator().box(); }
/** Places one or more blocks in sequence, leaving the theme's spacing between them. */
public void place(Block... blocks) throws IOException {
for (Block block : blocks) {
block.place(this);
paginator().moveDown(theme.blockSpacing());
}
}
}image(path)is a per-document cache: the header on page 1 and the compact one on page 5 ask for the same logo and receive the samePDImageXObject. The "one image per document" rule takes care of itself.usePaginatorisn't public (it has no modifier): only classes in thegeneratorpackage can set the paginator. A block mustn't be able to replace it.- It isn't thread-safe and isn't shared between documents: just like the
PDDocument, each generation creates its own. To generate in parallel, each thread generates its own document (you'll check this in exercise 3). place(Block...)receives blocks as varargs and places them in order. It's how generators "compose" the document.
Centralised styles: the Theme
The corporate colours were already in NebulaColors, but font sizes, spacing between blocks and table style were still scattered around the code. The Theme gathers together the design decisions shared by all documents:
package com.invoicelab.generator;
// imports: pdf (NebulaColors, InvoiceLabFonts, Measures, Table), java.awt.Color, java.io.IOException
/** Centralised styles: colours, sizes and spacing shared by all documents. */
public record Theme(Color primary, Color accent, Color softBackground, Color secondaryText, Color lineColor,
float textSize, float smallSize, float labelSize, float blockSpacing) {
/** Nebula Distribution's corporate theme. */
public static Theme nebula() {
return new Theme(NebulaColors.BLUE, NebulaColors.ORANGE, NebulaColors.BACKGROUND_BLUE,
NebulaColors.TEXT_GREY, NebulaColors.LINE_GREY,
9f, 7.5f, 7.5f, Measures.mm(6));
}
/** Table style derived from the theme. */
public Table.Style tableStyle(InvoiceLabFonts fonts) throws IOException {
return new Table.Style(fonts.regular(), fonts.bold(), textSize - 0.5f, Measures.mm(1.6),
primary, Color.WHITE, softBackground, lineColor, 0.5f);
}
}- The names are semantic (
primary,accent,softBackground), not literal (blue,orange): if another company in the group uses green, createTheme.otherCompany()without any block changing. tableStylederives lesson 03-01'sTable.Stylefrom the theme: every table in every document will look the same.- It's an immutable
record: it can be shared between threads and documents without risk. - Module 2 classes such as
InvoiceHeaderstill useNebulaColorsdirectly. That's fine: the theme can be adopted gradually, starting with the new pieces.
Composable blocks: the Block interface
An invoice is a sequence of blocks stacked from top to bottom: table, terms, totals, QR code. Each block honours the contract we've been using since lesson 02-04 (it receives its top edge and returns the height used), plus the ability to measure itself without drawing, which is what pagination needs:
package com.invoicelab.generator;
import com.invoicelab.pdf.Paginator;
import java.io.IOException;
/**
* A piece of a document that is drawn from a top edge and returns the height used.
* By default a block isn't split across pages: if it doesn't fit, it starts on the next page.
*/
public interface Block {
/** Height the block will need at this width (without drawing anything). */
float height(PdfContext ctx, float width) throws IOException;
/** Draws the block with its top-left corner at (x, yTop). Returns the height used. */
float draw(PdfContext ctx, float x, float yTop, float width) throws IOException;
/** Places the block at the paginator's current position, breaking the page if it doesn't fit. */
default void place(PdfContext ctx) throws IOException {
Paginator paginator = ctx.paginator();
float width = ctx.box().width();
paginator.ensure(height(ctx, width));
paginator.moveDown(draw(ctx, ctx.box().left(), paginator.y(), width));
}
}Three methods, three responsibilities:
| Method | Question it answers | Who uses it |
|---|---|---|
height(ctx, width) |
"How much space would you take at this width?" | The paginator (does it fit?), composite blocks |
draw(ctx, x, y, width) |
"Draw yourself here" | place and composite blocks |
place(ctx) |
"Put yourself in the document wherever you belong" | PdfContext.place |
xandwidthare parameters: a block doesn't decide where it goes or how wide it is. That way the same block can take up the whole box or half a column, and that's what makes it possible to compose blocks side by side.placeis adefaultmethod with "all or nothing" behaviour: it's measured,ensurebreaks the page if it doesn't fit, and it's drawn. Most blocks don't need to change it. A block that does need to spread across pages, such as the table, overrides it.
The first blocks
TableBlock: an adapter that does spread across pages
package com.invoicelab.generator;
// imports: pdf (Column, Table), java.io.IOException, java.util.List, java.util.function.IntFunction
/** Adapts Table to the Block contract. It's the only block that spreads across pages. */
public final class TableBlock implements Block {
private final List<Column> columns;
private final List<List<String>> rows;
private final IntFunction<String> runningTotal; // null = no "Carried forward"
public TableBlock(List<Column> columns, List<List<String>> rows, IntFunction<String> runningTotal) {
this.columns = List.copyOf(columns);
this.rows = List.copyOf(rows);
this.runningTotal = runningTotal;
}
private Table table(PdfContext ctx, float width) throws IOException {
return new Table(columns, width, ctx.theme().tableStyle(ctx.fonts()));
}
/** Height of the whole table if it were drawn on a single page. */
@Override
public float height(PdfContext ctx, float width) throws IOException {
Table table = table(ctx, width);
float height = table.headerHeight();
for (List<String> row : rows) {
height += table.rowHeight(row);
}
return height;
}
@Override
public float draw(PdfContext ctx, float x, float yTop, float width) throws IOException {
return table(ctx, width).draw(ctx.content(), rows, x, yTop);
}
/** Instead of "all or nothing", the table is paginated row by row. */
@Override
public void place(PdfContext ctx) throws IOException {
table(ctx, ctx.box().width()).drawPaginated(ctx.paginator(), rows, runningTotal);
}
}It's an adapter: it doesn't reimplement anything, it translates the Block contract into Table's API. height and draw let you use a small table inside other blocks (the VAT breakdown in the next lesson), and place takes advantage of drawPaginated for large tables.
ParagraphBlock: label and justified text
/** Optional label (in capitals, theme colour) and a justified paragraph below it. */
public final class ParagraphBlock implements Block {
private final String label; // may be null
private final String text;
public ParagraphBlock(String label, String text) {
this.label = label;
this.text = text == null ? "" : text;
}
@Override
public float height(PdfContext ctx, float width) throws IOException {
float height = 0;
if (label != null) {
height += label(ctx, width).measureHeight(clean(ctx.fonts().bold(), label)) + Measures.mm(1.5);
}
return height + paragraph(ctx, width).measureHeight(clean(ctx.fonts().regular(), text));
}
@Override
public float draw(PdfContext ctx, float x, float yTop, float width) throws IOException {
PDPageContentStream cs = ctx.content();
float y = yTop;
if (label != null) {
cs.saveGraphicsState();
cs.setNonStrokingColor(ctx.theme().primary());
y -= label(ctx, width).draw(cs, clean(ctx.fonts().bold(), label), x, y);
cs.restoreGraphicsState();
y -= Measures.mm(1.5);
}
y -= paragraph(ctx, width).draw(cs, clean(ctx.fonts().regular(), text), x, y);
return yTop - y;
}
private static TextBlock label(PdfContext ctx, float width) throws IOException {
return new TextBlock(ctx.fonts().bold(), ctx.theme().labelSize(), width);
}
private static TextBlock paragraph(PdfContext ctx, float width) throws IOException {
return new TextBlock(ctx.fonts().regular(), ctx.theme().smallSize(), width)
.alignment(Alignment.JUSTIFIED).lineSpacing(1.35f);
}
/** Sanitizes each paragraph separately (split on "\r?\n" and join with '\n') to keep the line breaks. */
private static String clean(PDFont font, String text) throws IOException { /* ... */ }
}Notice the pattern that every block will repeat: height and draw build their TextBlocks with the same private methods (label, paragraph), so measuring and drawing never get out of sync. Sanitizing by paragraph is necessary because sanitize turns \n into spaces: if we sanitized the whole text, we'd lose the separation between paragraphs.
ColumnsBlock: composing blocks side by side
/** Two blocks side by side; it's as tall as the taller of the two. */
public final class ColumnsBlock implements Block {
private final Block left;
private final Block right;
private final float leftFraction; // 0.5 = half and half
private final float gap;
// constructor that assigns the four fields
private float leftWidth(float width) { return (width - gap) * leftFraction; }
private float rightWidth(float width) { return width - gap - leftWidth(width); }
@Override
public float height(PdfContext ctx, float width) throws IOException {
return Math.max(left.height(ctx, leftWidth(width)), right.height(ctx, rightWidth(width)));
}
@Override
public float draw(PdfContext ctx, float x, float yTop, float width) throws IOException {
float a = left.draw(ctx, x, yTop, leftWidth(width));
float b = right.draw(ctx, x + leftWidth(width) + gap, yTop, rightWidth(width));
return Math.max(a, b);
}
}This is the Composite pattern: a block made of blocks, which behaves like any other block. Because x and width are parameters, ColumnsBlock doesn't need to know what's inside each column.
BarcodeBlock: a right-aligned Code 128
It wraps PdfCodes from the previous lesson. Its height is fixed (bars + human-readable text) and it's aligned to the right edge of the width it receives:
@Override
public float draw(PdfContext ctx, float x, float yTop, float width) throws IOException {
float codeWidth = PdfCodes.code128Width(value, MODULE); // MODULE = 0.33 mm
float xCode = x + width - codeWidth; // flush with the right edge
PdfCodes.drawCode128(ctx.content(), value, xCode, yTop, MODULE, BAR_HEIGHT);
PDFont f = ctx.fonts().regular();
float yText = yTop - BAR_HEIGHT - Measures.mm(1) - TextMetrics.ascent(f, TEXT_SIZE);
TextMetrics.writeAligned(ctx.content(), f, TEXT_SIZE, InvoiceLabFonts.sanitize(f, value),
xCode + codeWidth / 2, yText, Alignment.CENTER);
return height(ctx, width); // bars + 1 mm + line of text
}The common skeleton: BaseGenerator and the template method pattern
Now we write the infrastructure once. BaseGenerator implements generate with all the delicate steps in the right order, and leaves "gaps" (abstract methods) for whatever changes in each document. This is the template method pattern:
package com.invoicelab.generator;
import com.invoicelab.pdf.Paginator;
import com.invoicelab.pdf.PageFooter;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
/**
* Common skeleton of all generators ("template method" pattern):
* validate → create document and context → compose pages → number footers → save to memory.
*/
public abstract class BaseGenerator<T> implements DocumentGenerator<T> {
private final Theme theme;
protected BaseGenerator(Theme theme) {
this.theme = theme;
}
@Override
public final byte[] generate(T data) throws IOException {
validate(data); // 1) data errors, before anything else
try (PDDocument document = new PDDocument()) {
PdfContext ctx = new PdfContext(document, theme);
try (Paginator paginator = new Paginator(document, PDRectangle.A4, PageFooter.HEIGHT,
firstPageHeader(ctx, data), nextPagesHeader(ctx, data))) {
ctx.usePaginator(paginator);
paginator.newPage();
compose(ctx, data); // 2) the document's own content
} // 3) last page's stream closed
PageFooter.numberPages(document, ctx.fonts(), footerText(data)); // 4) second pass
ByteArrayOutputStream out = new ByteArrayOutputStream();
document.save(out); // 5) to memory
return out.toByteArray();
}
}
/** Checks the data; throws IllegalArgumentException with a clear message if something is wrong. */
protected void validate(T data) {
if (data == null) {
throw new IllegalArgumentException("There is no data to generate");
}
}
protected abstract Paginator.PageHeader firstPageHeader(PdfContext ctx, T data) throws IOException;
protected abstract Paginator.PageHeader nextPagesHeader(PdfContext ctx, T data) throws IOException;
/** Places the document's blocks. The first page has already been created. */
protected abstract void compose(PdfContext ctx, T data) throws IOException;
protected abstract String footerText(T data);
}sequenceDiagram
participant C as Generator client
participant B as BaseGenerator
participant S as Subclass (e.g. DeliveryNoteGenerator)
participant P as Paginator
C->>B: generate(data)
B->>S: validate(data)
B->>S: firstPageHeader / nextPagesHeader
B->>P: new Paginator(...) + newPage()
B->>S: compose(ctx, data)
S->>P: ctx.place(blocks...)
B->>P: close()
B->>S: footerText(data)
B->>B: PageFooter.numberPages + save
B-->>C: byte[]
generateisfinal: no subclass can alter the order of the steps (and therefore forget to close the paginator or number the pages).- Subclasses only implement what's specific: headers, content and footer text, and optionally refine
validateby callingsuper.validate(data). ByteArrayOutputStreamcollects the PDF in memory;PDDocument.save(OutputStream)works just as it does with a file.
Handling errors and resources
A generator will run thousands of times in production. These are its rules:
| Situation | Handling | Where |
|---|---|---|
| Invalid data (no lines, malformed number) | IllegalArgumentException with a clear message, before creating the document |
validate |
| Data with characters that can't be rendered | Sanitized; doesn't stop generation | sanitize in each block |
| Impossible content (a row taller than a page) | IllegalStateException with the row number |
Paginator, Table |
| I/O failure (font not found on the classpath) | IOException propagated upwards |
InvoiceLabFonts, Images |
| Any exception halfway through generation | The try-with-resources blocks close the paginator and the document; nothing is written to disk |
BaseGenerator, generate(data, path) |
Validating at the start has an additional advantage: the error happens in milliseconds and with a business message ("Delivery note A-2026-0001 has no lines") instead of a deep PDFBox exception after three pages have been drawn.
Class diagram
classDiagram
class DocumentGenerator~T~ {
<<interface>>
+generate(T) byte[]
+generate(T, Path)
}
class BaseGenerator~T~ {
<<abstract>>
-Theme theme
+generate(T) byte[]
#validate(T)
#firstPageHeader(PdfContext, T)*
#nextPagesHeader(PdfContext, T)*
#compose(PdfContext, T)*
#footerText(T)*
}
class DeliveryNoteGenerator
class InvoiceGenerator
class PdfContext {
+document() PDDocument
+fonts() InvoiceLabFonts
+theme() Theme
+image(String) PDImageXObject
+paginator() Paginator
+place(Block...)
}
class Theme {
<<record>>
+nebula()$ Theme
+tableStyle(InvoiceLabFonts) Style
}
class Block {
<<interface>>
+height(PdfContext, float) float
+draw(PdfContext, float, float, float) float
+place(PdfContext)
}
class TableBlock
class ParagraphBlock
class ColumnsBlock
class BarcodeBlock
class TotalsBlock
class Paginator
class PageFooter
class InvoiceHeader
DocumentGenerator <|.. BaseGenerator
BaseGenerator <|-- DeliveryNoteGenerator
BaseGenerator <|-- InvoiceGenerator
BaseGenerator ..> PdfContext : creates
BaseGenerator ..> PageFooter : numbers
PdfContext o-- Theme
PdfContext o-- Paginator
Block <|.. TableBlock
Block <|.. ParagraphBlock
Block <|.. ColumnsBlock
Block <|.. BarcodeBlock
Block <|.. TotalsBlock
ColumnsBlock o-- Block : 2
DeliveryNoteGenerator ..> InvoiceHeader : headers
InvoiceGenerator ..> InvoiceHeader : headers
InvoiceGenerator and TotalsBlock already appear in the diagram because they're the goal of the next lesson. InvoiceHeader and PageFooter aren't blocks: the header is drawn as a page header (through the paginator) and the footer as page decoration in the second pass. They don't "flow" with the content; instead, they occupy a fixed position on every page.
Reuse: the delivery note generator
Now for the acid test. A delivery note travels with the goods: it states what is being delivered and to whom, without prices (an "unpriced" delivery note). We create its model, which reuses Customer and InvoiceLine:
package com.invoicelab.model;
/** Delivery note (unpriced): what is delivered, to whom and when. Reuses InvoiceLine. */
public record DeliveryNote(String number, LocalDate date, String order, Customer issuer, Customer recipient,
List<InvoiceLine> lines, String notes) {
public DeliveryNote {
Objects.requireNonNull(number, "number");
// ... same for date, issuer and recipient ...
lines = List.copyOf(lines);
notes = notes == null ? "" : notes;
}
}The delivery note's header is the same as the invoice's except for the title. Instead of copying InvoiceHeader, we add a constructor with a title (the original still works and uses "INVOICE"):
private final String title;
public InvoiceHeader(InvoiceLabFonts fonts, PDImageXObject logo) {
this(fonts, logo, "INVOICE");
}
/** Same header with a different title ("DELIVERY NOTE", "QUOTE"...). */
public InvoiceHeader(InvoiceLabFonts fonts, PDImageXObject logo, String title) {
this.fonts = fonts;
this.logo = logo;
this.title = title;
}
// In draw: clean(bold, title) instead of "INVOICE"
// In drawCompact: clean(bold, title + " " + data.number()) + " (continued)"And the generator, which contains only what's specific to the delivery note:
package com.invoicelab.generator;
// imports: model (DeliveryNote, InvoiceLine), pdf (Alignment, InvoiceHeader, Column, Formats,
// Shapes, Measures, TextMetrics, Paginator), java.io.IOException, java.util (ArrayList, List)
/** Unpriced delivery note: reuses the header, table, paragraph and barcode. */
public final class DeliveryNoteGenerator extends BaseGenerator<DeliveryNote> {
public DeliveryNoteGenerator(Theme theme) {
super(theme);
}
@Override
protected void validate(DeliveryNote note) {
super.validate(note);
if (note.lines().isEmpty()) {
throw new IllegalArgumentException("Delivery note " + note.number() + " has no lines");
}
}
private static InvoiceHeader.Data headerData(DeliveryNote n) {
return new InvoiceHeader.Data(n.number(), Formats.date(n.date()),
n.issuer().lines(), n.recipient().lines());
}
private static InvoiceHeader header(PdfContext ctx) throws IOException {
return new InvoiceHeader(ctx.fonts(), ctx.image("/img/logo-nebula.png"), "DELIVERY NOTE");
}
@Override
protected Paginator.PageHeader firstPageHeader(PdfContext ctx, DeliveryNote n) throws IOException {
InvoiceHeader header = header(ctx);
return (cs, page, box, num) -> header.draw(cs, page.getMediaBox(), box, headerData(n));
}
@Override
protected Paginator.PageHeader nextPagesHeader(PdfContext ctx, DeliveryNote n) throws IOException {
InvoiceHeader header = header(ctx);
return (cs, page, box, num) -> header.drawCompact(cs, page.getMediaBox(), box, headerData(n));
}
@Override
protected void compose(PdfContext ctx, DeliveryNote n) throws IOException {
List<Column> columns = List.of(
Column.fixed("Ref.", Measures.mm(26), Alignment.LEFT),
Column.relative("Description", 1, Alignment.LEFT),
Column.fixed("Quantity", Measures.mm(20), Alignment.RIGHT),
Column.fixed("Checked", Measures.mm(20), Alignment.CENTER));
List<List<String>> rows = new ArrayList<>();
for (InvoiceLine l : n.lines()) {
rows.add(List.of(l.reference(), l.description(), Formats.quantity(l.quantity()), "☐"));
}
ctx.place(
new TableBlock(columns, rows, null),
new ColumnsBlock(
new ParagraphBlock("NOTES", "Customer order: " + n.order() + "\n" + n.notes()),
new BarcodeBlock(n.number()),
0.6f, Measures.mm(8)),
new SignaturesBlock());
}
@Override
protected String footerText(DeliveryNote n) {
return n.issuer().companyName() + " · Delivery note " + n.number();
}
/** Two boxes for signatures: "Delivered by" and "Received in good order". */
private static final class SignaturesBlock implements Block {
private static final float HEIGHT = Measures.mm(28);
@Override
public float height(PdfContext ctx, float width) {
return HEIGHT;
}
@Override
public float draw(PdfContext ctx, float x, float yTop, float width) throws IOException {
float gap = Measures.mm(8);
float boxWidth = (width - gap) / 2;
String[] labels = { "DELIVERED BY (signature and date)", "RECEIVED IN GOOD ORDER (signature, stamp and ID)" };
for (int i = 0; i < 2; i++) {
float xr = x + i * (boxWidth + gap);
Shapes.drawBox(ctx.content(), xr, yTop - HEIGHT, boxWidth, HEIGHT, Measures.mm(2),
null, ctx.theme().lineColor(), 0.75f);
float yLabel = yTop - Measures.mm(3) - TextMetrics.ascent(ctx.fonts().bold(), 7);
ctx.content().saveGraphicsState();
ctx.content().setNonStrokingColor(ctx.theme().secondaryText());
TextMetrics.writeAligned(ctx.content(), ctx.fonts().bold(), 7, labels[i],
xr + Measures.mm(3), yLabel, Alignment.LEFT);
ctx.content().restoreGraphicsState();
}
return HEIGHT;
}
}
}Notice what doesn't appear: no PDDocument, no save, no try-with-resources, no page numbering. compose reads almost like a description of the document: a table, below it the notes with the barcode to their right, and below that the signature boxes. SignaturesBlock is so specific to the delivery note that it lives as a private nested class; if another document needed it, it would be moved to its own file. The "☐" checkbox (U+2610) exists in DejaVu Sans: the carrier ticks it by hand when checking each line.
The program that uses it:
package com.invoicelab.examples;
// imports: generator (DeliveryNoteGenerator, DocumentGenerator, Theme), model (DeliveryNote, Invoice),
// java.io.IOException, java.nio.file.Path
public class GenerateDeliveryNote {
public static void main(String[] args) throws IOException {
Invoice invoice = SampleData.invoice(14); // we reuse the sample lines
DeliveryNote note = new DeliveryNote("A-2026-0001", invoice.date(), "PED-7781",
SampleData.NEBULA, SampleData.HARDWARE, invoice.lines(),
"Deliver between 8:00 and 14:00. Unload at the rear door of the premises.");
DocumentGenerator<DeliveryNote> generator = new DeliveryNoteGenerator(Theme.nebula());
long start = System.nanoTime();
generator.generate(note, Path.of("output/A-2026-0001.pdf"));
System.out.printf("Delivery note generated in %d ms%n", (System.nanoTime() - start) / 1_000_000);
}
}The result has the same visual identity as the invoice (band, logo, "DELIVERY NOTE" title, issuer and customer), the 14-line table with its check box, the notes with the Code 128 for "A-2026-0001" on the right, the two signature boxes and the "Page 1 of 1" footer. If the delivery note had 60 lines, it would spill over onto several pages with the compact header without writing a single extra line. And CheckCodes from the previous lesson confirms that the barcode scans. (The 286 ms include the cold start of the JVM and of PDFBox; subsequent generations in the same process are much faster.)
Common Mistakes and Tips
- Sharing a
PdfContext,InvoiceLabFontsorPDImageXObjectbetween documents (for example, by storing it in a field of the generator). They belong to onePDDocument. The generator can keep theTheme(immutable) and must create the context on everygenerate. - Measuring and drawing with different configurations in a block. Use the same private methods to build the
TextBlocks inheightand indraw. - Letting a block decide its own
xor width by usingctx.box()insidedraw. Then it can't be composed into columns. Always use the parameters you receive. - Bypassing the template: creating the document by hand in a subclass "because it's a special case". If it really is, add a new "hook" method to
BaseGenerator. - Validating late. An exception after drawing three pages wastes work and gives confusing messages. Validate at the start.
- Writing directly to the final file. A failure halfway leaves a corrupt PDF under the proper name. Temporary file + atomic rename.
- Tip: create blocks as small, immutable objects (
finalfields and lists copied withList.copyOf). They're easy to test and to reuse.
Exercises
- Separator block. Create
SeparatorBlock, a 4 mm-tall block that draws a horizontal line in the theme's line colour, vertically centred. Use it in the delivery note between the table and the notes. - Economy theme. Create
Theme.economy(), designed for black-and-white printing that uses little toner: dark grey primary, black accent, very light grey soft background. Generate the delivery note with it. Which parts of the document change and which don't? Why? - Parallel generation. Generate 100 delivery notes (
A-2026-0001toA-2026-0100) with a 4-threadExecutorServiceand a singleDeliveryNoteGenerator. Is it safe? Reason it out based on which objects are shared between threads.
Solutions
Solution 1.
package com.invoicelab.generator;
import com.invoicelab.pdf.Shapes;
import com.invoicelab.pdf.Measures;
import java.io.IOException;
/** Thin horizontal line, centred in a 4 mm gap. */
public final class SeparatorBlock implements Block {
private static final float HEIGHT = Measures.mm(4);
@Override
public float height(PdfContext ctx, float width) {
return HEIGHT;
}
@Override
public float draw(PdfContext ctx, float x, float yTop, float width) throws IOException {
Shapes.horizontalLine(ctx.content(), x, x + width, yTop - HEIGHT / 2, 0.5f, ctx.theme().lineColor());
return HEIGHT;
}
}In compose: ctx.place(new TableBlock(...), new SeparatorBlock(), new ColumnsBlock(...), new SignaturesBlock());. There's no need to touch place: the default "all or nothing" behaviour is exactly what we want.
Solution 2.
public static Theme economy() {
return new Theme(Color.DARK_GRAY, Color.BLACK, new Color(0xF2, 0xF2, 0xF2),
NebulaColors.TEXT_GREY, NebulaColors.LINE_GREY,
9f, 7.5f, 7.5f, Measures.mm(6));
}All the pieces that read the theme change: the table header (dark grey), the zebra rows (very light grey), the paragraph labels and the signature boxes. The band and the text of InvoiceHeader and the footer don't change, because those module 2 classes still use NebulaColors directly. For a complete theme, you'd have to pass the theme (or its colours) to InvoiceHeader and PageFooter: that's the gradual adoption of the theme we talked about.
Solution 3.
DocumentGenerator<DeliveryNote> generator = new DeliveryNoteGenerator(Theme.nebula());
Invoice f = SampleData.invoice(14);
ExecutorService pool = Executors.newFixedThreadPool(4);
List<Future<byte[]>> results = new ArrayList<>();
for (int i = 1; i <= 100; i++) {
DeliveryNote note = new DeliveryNote(String.format("A-2026-%04d", i), f.date(), "PED-" + i,
SampleData.NEBULA, SampleData.HARDWARE, f.lines(), "");
results.add(pool.submit(() -> generator.generate(note)));
}
long bytes = 0;
for (Future<byte[]> r : results) {
bytes += r.get().length; // get() waits and rethrows the thread's exceptions
}
pool.shutdown();It's safe because the only things shared between threads are immutable or thread-safe: the DeliveryNoteGenerator only keeps a Theme (an immutable record), the models are records with immutable lists, and the static cache in InvoiceLabFonts stores byte[] in a ConcurrentHashMap. Everything mutable (PDDocument, PdfContext, Paginator, the PDType0Fonts, the logo) is created inside each call to generate and never leaves its thread. If someone added a PdfContext field to the generator "to reuse it", they'd break this guarantee.
Conclusion
You've gone from having loose pieces to having an architecture. The model calculates, the generator lays out and the primitives in com.invoicelab.pdf draw. DocumentGenerator<T> is the common contract (bytes in memory and atomic writing to disk); PdfContext gathers what belongs to a document (fonts, images, paginator, theme); Theme centralises styles; the Block interface (measure, draw from a top edge, place itself with or without a page break) lets you compose documents with blocks such as TableBlock, ParagraphBlock, ColumnsBlock and BarcodeBlock; and BaseGenerator encloses in a template method the delicate steps that every example used to repeat. The delivery note has shown that a new document costs little more than describing its blocks.
In the next lesson you'll put all of this to work in the module's capstone project: InvoiceGenerator, which assembles the header, the multipage table with "Carried forward", the totals block with the VAT breakdown by rate, the payment terms, the verification QR code and the paginated footer, to generate the complete invoice F-2026-0001.
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
