By the end of module 2, Nebula Distribution's invoice already had a visual identity: a corporate band, a logo, a title, and the issuer's and customer's details. What it's still missing is the essential part: the lines with the products, quantities, prices and amounts. In a word processor you'd insert a table and be done; in PDFBox there's nothing of the sort. A PDF doesn't know what a table is: it only knows about text placed at coordinates, lines and coloured rectangles. In this lesson you'll build your own Table component on top of the previous module's pieces (TextBlock to measure and wrap text, Shapes for backgrounds and lines, TextMetrics for alignment) and, along the way, you'll create InvoiceLab's data model (Customer, InvoiceLine and Invoice), which will take care of calculating the taxable base, VAT and total. At the end you'll draw the line-item table of invoice F-2026-0001 on a single page.

Contents

  1. PDFBox has no tables: what that means in practice
  2. Anatomy of a table
  3. The invoice model: Customer, InvoiceLine and Invoice
  4. Formatting amounts, quantities and dates: the Formats utility
  5. Defining columns: fixed and relative widths
  6. Calculating the height of a row with multi-line text
  7. Drawing the table: header, zebra rows and lines
  8. The complete Table class
  9. The invoice's line-item table on one page
  10. What about table libraries?

PDFBox has no tables: what that means in practice

When you open a PDF invoice and see a table, what's actually in the content stream is something like this (simplified: with PDType0Font fonts the text appears as hexadecimal glyph codes, not readable text):

0.122 0.227 0.373 rg  51.02 552.4 493.23 19 re f     % blue header rectangle
BT /F1 8.5 Tf 1 1 1 rg 55.6 540.2 Td (Ref.) Tj ET     % white text "Ref."
BT /F1 8.5 Tf 1 1 1 rg 124.8 540.2 Td (Description) Tj ET
...
0.784 g 0.5 w 51.02 533.4 m 544.25 533.4 l S          % grey line under the row

There are no "cells", "rows" or "columns": just loose rectangles, pieces of text and lines that look like a table because they're neatly aligned. This has consequences:

  • You decide where each column starts and how wide it is.
  • You calculate how tall each row is, which depends on the cell with the most text.
  • You decide the drawing order: background first and text on top (otherwise the background hides the text).
  • If the text doesn't fit in the cell's width, it overflows: you have to wrap it onto several lines.

The good news is that you already have almost everything: TextBlock wraps text to a width and returns its height, TextMetrics aligns, and Shapes draws backgrounds and lines while saving the graphics state. A table is, above all, a matter of organising those pieces.

Anatomy of a table

flowchart TB
    subgraph T["Table (total width = content box width)"]
        direction TB
        C["Header row: BLUE background, bold white text"]
        F0["Row 0: no background · grey bottom line"]
        F1["Row 1: BACKGROUND_BLUE background (zebra) · grey bottom line"]
        F2["Row 2: no background · taller (description on 2 lines)"]
        C --> F0 --> F1 --> F2
    end
Concept What it is How we handle it
Column Title, width and alignment record Column
Fixed width Exact measurement in mm (amounts, quantities) Column.fixed(...)
Relative width Shares out the leftover space (description) Column.relative(...)
Padding Inner margin of each cell Style.padding
Row height Height of its tallest cell + 2 × padding TextBlock.measureHeight
Zebra Alternating background on odd rows to guide the eye Shapes.drawBox
Lines Horizontal separator under each row Shapes.horizontalLine

An important design decision: the table knows nothing about invoices. It receives rows of already formatted text (List<List<String>>). That way the same class will serve for the line-item table, for the VAT breakdown in lesson 03-05 and for the delivery note in lesson 03-04.

The invoice model: Customer, InvoiceLine and Invoice

Until now the invoice data was a set of loose strings. It's time to create the com.invoicelab.model package, which we announced in lesson 01-02. The golden rule is: money calculations live in the model, never in the drawing code. If tomorrow the invoice is also sent as XML or shown on a website, the amounts must be exactly the same.

We use Java 17 records, as we did with ContentBox: immutable, with a constructor, getters, equals and toString for free. In the compact constructor (the public Customer { ... } block without parameters) we validate the data.

package com.invoicelab.model;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/** A company's tax details: the invoice's customer (and, for now, the issuer as well). */
public record Customer(String companyName, String taxId, String address, String postalCode,
                       String city, String email) {

    public Customer {
        Objects.requireNonNull(companyName, "companyName");
        Objects.requireNonNull(taxId, "taxId");
        // ... same for address, postalCode and city; email is optional (may be null)
    }

    /** Lines ready to display in a data block: company name, VAT ID, address... */
    public List<String> lines() {
        List<String> lines = new ArrayList<>();
        lines.add(companyName);
        lines.add("VAT ID: " + taxId);
        lines.add(address);
        lines.add(postalCode + " " + city);
        if (email != null && !email.isBlank()) {
            lines.add(email);
        }
        return lines;
    }
}

We use the same record for the issuer's details (Nebula Distribution) and the customer's, because they contain the same information. If one day the issuer needs fields of its own (company registration, IBAN), it'll be split off into an Issuer.

The invoice line calculates its own amount. Note setScale(2, RoundingMode.HALF_UP): it rounds to cents using the "school" rounding everyone knows (0.005 rounds up).

package com.invoicelab.model;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Objects;

/** An invoice line: product, quantity, unit price excluding VAT and VAT rate (in %). */
public record InvoiceLine(String reference, String description, BigDecimal quantity,
                          BigDecimal unitPrice, BigDecimal vatRate) {

    public InvoiceLine {
        Objects.requireNonNull(reference, "reference");
        Objects.requireNonNull(description, "description");
        Objects.requireNonNull(quantity, "quantity");
        Objects.requireNonNull(unitPrice, "unitPrice");
        Objects.requireNonNull(vatRate, "vatRate");
        if (quantity.signum() <= 0) {
            throw new IllegalArgumentException("The quantity must be positive: " + quantity);
        }
        if (unitPrice.signum() < 0) {
            throw new IllegalArgumentException("The price cannot be negative: " + unitPrice);
        }
    }

    /** Line amount excluding VAT: quantity × price, rounded to cents. */
    public BigDecimal amount() {
        return quantity.multiply(unitPrice).setScale(2, RoundingMode.HALF_UP);
    }
}

And the invoice, which brings everything together and calculates the taxable base, the VAT breakdown by rate, the total VAT and the total:

package com.invoicelab.model;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.TreeMap;

/** A complete invoice. Calculations are done here, never in the drawing code. */
public record Invoice(String number, LocalDate date, Customer issuer, Customer customer,
                      List<InvoiceLine> lines, String paymentTerms) {

    /** One row of the VAT breakdown: rate (%), taxable base at that rate and resulting tax. */
    public record VatLine(BigDecimal rate, BigDecimal base, BigDecimal tax) {
    }

    private static final BigDecimal HUNDRED = new BigDecimal("100");

    public Invoice {
        Objects.requireNonNull(number, "number");
        Objects.requireNonNull(date, "date");
        Objects.requireNonNull(issuer, "issuer");
        Objects.requireNonNull(customer, "customer");
        lines = List.copyOf(lines);                // immutable copy: nobody can change it afterwards
        if (lines.isEmpty()) {
            throw new IllegalArgumentException("An invoice needs at least one line");
        }
        paymentTerms = paymentTerms == null ? "" : paymentTerms;
    }

    /** Sum of the amounts of all lines (excluding VAT). */
    public BigDecimal taxableBase() {
        return lines.stream().map(InvoiceLine::amount).reduce(BigDecimal.ZERO, BigDecimal::add);
    }

    /** Bases and tax grouped by VAT rate, from the highest rate to the lowest (21 %, 10 %, 4 %). */
    public List<VatLine> vatBreakdown() {
        Map<BigDecimal, BigDecimal> basesByRate = new TreeMap<>(Comparator.reverseOrder());
        for (InvoiceLine line : lines) {
            basesByRate.merge(line.vatRate(), line.amount(), BigDecimal::add);
        }
        List<VatLine> breakdown = new ArrayList<>();
        basesByRate.forEach((rate, base) -> breakdown.add(new VatLine(rate, base,
                base.multiply(rate).divide(HUNDRED, 2, RoundingMode.HALF_UP))));
        return breakdown;
    }

    /** Sum of the VAT amounts for all rates. */
    public BigDecimal totalVat() {
        return vatBreakdown().stream().map(VatLine::tax).reduce(BigDecimal.ZERO, BigDecimal::add);
    }

    /** Total amount payable: taxable base + VAT. */
    public BigDecimal total() {
        return taxableBase().add(totalVat());
    }
}

Key points for beginners:

  • List.copyOf(lines) inside the compact constructor reassigns the parameter with an immutable copy. If whoever created the invoice later modifies their list, the invoice doesn't change.
  • VAT is calculated per rate, not per line. The bases for each rate are added up first and the percentage is applied to the sum. Calculating and rounding VAT line by line can produce a difference of a cent or so; grouping by rate is standard practice on Spanish invoices. (Always check the calculation criteria with your tax advisor.)
  • TreeMap with Comparator.reverseOrder() sorts the rates from highest to lowest. What's more, TreeMap compares with compareTo, which considers 10 and 10.00 equal. A HashMap would use equals, which for BigDecimal takes the scale into account: 10 and 10.00 would be two different keys and the breakdown would come out duplicated.
  • merge(key, value, BigDecimal::add) adds the amount to the accumulated base for that rate, or creates it if it's the first line with that rate.

For the course examples we add the SampleData class in com.invoicelab.examples, with the two fictitious companies (constants NEBULA and HARDWARE), a PAYMENT_TERMS text and a small catalogue of ten products with VAT at 21 %, 10 % and 4 %. Its invoice(int lineCount) method creates invoice F-2026-0001 with as many lines as you ask for, cycling through the catalogue:

public static Invoice invoice(int lineCount) {
    List<InvoiceLine> lines = new ArrayList<>();
    for (int i = 0; i < lineCount; i++) {
        String[] p = CATALOGUE[i % CATALOGUE.length];            // { ref, description, price, VAT rate }
        BigDecimal quantity = BigDecimal.valueOf(1 + (i * 7) % 24);   // varied but fixed quantities
        lines.add(new InvoiceLine(p[0], p[1], quantity, new BigDecimal(p[2]), new BigDecimal(p[3])));
    }
    return new Invoice("F-2026-0001", LocalDate.of(2026, 1, 15), NEBULA, HARDWARE, lines,
            PAYMENT_TERMS);
}

Prices are created with new BigDecimal("18.40") (from text), never with new BigDecimal(18.40) (from a double), which would carry over the binary representation error: 18.39999999999999857891452847979962825775146484375.

Formatting amounts, quantities and dates: the Formats utility

In lesson 02-04 we formatted amounts with NumberFormat.getCurrencyInstance. Now we need several formats, always identical across all documents, so we centralise them in com.invoicelab.pdf.Formats:

package com.invoicelab.pdf;

import java.math.BigDecimal;
import java.text.NumberFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Locale;

/** Spanish formatting for amounts, quantities, percentages and dates. */
public final class Formats {

    public static final Locale ES = Locale.forLanguageTag("es-ES");
    private static final DateTimeFormatter DATE = DateTimeFormatter.ofPattern("dd/MM/yyyy", ES);

    private Formats() {
    }

    /** 1234.5 → "1.234,50 €" */
    public static String euros(BigDecimal amount) {
        NumberFormat nf = NumberFormat.getCurrencyInstance(ES);   // NumberFormat isn't thread-safe: one per call
        return nf.format(amount);
    }

    /** 12 → "12"; 2.5 → "2,5" (no unnecessary decimals). */
    public static String quantity(BigDecimal quantity) {
        NumberFormat nf = NumberFormat.getNumberInstance(ES);
        nf.setMaximumFractionDigits(3);
        return nf.format(quantity);
    }

    /** Unit price with 2 to 4 decimals: 0.1235 → "0,1235"; 3 → "3,00". */
    public static String price(BigDecimal price) {
        NumberFormat nf = NumberFormat.getNumberInstance(ES);
        nf.setMinimumFractionDigits(2);
        nf.setMaximumFractionDigits(4);
        return nf.format(price);
    }

    /** 21 → "21 %" (with a non-breaking space between the number and the symbol). */
    public static String percentage(BigDecimal rate) {
        return quantity(rate) + " %";
    }

    /** 2026-01-15 → "15/01/2026" */
    public static String date(LocalDate date) {
        return DATE.format(date);
    }
}
Method Input Output
euros 1470.85 1.470,85 €
quantity 12 / 2.5 12 / 2,5
price 18.4 18,40
percentage 21 21 %
date 2026-01-15 15/01/2026
  • Locale.forLanguageTag("es-ES") is equivalent to new Locale("es", "ES"), which we used in module 2, but that constructor has been deprecated since Java 19; this way the code won't produce warnings when you upgrade the JDK.
  • NumberFormat isn't thread-safe: that's why we create one on each call instead of keeping it in a static field. DateTimeFormatter, on the other hand, is immutable and can be shared.
  • The non-breaking space ( ) prevents "21" and "%" from ending up on different lines when text is wrapped.

We can now keep the promise made in lesson 02-06: the header gets its data from the model. We add a factory method to InvoiceHeader.Data (the rest of the class is unchanged):

/** Data the header needs, already converted to text. */
public record Data(String number, String date, List<String> issuer, List<String> customer) {

    /** Builds the header data from the model. */
    public static Data of(Invoice invoice) {
        return new Data(invoice.number(),
                Formats.date(invoice.date()),
                invoice.issuer().lines(),
                invoice.customer().lines());
    }
}

Defining columns: fixed and relative widths

The invoice columns have different needs: quantity, price and amount always take up a similar width, whereas the description should make use of all the space that's left over. Like CSS Grid's fr columns, we combine two kinds:

package com.invoicelab.pdf;

/**
 * Definition of a table column.
 * If relative is false, width is in points; if it's true, it's a "weight" for sharing out the leftover space.
 */
public record Column(String title, float width, boolean relative, Alignment alignment) {

    public Column {
        if (width <= 0) {
            throw new IllegalArgumentException("The width of column '" + title + "' must be positive");
        }
    }

    /** Fixed-width column in points (use Measures.mm to think in millimetres). */
    public static Column fixed(String title, float widthPoints, Alignment alignment) {
        return new Column(title, widthPoints, false, alignment);
    }

    /** Column that takes a share of the leftover space in proportion to its weight. */
    public static Column relative(String title, float weight, Alignment alignment) {
        return new Column(title, weight, true, alignment);
    }
}

The sharing algorithm is simple:

leftover        = total width − sum of fixed widths
relative width  = leftover × weight / sum of weights

For the invoice, in a 174 mm content box:

Column Type Width Alignment
Ref. Fixed 24 mm Left
Description Relative (weight 1) 174 − 95 = 79 mm Left
Qty Fixed 14 mm Right
Price Fixed 20 mm Right
VAT Fixed 13 mm Right
Amount Fixed 24 mm Right

All numeric columns are right-aligned, for the reason we saw in lesson 02-04: units, decimals and commas line up in a column. Text goes on the left.

Calculating the height of a row with multi-line text

A row is as tall as its tallest cell. Each cell is a TextBlock with the inner width of its column (the width minus the padding on both sides), and measureHeight tells us how much space it'll take without drawing anything:

flowchart LR
    A["For each cell i"] --> B["TextBlock(font, size,<br/>width[i] − 2·padding)"]
    B --> C["measureHeight(sanitized text)"]
    C --> D["maximum across all cells"]
    D --> E["row height = maximum + 2·padding"]

For example, "A2 stainless steel hex bolt M8x40 (box of 100 units)" doesn't fit in the 79 mm of the description at 8.5 pt, so it takes up two lines and that row is taller than the rest. Single-line cells stay top-aligned, which is the norm in tables with long text.

Drawing the table: header, zebra rows and lines

The drawing order of each row matters, because in PDF whatever is drawn last ends up on top:

  1. The row's background (only on odd rows: the zebra effect).
  2. The text of each cell.
  3. The row's bottom line.

The header row uses the corporate blue as its background, with bold white text. The whole look is grouped in a nested record Style, with a factory method for Nebula Distribution's style.

The complete Table class

package com.invoicelab.pdf;

import java.awt.Color;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDFont;

/**
 * Fixed-width table with a header, multi-line text, zebra rows and per-column alignment.
 * It knows nothing about invoices: it receives rows of already formatted text.
 */
public final class Table {

    /** The table's look. All measurements in points. */
    public record Style(PDFont font, PDFont headerFont, float size, float padding,
                        Color headerBackground, Color headerText, Color alternateBackground,
                        Color lineColor, float lineWidth) {

        /** Nebula Distribution's corporate style. */
        public static Style nebula(InvoiceLabFonts fonts) throws IOException {
            return new Style(fonts.regular(), fonts.bold(), 8.5f, Measures.mm(1.6),
                    NebulaColors.BLUE, Color.WHITE, NebulaColors.BACKGROUND_BLUE,
                    NebulaColors.LINE_GREY, 0.5f);
        }
    }

    private static final float LINE_SPACING = 1.2f;

    private final List<Column> columns;
    private final float[] widths;           // actual width of each column, in points
    private final Style style;

    public Table(List<Column> columns, float totalWidth, Style style) {
        if (columns.isEmpty()) {
            throw new IllegalArgumentException("A table needs at least one column");
        }
        this.columns = List.copyOf(columns);
        this.style = style;
        this.widths = computeWidths(this.columns, totalWidth);
    }

    // ------------------------------------------------------------------ widths

    /** Fixed: their value. Relative: the leftover space shared out according to their weight. */
    private static float[] computeWidths(List<Column> columns, float totalWidth) {
        float fixedSum = 0;
        float weightSum = 0;
        for (Column c : columns) {
            if (c.relative()) {
                weightSum += c.width();
            } else {
                fixedSum += c.width();
            }
        }
        float leftover = totalWidth - fixedSum;
        if (leftover < 0 || (weightSum > 0 && leftover < Measures.mm(10))) {
            throw new IllegalArgumentException(String.format(
                    "The fixed columns (%.1f mm) leave no room in a %.1f mm table",
                    Measures.toMm(fixedSum), Measures.toMm(totalWidth)));
        }
        float[] widths = new float[columns.size()];
        for (int i = 0; i < widths.length; i++) {
            Column c = columns.get(i);
            widths[i] = c.relative() ? leftover * c.width() / weightSum : c.width();
        }
        return widths;
    }

    public float totalWidth() {
        float total = 0;
        for (float w : widths) {
            total += w;
        }
        return total;
    }

    public float columnWidth(int index) {
        return widths[index];
    }

    // ------------------------------------------------------------------ measuring

    public float headerHeight() throws IOException {
        return cellsHeight(titles(), style.headerFont());
    }

    public float rowHeight(List<String> cells) throws IOException {
        checkCellCount(cells);
        return cellsHeight(cells, style.font());
    }

    /** A row is as tall as its tallest cell, plus the top and bottom padding. */
    private float cellsHeight(List<String> cells, PDFont font) throws IOException {
        float maximum = 0;
        for (int i = 0; i < cells.size(); i++) {
            float height = block(font, i).measureHeight(clean(font, cells.get(i)));
            maximum = Math.max(maximum, height);
        }
        return maximum + 2 * style.padding();
    }

    // ------------------------------------------------------------------ drawing

    /** Header row with the corporate background and white text. Returns the height used. */
    public float drawHeader(PDPageContentStream content, float x, float yTop) throws IOException {
        float height = headerHeight();
        Shapes.drawBox(content, x, yTop - height, totalWidth(), height, 0,
                style.headerBackground(), null, 0);
        writeCells(content, titles(), style.headerFont(), style.headerText(), x, yTop);
        return height;
    }

    /** Data row. index decides the zebra background (odd rows get one). Returns the height used. */
    public float drawRow(PDPageContentStream content, List<String> cells, int index,
                         float x, float yTop) throws IOException {
        float height = rowHeight(cells);
        float yBottom = yTop - height;
        if (index % 2 == 1) {                                          // 1) background (zebra)
            Shapes.drawBox(content, x, yBottom, totalWidth(), height, 0, style.alternateBackground(), null, 0);
        }
        writeCells(content, cells, style.font(), Color.BLACK, x, yTop);                 // 2) text
        Shapes.horizontalLine(content, x, x + totalWidth(), yBottom,                    // 3) bottom line
                style.lineWidth(), style.lineColor());
        return height;
    }

    /** Header + all rows, without checking whether they fit (page breaks come in 03-02). */
    public float draw(PDPageContentStream content, List<List<String>> rows, float x, float yTop)
            throws IOException {
        float y = yTop;
        y -= drawHeader(content, x, y);
        for (int i = 0; i < rows.size(); i++) {
            y -= drawRow(content, rows.get(i), i, x, y);
        }
        return yTop - y;
    }

    // ------------------------------------------------------------------ private

    private void writeCells(PDPageContentStream content, List<String> cells, PDFont font,
                            Color color, float x, float yTop) throws IOException {
        content.saveGraphicsState();
        content.setNonStrokingColor(color);
        float xCell = x;
        for (int i = 0; i < cells.size(); i++) {
            block(font, i).draw(content, clean(font, cells.get(i)),
                    xCell + style.padding(), yTop - style.padding());
            xCell += widths[i];
        }
        content.restoreGraphicsState();
    }

    /** Text box with the column's inner width and its alignment. */
    private TextBlock block(PDFont font, int column) {
        Alignment alignment = columns.get(column).alignment();
        return new TextBlock(font, style.size(), widths[column] - 2 * style.padding())
                .alignment(alignment)
                .lineSpacing(LINE_SPACING);
    }

    private List<String> titles() {
        List<String> titles = new ArrayList<>();
        for (Column c : columns) {
            titles.add(c.title());
        }
        return titles;
    }

    private void checkCellCount(List<String> cells) {
        if (cells.size() != columns.size()) {
            throw new IllegalArgumentException("The row has " + cells.size() + " cells and the table has "
                    + columns.size() + " columns: " + cells);
        }
    }

    private static String clean(PDFont font, String text) throws IOException {
        return text == null ? "" : InvoiceLabFonts.sanitize(font, text);
    }
}

A walk through the important decisions:

  • The widths are calculated once, in the constructor. If the fixed columns don't leave at least 10 mm for the relative ones, an exception is thrown with a message in millimetres: it's much better to fail early than to generate a table with a 2 mm-wide description.
  • rowHeight and drawRow use the same block(...): measuring and drawing share the font, size, width and line spacing. If you measured with one configuration and drew with another, the calculated row and the real one wouldn't match.
  • Each cell is a TextBlock with its column's alignment. The right alignment of the amounts is done by TextBlock, which already knew how to align each line within its width.
  • The text is placed at yTop - padding: since TextBlock receives the top edge (not the baseline), the top padding is exact.
  • writeCells saves and restores the graphics state so that the header's white colour doesn't "leak" into whatever is drawn next. It's the rule for helpers we've followed since lesson 02-01.
  • All text goes through sanitize, and a null becomes an empty cell: a missing piece of data shouldn't prevent the invoice from being generated.
  • Each drawing method returns the height used, the same contract as TextBlock and InvoiceHeader.
  • The zebra pattern depends on the row index, which drawRow receives. That way, in the next lesson, when the table continues onto another page, the colour alternation will still be correct.

The invoice's line-item table on one page

Let's put the header and the table together. The example class defines the invoice columns and turns each InvoiceLine into a row of text using Formats:

package com.invoicelab.examples;

// imports: model (Invoice, InvoiceLine), pdf (Alignment, InvoiceHeader, ContentBox, Column,
// Formats, InvoiceLabFonts, Images, Measures, ReferenceGrid, Table), java.io, java.nio.file,
// java.util and PDFBox (PDDocument, PDPage, PDPageContentStream, PDRectangle)

public class InvoiceTableOnePage {

    /** The 6 columns of the invoice's line-item table. */
    static List<Column> invoiceColumns() {
        return 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));
    }

    /** Turns each InvoiceLine into a row of already formatted text. */
    static List<List<String>> rows(Invoice invoice) {
        List<List<String>> rows = new ArrayList<>();
        for (InvoiceLine l : invoice.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;
    }

    public static void main(String[] args) throws IOException {
        Files.createDirectories(Path.of("output"));
        Invoice invoice = SampleData.invoice(12);

        try (PDDocument document = new PDDocument()) {
            InvoiceLabFonts fonts = new InvoiceLabFonts(document);
            InvoiceHeader header = new InvoiceHeader(fonts,
                    Images.loadResource(document, "/img/logo-nebula.png"));

            PDPage page = new PDPage(PDRectangle.A4);
            document.addPage(page);
            ContentBox box = ContentBox.invoice(page.getMediaBox());
            Table table = new Table(invoiceColumns(), box.width(), Table.Style.nebula(fonts));

            try (PDPageContentStream content = new PDPageContentStream(document, page)) {
                if (Boolean.getBoolean("invoicelab.grid")) {
                    ReferenceGrid.draw(content, page.getMediaBox());
                }
                float y = header.draw(content, page.getMediaBox(), box,
                        InvoiceHeader.Data.of(invoice));
                float height = table.draw(content, rows(invoice), box.left(), y);
                y -= height;
                System.out.printf("Table: %d rows, %.1f mm tall; space left down to y = %.1f%n",
                        invoice.lines().size(), Measures.toMm(height), y);
                System.out.println("Taxable base: " + Formats.euros(invoice.taxableBase()));
                invoice.vatBreakdown().forEach(d -> System.out.printf("  VAT %s on %s = %s%n",
                        Formats.percentage(d.rate()), Formats.euros(d.base()), Formats.euros(d.tax())));
                System.out.println("Total: " + Formats.euros(invoice.total()));
            }
            document.save("output/invoice-table.pdf");
        }
    }
}

Console output:

Table: 12 rows, 101.4 mm tall; space left down to y = 303.1
Taxable base: 1.225,95 €
  VAT 21 % on 1.138,05 € = 238,99 €
  VAT 10 % on 39,90 € = 3,99 €
  VAT 4 % on 48,00 € = 1,92 €
Total: 1.470,85 €

Open output/invoice-table.pdf and check:

  • The blue header with the titles in white, and the numeric titles ("Qty", "Amount") right-aligned just like their values.
  • Alternate rows with a very light blue background and a thin grey line under each row.
  • Long descriptions take up two lines and their row grows; the other cells in that row stay at the top.
  • The amounts in a perfect column, with the decimal commas aligned.

The usage pattern is always the same: header.draw returns the y where the content continues, the table starts there and returns its height. With 12 lines there are almost 9 cm to spare before the bottom margin. And with 80? The table would carry on being drawn below the edge of the paper: draw doesn't check whether it fits. Solving that (detecting the end of the page, creating another one, repeating the table header) is exactly the topic of the next lesson.

What about table libraries?

There are libraries that add tables on top of PDFBox. It's worth knowing about them so you can make an informed decision:

Option What it offers Things to bear in mind
boxable Tables with cells, borders, page breaks, basic HTML in cells A long-standing project; check that its version is compatible with PDFBox 3.x before adopting it
easytable (vandeseer) Fluent API with builders, text, image and paragraph cells; tables that span several pages Likewise, check the version compatible with PDFBox 3.x
Your own table (this lesson) Full control, no dependencies, ~200 lines you understand You maintain the code and add whatever you need

For a corporate document with a fixed design, such as Nebula Distribution's invoice, your own table is usually enough and saves you from depending on a third party's update schedule. If you need very varied tables (merged cells, images in cells, per-cell styles), a library can save you work. And if the document is almost entirely formatted text, consider a higher-level tool (HTML to PDF, JasperReports), as we saw in lesson 01-01.

Common Mistakes and Tips

  • Drawing the text before the background. The zebra rectangle would cover the text. The order is background → text → lines.
  • Measuring with one width and drawing with another. If rowHeight doesn't use exactly the same TextBlock (font, size, inner width, line spacing) as the drawing code, the "calculated" row and the real one don't match and the text spills into the next row.
  • Forgetting the padding when calculating the inner width. The text runs right up to the neighbouring column's line. The width of the text box is columnWidth − 2 × padding.
  • Left-aligning amounts. The figures end up misaligned and are hard to compare. Numbers always go on the right, and so does their title.
  • Calculating amounts in the drawing code. If Table or the example multiply quantity × price, sooner or later there'll be two different calculations. Amounts come from the model (InvoiceLine.amount()).
  • Using double or new BigDecimal(18.40). Use new BigDecimal("18.40") and an explicit RoundingMode.HALF_UP.
  • Grouping VAT rates in a HashMap<BigDecimal, ...>. 10 and 10.00 are different keys for equals. Use a TreeMap or normalise the scale.
  • Fixed columns that add up to more than the box. Table detects this in the constructor; read the message, which tells you the millimetres.
  • Tip: run with -Dinvoicelab.grid=true and use the grid to check that the table starts and ends exactly at the 18 mm margins.

Exercises

  1. Full grid. Add a boolean verticalLines field to Table.Style and, when it's true, also draw the vertical lines between columns and the left and right borders of each row (header included). Update Style.nebula so that it still has none.
  2. Check the model by hand. Create an invoice with three lines: 3 units at €10.005 at 21 %, 2 units at €4.50 at 10 % and 1 unit at €24.00 at 4 %. Calculate the base, the breakdown and the total by hand, and compare them with what Invoice returns. What happens to the amount on the first line?
  3. Price list. Use Table (without modifying it) to generate output/price-list.pdf with the product catalogue: columns "Ref.", "Description", "Price excl. VAT" and "Price incl. VAT", the last two right-aligned and formatted with Formats.euros. The price including VAT is calculated with BigDecimal and rounded to cents.

Solutions

Solution 1. Add the field to the record and a private method that walks through the widths; it's called from drawHeader and drawRow after the text (the lines go on top of everything):

public record Style(PDFont font, PDFont headerFont, float size, float padding,
                    Color headerBackground, Color headerText, Color alternateBackground,
                    Color lineColor, float lineWidth, boolean verticalLines) {
    public static Style nebula(InvoiceLabFonts fonts) throws IOException {
        return new Style(fonts.regular(), fonts.bold(), 8.5f, Measures.mm(1.6),
                NebulaColors.BLUE, Color.WHITE, NebulaColors.BACKGROUND_BLUE,
                NebulaColors.LINE_GREY, 0.5f, false);
    }
}

private void verticalLines(PDPageContentStream content, float x, float yTop, float height)
        throws IOException {
    if (!style.verticalLines()) {
        return;
    }
    content.saveGraphicsState();
    content.setStrokingColor(style.lineColor());
    content.setLineWidth(style.lineWidth());
    float xLine = x;
    for (int i = 0; i <= widths.length; i++) {          // n columns → n + 1 lines
        content.moveTo(xLine, yTop);
        content.lineTo(xLine, yTop - height);
        if (i < widths.length) {
            xLine += widths[i];
        }
    }
    content.stroke();                                   // a single stroke for all the lines
    content.restoreGraphicsState();
}

In drawRow, after the bottom line: verticalLines(content, x, yTop, height);. Notice that all the lines are added to the same path and stroked with a single stroke(), as you learned in lesson 02-05.

Solution 2.

Invoice f = new Invoice("F-2026-0002", LocalDate.of(2026, 1, 20), SampleData.NEBULA, SampleData.HARDWARE,
        List.of(new InvoiceLine("A", "Product at 21%", new BigDecimal("3"), new BigDecimal("10.005"), new BigDecimal("21")),
                new InvoiceLine("B", "Product at 10%", new BigDecimal("2"), new BigDecimal("4.50"), new BigDecimal("10")),
                new InvoiceLine("C", "Book", new BigDecimal("1"), new BigDecimal("24.00"), new BigDecimal("4"))),
        "");
System.out.println(f.lines().get(0).amount() + " | " + f.vatBreakdown() + " | " + f.total());
30.02 | [VatLine[rate=21, base=30.02, tax=6.30], VatLine[rate=10, base=9.00, tax=0.90],
         VatLine[rate=4, base=24.00, tax=0.96]] | 71.18

By hand: 3 × 10.005 = 30.015 → 30.02 (the 5 rounds up with HALF_UP); 2 × 4.50 = 9.00; 1 × 24.00 = 24.00. Base = 63.02. VAT: 30.02 × 21 % = 6.3042 → 6.30; 9.00 × 10 % = 0.90; 24.00 × 4 % = 0.96. VAT = 8.16 and total = €71.18. The first line shows why rounding must be explicit: with another mode (HALF_EVEN, "banker's rounding") 30.015 would also end up as 30.02, but 30.025 would go down to 30.02 instead of up to 30.03.

Solution 3.

List<Column> columns = List.of(
        Column.fixed("Ref.", Measures.mm(26), Alignment.LEFT),
        Column.relative("Description", 1, Alignment.LEFT),
        Column.fixed("Price excl. VAT", Measures.mm(24), Alignment.RIGHT),
        Column.fixed("Price incl. VAT", Measures.mm(24), Alignment.RIGHT));

List<List<String>> rows = new ArrayList<>();
for (InvoiceLine l : SampleData.invoice(10).lines()) {          // one line per catalogue product
    BigDecimal withVat = l.unitPrice()
            .multiply(BigDecimal.ONE.add(l.vatRate().movePointLeft(2)))   // × (1 + 21/100)
            .setScale(2, RoundingMode.HALF_UP);
    rows.add(List.of(l.reference(), l.description(),
            Formats.euros(l.unitPrice()), Formats.euros(withVat)));
}
// ... document, page and box as in the example ...
new Table(columns, box.width(), Table.Style.nebula(fonts))
        .draw(content, rows, box.left(), box.top());

movePointLeft(2) divides by 100 without rounding errors (21 → 0.21). The table didn't need a single change: that's the advantage of it receiving text rather than InvoiceLine objects.

Conclusion

PDFBox has no tables, but now you have your own: fixed and relative columns with their alignment, rows that grow with the text thanks to TextBlock.measureHeight, a corporate header, zebra rows and lines drawn in the right order, and all text sanitized. On top of that, InvoiceLab finally has a model (Customer, InvoiceLine, Invoice) that calculates the taxable base, the VAT breakdown by rate and the total with BigDecimal, a Formats utility for the Spanish style and a header fed by the model through InvoiceHeader.Data.of(invoice).

But the table has a very clear limit: if the invoice has 80 lines, it runs off the paper. In the next lesson you'll learn to detect when a row doesn't fit (ContentBox.fits), to create new pages safely, to repeat the table header on every page without splitting rows, to show "Carried forward" and to number pages with "Page X of N".

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