It's time to wrap up the module with the capstone project. You have a model that calculates amounts and VAT, a table that spreads across pages, full and compact headers, numbered footers, vector QR codes and a generator architecture with composable blocks. In this lesson you'll build InvoiceGenerator, which assembles all those pieces into Nebula Distribution's invoice F-2026-0001: a header with the issuer's and customer's details, a multipage line-item table with "Carried forward", a totals block with the VAT breakdown by rate (21 %, 10 % and 4 %), payment terms, a verification QR code and a "Page X of N" footer. Along the way you'll come across a real layout problem (a QR code left on its own on a page) and solve it with a new composite block. You'll finish with a visual review checklist and the final project structure.

Contents

  1. What we're going to build
  2. The missing pieces
  3. The totals block with the VAT breakdown
  4. The verification QR code block
  5. InvoiceGenerator: validate, headers and compose
  6. A real problem: the orphan QR code and StackBlock
  7. The main program
  8. Results with 12, 30 and 80 lines
  9. Visual review checklist
  10. Final project structure

What we're going to build

flowchart TB
    subgraph P1["Page 1"]
        direction TB
        C["Full header: band, logo, INVOICE No., date, issuer and customer"]
        T1["Line-item table (blue header, zebra)"]
        S1["Carried forward"]
        F1["Footer: Nebula Distribution Ltd. · VAT ID · Invoice F-2026-0001 ......... Page 1 of N"]
        C --> T1 --> S1 --> F1
    end
    subgraph PN["Last page"]
        direction TB
        R["Compact header: INVOICE F-2026-0001 (continued)"]
        T2["Table: Brought forward + remaining lines"]
        subgraph COL["Two columns"]
            direction LR
            IZ["PAYMENT TERMS<br/>+ verification QR code"] ~~~ DE["VAT breakdown by rate<br/>Taxable base · Total VAT<br/>INVOICE TOTAL (orange)"]
        end
        FN["Footer: ......... Page N of N"]
        R --> T2 --> COL --> FN
    end
    P1 --> PN

Document requirements:

Requirement Piece that solves it Lesson
Visual identity, issuer and customer InvoiceHeader + Data.of(invoice) 02-06, 03-01
Compact header on pages 2+ InvoiceHeader.drawCompact 03-02
Lines with aligned amounts Table + Formats 03-01
Table over several pages, without splitting rows, "Carried forward" TableBlock → Table.drawPaginated 03-02, 03-04
VAT breakdown by rate, base, VAT and total Invoice.vatBreakdown() + TotalsBlock 03-01, this one
Payment terms ParagraphBlock 03-04
Verification QR code PdfCodes + QrBlock 03-03, this one
Totals and QR code never split Block.place + Paginator.ensure 03-02, 03-04
"Page X of N" PageFooter.numberPages (inside BaseGenerator) 03-02, 03-04

The missing pieces

Almost everything already exists. We only need two new blocks in com.invoicelab.generator:

  • TotalsBlock: the VAT breakdown, the taxable base, the total VAT and the highlighted total.
  • QrBlock: the verification QR code with an explanatory text beside it.

And, as you'll see in section 6, a third one we weren't expecting: StackBlock.

The totals block with the VAT breakdown

On an invoice with several VAT rates, you have to state the taxable base and the tax amount for each rate. Our block shows this as a small table, followed by the totals:

┌───────────┬────────────────┬────────────┐
│ VAT rate  │   Taxable base │        Tax │   ← reuses Table (blue header, zebra)
├───────────┼────────────────┼────────────┤
│ 21 %      │     2.378,55 € │   499,50 € │
│ 10 %      │       107,10 € │    10,71 € │
│ 4 %       │     1.152,00 € │    46,08 € │
└───────────┴────────────────┴────────────┘
  Taxable base                  3.637,65 €
  Total VAT                       556,29 €
╭─────────────────────────────────────────╮
│ INVOICE TOTAL               4.193,94 €  │   ← orange background, white text
╰─────────────────────────────────────────╯

Here you can see the advantage of Table receiving text and knowing nothing about invoices: the breakdown is another instance of Table, with three relative columns.

package com.invoicelab.generator;

// imports: model.Invoice, pdf (Alignment, Column, Formats, Shapes, Measures, TextMetrics, Table),
// java.awt.Color, java.io.IOException, java.util (ArrayList, List), PDPageContentStream, PDFont

/**
 * VAT breakdown by rate (reuses Table) + taxable base, total VAT and highlighted TOTAL.
 * It's aligned to the right of the space it receives and is never split across pages.
 */
public final class TotalsBlock implements Block {

    private static final float MAX_WIDTH = Measures.mm(85);
    private static final float LINE_HEIGHT = Measures.mm(5.5);
    private static final float TOTAL_HEIGHT = Measures.mm(9);

    private final Invoice invoice;

    public TotalsBlock(Invoice invoice) {
        this.invoice = invoice;
    }

    private Table breakdown(PdfContext ctx, float width) throws IOException {
        return new Table(List.of(
                Column.relative("VAT rate", 1, Alignment.LEFT),
                Column.relative("Taxable base", 1.6f, Alignment.RIGHT),
                Column.relative("Tax", 1.3f, Alignment.RIGHT)),
                width, ctx.theme().tableStyle(ctx.fonts()));
    }

    private List<List<String>> breakdownRows() {
        List<List<String>> rows = new ArrayList<>();
        for (Invoice.VatLine d : invoice.vatBreakdown()) {
            rows.add(List.of(Formats.percentage(d.rate()), Formats.euros(d.base()), Formats.euros(d.tax())));
        }
        return rows;
    }

    @Override
    public float height(PdfContext ctx, float width) throws IOException {
        float blockWidth = Math.min(width, MAX_WIDTH);
        Table table = breakdown(ctx, blockWidth);
        float height = table.headerHeight();
        for (List<String> row : breakdownRows()) {
            height += table.rowHeight(row);
        }
        return height + Measures.mm(2) + 2 * LINE_HEIGHT + Measures.mm(1.5) + TOTAL_HEIGHT;
    }

    @Override
    public float draw(PdfContext ctx, float x, float yTop, float width) throws IOException {
        PDPageContentStream cs = ctx.content();
        float blockWidth = Math.min(width, MAX_WIDTH);
        float xBlock = x + width - blockWidth;                   // right-aligned
        float right = xBlock + blockWidth - Measures.mm(1.6);
        PDFont normal = ctx.fonts().regular();
        PDFont bold = ctx.fonts().bold();
        float size = ctx.theme().textSize();

        // 1) Breakdown by rate: a small Table
        float y = yTop;
        y -= breakdown(ctx, blockWidth).draw(cs, breakdownRows(), xBlock, y);
        y -= Measures.mm(2);

        // 2) Taxable base and total VAT: label on the left, amount on the right
        String[][] summaryLines = {
                { "Taxable base", Formats.euros(invoice.taxableBase()) },
                { "Total VAT", Formats.euros(invoice.totalVat()) } };
        for (String[] r : summaryLines) {
            float yBase = y - LINE_HEIGHT / 2 - TextMetrics.capHeight(normal, size) / 2;
            TextMetrics.writeAligned(cs, normal, size, r[0], xBlock + Measures.mm(1.6), yBase, Alignment.LEFT);
            TextMetrics.writeAligned(cs, normal, size, r[1], right, yBase, Alignment.RIGHT);
            y -= LINE_HEIGHT;
        }
        y -= Measures.mm(1.5);

        // 3) TOTAL on an orange background, white text
        Shapes.drawBox(cs, xBlock, y - TOTAL_HEIGHT, blockWidth, TOTAL_HEIGHT, Measures.mm(1.5),
                ctx.theme().accent(), null, 0);
        float yTotal = y - TOTAL_HEIGHT / 2 - TextMetrics.capHeight(bold, 11) / 2;
        cs.saveGraphicsState();
        cs.setNonStrokingColor(Color.WHITE);
        TextMetrics.writeAligned(cs, bold, 11, "INVOICE TOTAL", xBlock + Measures.mm(3), yTotal,
                Alignment.LEFT);
        TextMetrics.writeAligned(cs, bold, 11, Formats.euros(invoice.total()),
                xBlock + blockWidth - Measures.mm(3), yTotal, Alignment.RIGHT);
        cs.restoreGraphicsState();
        y -= TOTAL_HEIGHT;
        return yTop - y;
    }
}

Worth highlighting:

  • No calculations: all the amounts come from Invoice (vatBreakdown, taxableBase, totalVat, total). The block only formats and positions. If the rounding method changes tomorrow, the PDF changes without touching this code.
  • Vertical centring with the cap height (lesson 02-04): on each line and on the orange band, the baseline is calculated so that the figures look visually centred: centre − capHeight / 2.
  • A maximum width of 85 mm, right-aligned: if the block receives the whole box (174 mm), it doesn't stretch; if it receives half a column, it fills it. It's a block that adapts to the width it's given, as the contract requires.
  • height reproduces the geometry of draw by adding up the same constants. That way place can decide whether it fits, and the block is never split across pages: a total separated from its breakdown would be a serious error on an invoice.

The verification QR code block

The QR code comes with a brief explanation, vertically centred relative to the code:

package com.invoicelab.generator;

// imports: pdf (TextBlock, PdfCodes, InvoiceLabFonts, Measures), ErrorCorrectionLevel,
// java.io.IOException, PDFont

/** QR code on the left and an explanatory text on its right, vertically centred with the QR code. */
public final class QrBlock implements Block {

    private static final float SIDE = Measures.mm(26);
    private static final float GAP = Measures.mm(4);

    private final String qrContent;
    private final String explanation;

    public QrBlock(String qrContent, String explanation) {
        this.qrContent = qrContent;
        this.explanation = explanation;
    }

    private TextBlock text(PdfContext ctx, float width) throws IOException {
        return new TextBlock(ctx.fonts().regular(), ctx.theme().smallSize(), width - SIDE - GAP)
                .lineSpacing(1.35f);
    }

    @Override
    public float height(PdfContext ctx, float width) throws IOException {
        return Math.max(SIDE, text(ctx, width).measureHeight(clean(ctx)));
    }

    @Override
    public float draw(PdfContext ctx, float x, float yTop, float width) throws IOException {
        PdfCodes.drawQr(ctx.content(), qrContent, ErrorCorrectionLevel.M, x, yTop, SIDE);
        TextBlock block = text(ctx, width);
        float textHeight = block.measureHeight(clean(ctx));
        float yText = yTop - Math.max(0, (SIDE - textHeight) / 2);            // centred with the QR code
        ctx.content().saveGraphicsState();
        ctx.content().setNonStrokingColor(ctx.theme().secondaryText());
        block.draw(ctx.content(), clean(ctx), x + SIDE + GAP, yText);
        ctx.content().restoreGraphicsState();
        return height(ctx, width);
    }

    private String clean(PdfContext ctx) throws IOException {
        PDFont f = ctx.fonts().regular();
        return InvoiceLabFonts.sanitize(f, explanation);
    }
}

The 26 mm side includes the quiet zone (lesson 03-03): with level M and our URL (41 modules + 8 of quiet zone), each module measures 0.53 mm, comfortable for any phone. If the text is taller than the QR code, the block is as tall as the text; if it's shorter, the text is centred.

InvoiceGenerator: validate, headers and compose

With the pieces ready, the generator is a subclass of BaseGenerator<Invoice> that only describes what's specific to the invoice:

package com.invoicelab.generator;

// imports: model (Invoice, InvoiceLine), pdf (Alignment, InvoiceHeader, Column, Formats,
// Measures, Paginator), java.io.IOException, java.math.BigDecimal, java.net.URLEncoder,
// java.nio.charset.StandardCharsets, java.time.format.DateTimeFormatter, java.util (ArrayList, List)

/** Generates the complete PDF of a Nebula Distribution invoice. */
public final class InvoiceGenerator extends BaseGenerator<Invoice> {

    private static final String LOGO = "/img/logo-nebula.png";
    private static final String VERIFICATION_URL = "https://verifica.example/f";

    private static final List<Column> COLUMNS = List.of(
            Column.fixed("Ref.", Measures.mm(24), Alignment.LEFT),
            Column.relative("Description", 1, Alignment.LEFT),
            Column.fixed("Qty", Measures.mm(14), Alignment.RIGHT),
            Column.fixed("Price", Measures.mm(20), Alignment.RIGHT),
            Column.fixed("VAT", Measures.mm(13), Alignment.RIGHT),
            Column.fixed("Amount", Measures.mm(24), Alignment.RIGHT));

    public InvoiceGenerator(Theme theme) {
        super(theme);
    }

    // ------------------------------------------------------------------ 1. validate

    @Override
    protected void validate(Invoice invoice) {
        super.validate(invoice);
        if (!invoice.number().matches("F-\\d{4}-\\d{4}")) {
            throw new IllegalArgumentException("Malformed invoice number: " + invoice.number());
        }
        if (invoice.total().signum() <= 0) {
            throw new IllegalArgumentException("Invoice " + invoice.number() + " has a zero or negative total");
        }
    }

    // ------------------------------------------------------------------ 2. headers

    @Override
    protected Paginator.PageHeader firstPageHeader(PdfContext ctx, Invoice f) throws IOException {
        InvoiceHeader header = new InvoiceHeader(ctx.fonts(), ctx.image(LOGO));
        InvoiceHeader.Data data = InvoiceHeader.Data.of(f);
        return (cs, page, box, n) -> header.draw(cs, page.getMediaBox(), box, data);
    }

    @Override
    protected Paginator.PageHeader nextPagesHeader(PdfContext ctx, Invoice f) throws IOException {
        InvoiceHeader header = new InvoiceHeader(ctx.fonts(), ctx.image(LOGO));
        InvoiceHeader.Data data = InvoiceHeader.Data.of(f);
        return (cs, page, box, n) -> header.drawCompact(cs, page.getMediaBox(), box, data);
    }

    // ------------------------------------------------------------------ 3. compose (see section 6)

    @Override
    protected String footerText(Invoice f) {
        return f.issuer().companyName() + " · VAT ID " + f.issuer().taxId() + " · Invoice " + f.number();
    }

    // ------------------------------------------------------------------ helpers

    static List<List<String>> rows(Invoice f) {
        List<List<String>> rows = new ArrayList<>();
        for (InvoiceLine l : f.lines()) {
            rows.add(List.of(l.reference(), l.description(), Formats.quantity(l.quantity()),
                    Formats.price(l.unitPrice()), Formats.percentage(l.vatRate()),
                    Formats.euros(l.amount())));
        }
        return rows;
    }

    /** cumulative[n] = sum of the amounts of the first n lines (for "Carried forward"). */
    static BigDecimal[] partialSums(Invoice f) {
        BigDecimal[] cumulative = new BigDecimal[f.lines().size() + 1];
        cumulative[0] = BigDecimal.ZERO;
        for (int i = 0; i < f.lines().size(); i++) {
            cumulative[i + 1] = cumulative[i].add(f.lines().get(i).amount());
        }
        return cumulative;
    }

    /** Fictitious verification URL with the invoice's key data. */
    static String verificationUrl(Invoice f) {
        return VERIFICATION_URL
                + "?nif=" + encode(f.issuer().taxId())
                + "&num=" + encode(f.number())
                + "&fecha=" + f.date().format(DateTimeFormatter.ofPattern("dd-MM-yyyy"))
                + "&importe=" + f.total().toPlainString();
    }

    private static String encode(String value) {
        return URLEncoder.encode(value, StandardCharsets.UTF_8);
    }
}

Code details:

  • The columns and the conversion to rows have been moved here from the InvoiceTableOnePage example class: they're now part of the invoice generator rather than an example.
  • validate checks rules that the Invoice record doesn't enforce: the number's format (series "F", year, four digits) and that the total is positive. Your real rules will depend on your numbering scheme and your tax advisor.
  • verificationUrl builds the URL from the model: the amount comes from f.total() and is written with toPlainString() (decimal point, no scientific notation), which is the norm for URL parameters. The text values are encoded with URLEncoder in case they contain spaces or special characters. The URL is fictitious; remember the warning in lesson 03-03 about real verification systems.
  • The headers create the InvoiceHeader with the logo from the context, which loads it only once even though it's used on page 1 and on the compact pages.

A real problem: the orphan QR code and StackBlock

The first version of compose placed the blocks one below the other: the table, then the terms next to the totals, and finally the QR code:

// First version
ctx.place(
        new TableBlock(COLUMNS, rows(f), n -> Formats.euros(cumulative[n])),
        new ColumnsBlock(
                new ParagraphBlock("PAYMENT TERMS", f.paymentTerms()),
                new TotalsBlock(f),
                0.45f, Measures.mm(8)),
        new QrBlock(verificationUrl(f), "Invoice verification: ..."));

With 30 lines the result was correct. But when testing with 12 lines (always test several sizes!) this appeared: the table, the terms and the totals fitted on page 1, but the QR code didn't, so place sent it on its own to a page 2, with its compact header and its "Page 2 of 2" footer. Technically correct; visually, a disaster: an almost empty page for one QR code.

Looking at the design, the left column (payment terms) was shorter than the right one (totals) and left a gap underneath. The QR code fits perfectly there, stacked below the terms. We need a block that stacks several blocks vertically and behaves as one: the natural counterpart to ColumnsBlock.

package com.invoicelab.generator;

import java.io.IOException;
import java.util.List;

/** Several blocks one below the other, treated as a single block that isn't split. */
public final class StackBlock implements Block {

    private final List<Block> blocks;
    private final float gap;

    public StackBlock(float gap, Block... blocks) {
        this.blocks = List.of(blocks);
        this.gap = gap;
    }

    @Override
    public float height(PdfContext ctx, float width) throws IOException {
        float height = 0;
        for (Block b : blocks) {
            height += b.height(ctx, width);
        }
        return height + gap * (blocks.size() - 1);
    }

    @Override
    public float draw(PdfContext ctx, float x, float yTop, float width) throws IOException {
        float y = yTop;
        for (int i = 0; i < blocks.size(); i++) {
            if (i > 0) {
                y -= gap;
            }
            y -= blocks.get(i).draw(ctx, x, y, width);
        }
        return yTop - y;
    }
}

And the final version of compose:

@Override
protected void compose(PdfContext ctx, Invoice f) throws IOException {
    BigDecimal[] cumulative = partialSums(f);
    Block termsAndQr = new StackBlock(Measures.mm(5),
            new ParagraphBlock("PAYMENT TERMS", f.paymentTerms()),
            new QrBlock(verificationUrl(f),
                    "Verification: scan the code or visit verifica.example with the issuer's VAT ID, "
                    + "the number, the date and the total amount. Fictitious service for training purposes."));
    ctx.place(
            new TableBlock(COLUMNS, rows(f), n -> Formats.euros(cumulative[n])),
            new ColumnsBlock(termsAndQr, new TotalsBlock(f), 0.5f, Measures.mm(8)));
}

Now the end of the invoice is a single two-column block: on the left, the terms and QR code stacked; on the right, the totals. place treats it as a unit: either it fits whole on the current page or it moves whole to the next one. With 12 lines, the invoice is back to a single page.

This is the payoff of the previous lesson's architecture: the fix didn't touch the paginator, the table or the existing blocks. All it took was one new 30-line piece and reordering the composition. And StackBlock is now available for any future document.

The main program

package com.invoicelab.examples;

import com.invoicelab.generator.DocumentGenerator;
import com.invoicelab.generator.InvoiceGenerator;
import com.invoicelab.generator.Theme;
import com.invoicelab.model.Invoice;
import com.invoicelab.pdf.Formats;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class GenerateFullInvoice {

    public static void main(String[] args) throws IOException {
        int lineCount = args.length > 0 ? Integer.parseInt(args[0]) : 30;
        Invoice invoice = SampleData.invoice(lineCount);
        Path target = Path.of("output/" + invoice.number() + ".pdf");

        DocumentGenerator<Invoice> generator = new InvoiceGenerator(Theme.nebula());
        long start = System.nanoTime();
        generator.generate(invoice, target);
        long ms = (System.nanoTime() - start) / 1_000_000;

        System.out.printf("%s: %d lines, total %s%n", invoice.number(), invoice.lines().size(),
                Formats.euros(invoice.total()));
        System.out.printf("Generated in %d ms → %s (%,d bytes)%n", ms, target, Files.size(target));
    }
}

Run it with mvn compile exec:java -Dexec.mainClass=com.invoicelab.examples.GenerateFullInvoice (and add -Dexec.args=80 to try a different number of lines):

F-2026-0001: 30 lines, total 4.193,94 €
Generated in 378 ms → output/F-2026-0001.pdf (52,410 bytes)

Notice how little main does: create the data, create the generator with a theme and ask it for the PDF. All the complexity sits behind DocumentGenerator<Invoice>, which is exactly the interface we'll expose as a REST service in module 8.

Results with 12, 30 and 80 lines

Lines Pages Size What to look for
12 1 48,979 bytes Everything on one page: table, terms with QR code and totals
30 2 52,410 bytes "Carried forward 2.699,20 €" at the bottom of page 1; page 2 starts with "Brought forward" and ends with terms, QR code and totals
80 4 58,911 bytes Three table breaks; the final block fits on page 4

Two observations about file size: almost all of it is the subsets of the two DejaVu fonts and the logo, which are included only once; that's why 50 more lines add only about 10 KB. And with pdffonts output/F-2026-0001.pdf (from Poppler) or with PDFDebugger (lesson 01-05) you can check that there are exactly two fonts embedded as subsets (AAATGW+DejaVuSans and AAAMWL+DejaVuSans-Bold, with prefixes that will vary on your machine).

For the 30-line invoice, the printed totals are:

VAT rate     Taxable base        Tax
21 %           2.378,55 €   499,50 €
10 %             107,10 €    10,71 €
4 %            1.152,00 €    46,08 €
Taxable base                3.637,65 €
Total VAT                     556,29 €
INVOICE TOTAL               4.193,94 €

Check them: 2,378.55 + 107.10 + 1,152.00 = 3,637.65; 499.50 + 10.71 + 46.08 = 556.29; and 3,637.65 + 556.29 = 4,193.94. Finally, CheckCodes from lesson 03-03 confirms that the QR code scans:

Page 1: no readable code
Page 2: QR_CODE -> https://verifica.example/f?nif=B00000000&num=F-2026-0001&fecha=15-01-2026&importe=4193.94

Visual review checklist

Before signing off an invoice template, review the PDF both printed and on screen with this checklist. Many faults only show up with certain data, so do it with 1, 12, 30 and 80 lines and with a customer whose name and address are very long:

# Check How
1 Nothing spills out of the content box (18 mm at the sides, 20 mm top and bottom) -Dinvoicelab.grid=true
2 Number, date, issuer and customer correct and complete Compare with the model
3 Amounts right-aligned, decimal commas in a column, 1.234,56 € format Visual
4 No row split across pages; table header repeated Invoices with 30 and 80 lines
5 One page's "Carried forward" = the next page's "Brought forward" Visual
6 Breakdown sum = taxable base; base + VAT = total Calculator
7 Totals never separated from their breakdown or alone on a page Try several line counts
8 "Page X of N" correct on every page Visual
9 QR code readable with a phone and with CheckCodes; quiet zone respected Phone + automated test
10 Accents, special letters and symbols (€, º, ², «») correct Data with special characters
11 Text selectable and copyable (not images) Select with the mouse in the viewer
12 Fonts embedded as subsets, logo only once pdffonts or PDFDebugger
13 Reads well when printed in black and white Print in greyscale
14 Opens without warnings in several viewers (Acrobat Reader, browser, system viewer) Open it in each one

Final project structure

invoicelab/
├── pom.xml                                ← pdfbox ${pdfbox.version}, zxing core/javase ${zxing.version}
├── output/                                ← generated PDFs (not committed to the repository)
└── src/main/
    ├── java/com/invoicelab/
    │   ├── model/                         ← data and calculations, no PDF
    │   │   ├── Customer.java
    │   │   ├── InvoiceLine.java
    │   │   ├── Invoice.java               (taxableBase, vatBreakdown, totalVat, total)
    │   │   └── DeliveryNote.java
    │   ├── pdf/                           ← reusable drawing primitives
    │   │   ├── Measures.java, ContentBox.java, ReferenceGrid.java         (02-01)
    │   │   ├── InvoiceLabFonts.java, FallbackText.java                    (02-03)
    │   │   ├── Alignment.java, TextMetrics.java, TextBlock.java           (02-04)
    │   │   ├── NebulaColors.java, Shapes.java                             (02-05)
    │   │   ├── Images.java, InvoiceHeader.java                            (02-06, 03-01, 03-02, 03-04)
    │   │   ├── Formats.java, Column.java, Table.java                      (03-01, 03-02)
    │   │   ├── Paginator.java, PageFooter.java                            (03-02)
    │   │   └── PdfCodes.java                                              (03-03)
    │   ├── generator/                     ← document architecture
    │   │   ├── DocumentGenerator.java, BaseGenerator.java
    │   │   ├── PdfContext.java, Theme.java, Block.java
    │   │   ├── TableBlock.java, ParagraphBlock.java, ColumnsBlock.java, StackBlock.java
    │   │   ├── BarcodeBlock.java, QrBlock.java, TotalsBlock.java
    │   │   ├── DeliveryNoteGenerator.java
    │   │   └── InvoiceGenerator.java
    │   └── examples/                      ← each lesson's programs (SampleData, GenerateFullInvoice...)
    └── resources/
        ├── fonts/                         ← DejaVuSans.ttf, DejaVuSans-Bold.ttf, DejaVuSans-Oblique.ttf
        └── img/                           ← logo-nebula.png

The dependencies between packages follow the direction we designed: examples → generator → pdf → PDFBox, and model depends on nobody. The only deliberate exception is InvoiceHeader.Data.of(Invoice), a convenience you could move into the generator if you wanted a pdf package completely independent of the model.

Common Mistakes and Tips

  • Testing only with "nice" data. The orphan QR code only appeared with 12 lines. Test with 1 line, with exactly enough lines to fill a page, with lots of lines and with very long text.
  • Calculating totals in the block. If TotalsBlock added up the lines on its own, sooner or later it wouldn't match Invoice.total() (or the XML, the accounts or the QR code's URL). A single source of truth: the model.
  • The QR code's amount and the printed one differing because of formatting with different decimals or rounding twice. Both come from invoice.total().
  • Final blocks that get split or left on their own. Group whatever must stay together with ColumnsBlock and StackBlock, and let place treat it as a unit.
  • Forgetting that place adds the theme's spacing after each block: if you chain very small blocks and see too much white space, combine them in a StackBlock with its own gap.
  • Relying on on-screen review. Print at least once: light greys, 7 pt text and small QR codes behave differently on paper.
  • Tip: keep a reference PDF of each validated template. In module 8 we'll automate comparing new PDFs against that reference to detect unintended changes.

Exercises

  1. Optional terms. If invoice.paymentTerms() is empty, the invoice mustn't show an empty "PAYMENT TERMS" label; the QR code should take its place. Modify compose to build the stack dynamically.
  2. Due date. Add to TotalsBlock, between "Total VAT" and the orange total, a "Due date" line with the invoice date plus 30 days (for F-2026-0001: 14/02/2026). Remember to update height.
  3. Automated test. Write a JUnit 5 test that generates the invoice in memory with 12, 30 and 80 lines, loads it with Loader.loadPDF(byte[]) and checks that it has 1, 2 and 4 pages; and another that verifies that an invoice with the number "F-26-1" is rejected with an IllegalArgumentException.

Solutions

Solution 1.

List<Block> left = new ArrayList<>();
if (!f.paymentTerms().isBlank()) {
    left.add(new ParagraphBlock("PAYMENT TERMS", f.paymentTerms()));
}
left.add(new QrBlock(verificationUrl(f), "Verification: ..."));
Block leftColumn = new StackBlock(Measures.mm(5), left.toArray(new Block[0]));

toArray(new Block[0]) turns the list into the array that the constructor's varargs expect. Since the Invoice record turns a null into "", isBlank() is enough. With a single piece in the stack, StackBlock adds no gap (gap × (1 − 1) = 0).

Solution 2. In draw, a third line is added to the array (and height now adds 3 * LINE_HEIGHT):

String[][] summaryLines = {
        { "Taxable base", Formats.euros(invoice.taxableBase()) },
        { "Total VAT", Formats.euros(invoice.totalVat()) },
        { "Due date", Formats.date(invoice.date().plusDays(30)) } };

LocalDate.plusDays(30) handles month and year changes by itself: 15/01/2026 + 30 days = 14/02/2026. In a real system, the term would come from the customer or the payment terms, and it would probably be a model field (Invoice.dueDate()) rather than a calculation in the block: it's a business rule.

Solution 3. With the junit-jupiter dependency we added in lesson 01-02, in src/test/java/com/invoicelab/generator/InvoiceGeneratorTest.java:

package com.invoicelab.generator;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;

import com.invoicelab.examples.SampleData;
import com.invoicelab.model.Invoice;
import java.io.IOException;
import org.apache.pdfbox.Loader;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;

class InvoiceGeneratorTest {

    private final InvoiceGenerator generator = new InvoiceGenerator(Theme.nebula());

    @ParameterizedTest
    @CsvSource({ "12, 1", "30, 2", "80, 4" })
    void pageCountDependsOnLines(int lines, int expectedPages) throws IOException {
        byte[] pdf = generator.generate(SampleData.invoice(lines));
        try (PDDocument document = Loader.loadPDF(pdf)) {
            assertEquals(expectedPages, document.getNumberOfPages());
        }
    }

    @Test
    void rejectsMalformedNumber() {
        Invoice valid = SampleData.invoice(3);
        Invoice invalid = new Invoice("F-26-1", valid.date(), valid.issuer(), valid.customer(),
                valid.lines(), valid.paymentTerms());
        assertThrows(IllegalArgumentException.class, () -> generator.generate(invalid));
    }
}

@ParameterizedTest with @CsvSource runs the same test with three pairs of values. Because generate returns byte[], the test doesn't touch the disk. In module 8 we'll extend these tests by extracting the PDF's text and comparing its visual appearance.

Conclusion

You've completed module 3 and, with it, InvoiceLab's invoice generator. InvoiceGenerator assembles the full and compact headers, the multipage line-item table with "Carried forward", the VAT breakdown by rate with the taxable base, the total VAT and the highlighted total, the payment terms, the verification QR code and the "Page X of N" footer, and it does so with very little code of its own because it builds on everything you've constructed: Table and Formats (03-01), Paginator and PageFooter (03-02), PdfCodes (03-03) and the architecture of BaseGenerator, PdfContext, Theme and composable blocks (03-04). You've also lived through a real layout cycle: testing with different data, finding a design flaw and fixing it with a new piece (StackBlock) without touching the existing ones, and you have a visual review checklist for validating any future template.

Now that InvoiceLab generates complete invoices, it's time for a change of perspective: in module 4 we'll learn to modify existing PDFs, starting with loading a document that has already been issued, changing it and saving it with a full or incremental save, and then applying to invoices that have already been sent stamps such as «PAID», watermarks, new pages or metadata without having to regenerate them.

PDF Generation and Editing with Apache PDFBox

Module 1: PDF and PDFBox Fundamentals

Module 2: Generating Content

Module 3: Business Documents

Module 4: Editing Existing PDFs

Module 5: AcroForm Forms

Module 6: Extraction and Analysis

Module 7: Security and Digital Signatures

Module 8: PDFBox in Production

© Copyright 2026. All rights reserved