The Table from the previous lesson draws the header and all the rows one after another, without asking itself whether they fit. With 12 lines there's no problem; with 80, the rows keep going down and end up being drawn below the edge of the paper, where nobody will see them (PDFBox doesn't raise any error: negative coordinates are valid). A real business document has to be spread across pages, and doing it properly involves several things: deciding before drawing whether an element fits, creating a new page and its content stream without leaving any of them open, repeating the table header, not splitting a row in half, showing "Carried forward" and numbering the pages with "Page X of N", even though N isn't known until the end. In this lesson you'll wrap all of that up in the Paginator class, extend Table with drawPaginated, add a compact header to InvoiceHeader and create PageFooter, which numbers the pages in a second pass.
Contents
- The problem: content that doesn't fit on one page
- Measuring before drawing:
ContentBox.fitsand the footer reserve - Creating new pages and reopening the content stream safely
- The
Paginatorclass - Full header on page 1 and a compact one on the following pages
- Tables that continue: repeating the header and not splitting rows
- "Carried forward"
- "Page X of N": numbering in two passes
- Example: the 80-line invoice
The problem: content that doesn't fit on one page
Remember the two content stream rules we saw in lessons 01-04 and 02-02:
- A
PDPageContentStreambelongs to one page: everything you write to it appears on that page and that page only. - It has to be closed (
close(), usually withtry-with-resources) before saving; otherwise the content is left incomplete.
Until now we had one page and one try with its stream. With several pages, the "current" stream changes halfway through the drawing: when a row doesn't fit, you have to close the current page's stream, create the next page and open its stream, and all the drawing code has to switch to the new one. If each block of the invoice handled this on its own, the code would fill up with page, content and y variables that have to be kept in sync. The solution is an object that encapsulates the current page: the paginator.
flowchart TD
A["Next element (row, block)"] --> B["Measure its height<br/>(without drawing)"]
B --> C{"does it fit between y<br/>and the bottom limit?"}
C -- Yes --> D["Draw it at (x, y)"]
C -- No --> E["Close the current stream"]
E --> F["Create page + open stream"]
F --> G["Draw the page header<br/>and place y below it"]
G --> D
D --> H["y -= height used"]
H --> A
Measuring before drawing: ContentBox.fits and the footer reserve
All pagination is based on an idea we prepared in module 2: measuring without drawing. TextBlock.measureHeight and Table.rowHeight return the height something will take up, and ContentBox.fits(y, height) (lesson 02-01) tells you whether an element whose top edge is at y ends above the box's bottom edge:
But the content can't go all the way down to the bottom edge of the content box, because that's where the page footer goes ("Page 2 of 4"). That space has to be reserved. Instead of subtracting the reserve in every check, the paginator creates a second box, the body box, the same as the content box but with its bottom edge raised:
┌─────────── content box (174 × 257 mm) ───────────┐
│ page header (full or compact) │
│ ────────────────────────────────────────────── │ ← initial y
│ │
│ body (table, totals...) │
│ │
│- - - - - - - - - body box limit - - - - - - - - -│ ← bottom + footer reserve
│ footer: reference · "Page X of N" │ ← reserve (9 mm)
└──────────────────────────────────────────────────┘ ← bottom of the content boxCreating new pages and reopening the content stream safely
A page break follows a strict order:
- Close the current page's stream. There must never be two streams open at the same time in the same document: if the code mistakenly draws on the old one, the content ends up on the wrong page.
- Create the page (
new PDPage(PDRectangle.A4)) and add it withdocument.addPage(...), which puts it at the end. - Open its stream (
new PDPageContentStream(document, page)). - Draw the page header (full or compact) and place the
ycursor below it.
And what if an exception occurs halfway through the document? The last open stream must still be closed. That's why the paginator will implement Closeable and be used with try-with-resources. Watch the order: the paginator is closed before saving, so it goes in an inner try:
try (PDDocument document = new PDDocument()) {
try (Paginator paginator = new Paginator(...)) {
// ... draw ...
} // the last page's stream is closed here
document.save("output/invoice.pdf"); // and only then is the document saved
}The Paginator class
package com.invoicelab.pdf;
import java.io.Closeable;
import java.io.IOException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
/**
* Encapsulates "the current page": the PDPage, its open content stream and the vertical cursor y.
* Creates new pages when the content doesn't fit and guarantees that only one stream is open.
*/
public final class Paginator implements Closeable {
/** What gets drawn at the top of each new page. Returns the Y where the content starts. */
@FunctionalInterface
public interface PageHeader {
float draw(PDPageContentStream content, PDPage page, ContentBox box, int pageNumber)
throws IOException;
}
private final PDDocument document;
private final PDRectangle pageSize;
private final float footerReserve;
private final PageHeader firstPageHeader;
private final PageHeader nextPagesHeader;
private PDPage page;
private PDPageContentStream content;
private ContentBox box; // the page's full content box
private ContentBox bodyBox; // content box minus the footer reserve
private float y;
private int pageNumber;
public Paginator(PDDocument document, PDRectangle pageSize, float footerReserve,
PageHeader firstPageHeader, PageHeader nextPagesHeader) {
this.document = document;
this.pageSize = pageSize;
this.footerReserve = footerReserve;
this.firstPageHeader = firstPageHeader; // may be null: no header
this.nextPagesHeader = nextPagesHeader;
}
/** Closes the current page (if any), creates another, draws its header and positions the cursor. */
public void newPage() throws IOException {
closeContent(); // 1) never two open streams
page = new PDPage(pageSize); // 2) new page at the end of the document
document.addPage(page);
pageNumber++;
box = ContentBox.invoice(page.getMediaBox());
bodyBox = new ContentBox(box.left(), box.bottom() + footerReserve,
box.right(), box.top());
content = new PDPageContentStream(document, page); // 3) its stream
if (Boolean.getBoolean("invoicelab.grid")) {
ReferenceGrid.draw(content, page.getMediaBox());
}
PageHeader header = pageNumber == 1 ? firstPageHeader : nextPagesHeader;
y = header == null ? box.top() // 4) cursor below the header
: header.draw(content, page, box, pageNumber);
}
/** Does an element of this height fit from the current position? */
public boolean fits(float height) {
checkPage();
return bodyBox.fits(y, height);
}
/** If the element doesn't fit, moves to a new page. Returns true if there was a page break. */
public boolean ensure(float height) throws IOException {
if (fits(height)) {
return false;
}
newPage();
if (!fits(height)) {
throw new IllegalStateException(String.format(
"A %.1f mm element doesn't fit even on an empty page", Measures.toMm(height)));
}
return true;
}
/** Moves the cursor down by the height used by whatever was just drawn. */
public void moveDown(float height) {
y -= height;
}
public PDPageContentStream content() {
checkPage();
return content;
}
public float y() {
checkPage();
return y;
}
public ContentBox box() {
checkPage();
return box;
}
public PDPage page() {
checkPage();
return page;
}
public int pageNumber() {
return pageNumber;
}
/** Closes the last page's stream. It must be called BEFORE saving the document. */
@Override
public void close() throws IOException {
closeContent();
}
private void closeContent() throws IOException {
if (content != null) {
content.close();
content = null;
}
}
private void checkPage() {
if (content == null) {
throw new IllegalStateException("No page is open: call newPage() first");
}
}
}How it's designed:
| Method | What it's for |
|---|---|
newPage() |
A complete page break, in the safe order: close, create, open, header |
fits(height) |
A query with no side effects, using ContentBox.fits on the body box |
ensure(height) |
"If it doesn't fit, break the page". If it doesn't fit on an empty page either, it throws an exception instead of creating pages in a loop |
moveDown(height) |
Moves the cursor after drawing. It matches the blocks' contract: "I return the height used" |
content(), y(), box() |
Access to the current page. Always ask the paginator for them after a possible page break |
close() |
Closes the last stream; lets you use try-with-resources |
PageHeaderis a functional interface (a single abstract method), so it can be passed as a lambda:(cs, page, box, n) -> header.draw(...). It receives the page number in case the header needs it.- The debugging grid is drawn on each new page with the same
-Dinvoicelab.grid=trueproperty as always. checkPageturns a slip (forgetting to callnewPage()at the start, or using the paginator after closing it) into a clear message instead of aNullPointerException.
Full header on page 1 and a compact one on the following pages
Repeating the full header (large logo, issuer and customer details) on every page wastes almost 9 cm per page. The usual approach is a compact header on page 2 onwards: the corporate band, a small logo and a line that identifies the document. We add a method to InvoiceHeader (the rest of the class is unchanged):
/**
* Compact header for pages 2 onwards: band, small logo and an
* "INVOICE F-2026-0001 (continued)" line with the customer below it.
* @return the Y coordinate from which the content can continue
*/
public float drawCompact(PDPageContentStream content, PDRectangle sheet, ContentBox box, Data data)
throws IOException {
PDFont normal = fonts.regular();
PDFont bold = fonts.bold();
// Same corporate band as on page 1, so that every page is recognisable
float yBand = sheet.getUpperRightY() - BAND_HEIGHT;
Shapes.drawBox(content, sheet.getLowerLeftX(), yBand, sheet.getWidth(), BAND_HEIGHT,
0, NebulaColors.BLUE, null, 0);
Shapes.drawBox(content, sheet.getLowerLeftX(), yBand - RULE_HEIGHT, sheet.getWidth(), RULE_HEIGHT,
0, NebulaColors.ORANGE, null, 0);
float yRow = box.top();
Images.Size logoSize = Images.drawFitted(content, logo, box.left(), yRow,
Measures.mm(30), Measures.mm(10));
float yTitle = yRow - TextMetrics.ascent(bold, 11);
content.saveGraphicsState();
content.setNonStrokingColor(NebulaColors.BLUE);
TextMetrics.writeAligned(content, bold, 11,
"INVOICE " + clean(bold, data.number()) + " (continued)",
box.right(), yTitle, Alignment.RIGHT);
content.restoreGraphicsState();
float yCustomer = yTitle - 11 * 1.4f;
TextMetrics.writeAligned(content, normal, 8.5f,
"Customer: " + clean(normal, data.customer().get(0)) + " · Date: " + clean(normal, data.date()),
box.right(), yCustomer, Alignment.RIGHT);
float rowHeight = Math.max(logoSize.height(), yRow - yCustomer + TextMetrics.descent(normal, 8.5f));
float y = yRow - rowHeight - Measures.mm(3);
Shapes.horizontalLine(content, box.left(), box.right(), y, 0.75f, NebulaColors.LINE_GREY);
return y - Measures.mm(4);
}It uses the same logo (PDImageXObject) as the full header, just drawn smaller: remember from lesson 02-06 that an image is stored once and drawn as many times as you like. It returns the y where the content starts, the same contract as draw, which is why both methods fit into a Paginator.PageHeader.
Tables that continue: repeating the header and not splitting rows
Now we extend Table with a method that draws through the paginator (it needs import java.util.function.IntFunction;). The professional rules for a table spanning several pages are:
| Rule | Why | How |
|---|---|---|
| Don't split rows | A row split across two pages is unreadable and mixes up amounts | The whole row is measured; if it doesn't fit, the page breaks before drawing it |
| Repeat the header | On page 3 nobody remembers which column is "Price" and which is "Amount" | After each break, drawHeader |
| No orphan headers | A header on its own at the bottom of a page, with no rows, looks like a mistake | Before starting, the header and the first row are required to fit |
| The zebra continues | The colour alternation doesn't restart on each page | The row index is the table-wide one |
/**
* Draws the table from the paginator's position, breaking pages when needed.
* Repeats the header on every page and never splits a row.
*
* @param runningTotal if not null, receives how many rows have been drawn and returns the
* formatted sum up to that point: "Carried forward" / "Brought forward" rows are shown
*/
public void drawPaginated(Paginator paginator, List<List<String>> rows, IntFunction<String> runningTotal)
throws IOException {
float x = paginator.box().left();
float summaryHeight = runningTotal == null ? 0 : summaryHeight();
float firstRow = rows.isEmpty() ? 0 : rowHeight(rows.get(0));
// The header is never left alone at the bottom of a page: we require header + first row
paginator.ensure(headerHeight() + firstRow + (rows.size() > 1 ? summaryHeight : 0));
paginator.moveDown(drawHeader(paginator.content(), x, paginator.y()));
for (int i = 0; i < rows.size(); i++) {
float height = rowHeight(rows.get(i));
boolean isLast = (i == rows.size() - 1);
float reserve = isLast ? 0 : summaryHeight; // room for a possible "Carried forward"
if (!paginator.fits(height + reserve)) {
if (runningTotal != null) {
paginator.moveDown(drawSummary(paginator.content(), "Carried forward",
runningTotal.apply(i), x, paginator.y()));
}
paginator.newPage();
if (!paginator.fits(headerHeight() + summaryHeight + height)) {
throw new IllegalStateException("Row " + (i + 1) + " doesn't fit even on an empty page");
}
paginator.moveDown(drawHeader(paginator.content(), x, paginator.y()));
if (runningTotal != null) {
paginator.moveDown(drawSummary(paginator.content(), "Brought forward",
runningTotal.apply(i), x, paginator.y()));
}
}
paginator.moveDown(drawRow(paginator.content(), rows.get(i), i, x, paginator.y()));
}
}The most important part is in the loop:
- The row is measured with
rowHeightbefore anything is drawn. - If it doesn't fit, the page is closed off (with its "Carried forward"), another one is created with
newPage()(which already draws the invoice's compact header) and the table header is repeated. - If a row doesn't fit even on an empty page (a description three pages long), an exception is thrown with the row number: it's impossible to honour the no-split rule, and it's better to warn than to enter an infinite loop of blank pages.
- The row is drawn with its table-wide index
i: the zebra doesn't restart. - Notice that
paginator.content()andpaginator.y()are requested every time they're used: after a page break, the stream and theyare different ones. Storing them in local variables at the start would be a classic mistake.
"Carried forward"
On long invoices it's traditional to close each page with the running total so far ("Carried forward") and to start the next one by restating it ("Brought forward"). To keep the table independent of money, it doesn't calculate anything: it receives an IntFunction<String> that, given the number of rows already drawn, returns the text of the running total. If null is passed, there are no summary rows.
The summary row spans the full width, with the label on the left and the amount on the right in bold blue, inside a box with a corporate border:
private float summaryHeight() {
PDFont f = style.headerFont();
return TextMetrics.ascent(f, style.size()) + TextMetrics.descent(f, style.size())
+ 2 * style.padding();
}
/** Full-width row: label on the left and amount on the right, in bold. */
private float drawSummary(PDPageContentStream content, String label, String amount,
float x, float yTop) throws IOException {
float height = summaryHeight();
PDFont f = style.headerFont();
Shapes.drawBox(content, x, yTop - height, totalWidth(), height, 0, null,
style.headerBackground(), style.lineWidth());
float yBase = yTop - style.padding() - TextMetrics.ascent(f, style.size());
content.saveGraphicsState();
content.setNonStrokingColor(style.headerBackground());
TextMetrics.writeAligned(content, f, style.size(), clean(f, label),
x + style.padding(), yBase, Alignment.LEFT);
TextMetrics.writeAligned(content, f, style.size(), clean(f, amount),
x + totalWidth() - style.padding(), yBase, Alignment.RIGHT);
content.restoreGraphicsState();
return height;
}The subtlety lies in the reserve: before drawing row i, the code checks that the row and a possible "Carried forward" row below it both fit. If we only checked the row, it could just about fit and then leave no room for the summary. The last row needs no reserve, because no page break follows it. The running total is calculated outside, with BigDecimal, from the model:
// cumulative[n] = sum of the amounts of the first n lines
BigDecimal[] cumulative = new BigDecimal[invoice.lines().size() + 1];
cumulative[0] = BigDecimal.ZERO;
for (int i = 0; i < invoice.lines().size(); i++) {
cumulative[i + 1] = cumulative[i].add(invoice.lines().get(i).amount());
}
// and it's passed to the table as: n -> Formats.euros(cumulative[n])"Page X of N": numbering in two passes
The "Page 2 of 4" footer poses a chicken-and-egg problem: when drawing page 1 we don't yet know how many pages there will be. There are two strategies:
| Strategy | How | Advantages | Drawbacks |
|---|---|---|---|
| Two passes | All the content is generated; then the document's pages (still in memory) are walked through and the footer is added to each one | Simple and always exact | Each page has to be reopened a second time |
| Calculate N beforehand | The layout is simulated by measuring everything without drawing, and the pages are counted | A single drawing pass | The pagination logic has to be duplicated in the simulation; any difference gives a wrong N |
We choose two passes. To add content to a page that already has a content stream, you use the constructor with an append mode:
| Parameter | Value | Meaning |
|---|---|---|
AppendMode |
APPEND |
Adds a new stream after the existing one: the new content ends up on top |
PREPEND |
Adds it before: the new content ends up underneath (useful for backgrounds) | |
OVERWRITE |
Replaces the page's content: it wipes out what was there! (this is what the two-parameter constructor does) | |
compress |
true |
Compresses the new stream with Flate |
resetContext |
true |
Wraps the previous content in q … Q so that its graphics state (CTM, colours, clipping) doesn't affect the new content |
resetContext = true matters: if the previous content left a transformation or a clipping path active (for instance, because it forgot a restoreGraphicsState), our footer would appear shifted or clipped. This way we always start with a clean graphics state. In module 4 we'll use this same technique on PDFs loaded from disk to apply stamps; here we do it on the pages of the very document we've just generated.
package com.invoicelab.pdf;
import java.io.IOException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.PDPageContentStream.AppendMode;
import org.apache.pdfbox.pdmodel.font.PDFont;
/** "reference ... Page X of N" page footer, added in a second pass. */
public final class PageFooter {
/** Height the content must leave free at the bottom of the content box. */
public static final float HEIGHT = Measures.mm(9);
private static final float SIZE = 7.5f;
private PageFooter() {
}
/**
* Walks through all the pages of the document (still in memory) and adds the footer to each one.
* It must be called once no more pages will be created, and before saving.
*/
public static void numberPages(PDDocument document, InvoiceLabFonts fonts, String reference)
throws IOException {
PDFont font = fonts.regular();
String referenceText = InvoiceLabFonts.sanitize(font, reference);
int total = document.getNumberOfPages();
int number = 0;
for (PDPage page : document.getPages()) {
number++;
ContentBox box = ContentBox.invoice(page.getMediaBox());
// APPEND: adds a new stream AFTER the existing one; compress = true; resetContext = true
try (PDPageContentStream content = new PDPageContentStream(document, page,
AppendMode.APPEND, true, true)) {
draw(content, font, box, referenceText, number, total);
}
}
}
/** Draws a page's footer: rule, reference on the left and "Page X of N" on the right. */
public static void draw(PDPageContentStream content, PDFont font, ContentBox box,
String reference, int number, int total) throws IOException {
float yLine = box.bottom() + HEIGHT - Measures.mm(2);
Shapes.horizontalLine(content, box.left(), box.right(), yLine, 0.5f,
NebulaColors.LINE_GREY);
float yText = box.bottom() + TextMetrics.descent(font, SIZE);
content.saveGraphicsState();
content.setNonStrokingColor(NebulaColors.TEXT_GREY);
TextMetrics.writeAligned(content, font, SIZE, reference, box.left(), yText,
Alignment.LEFT);
TextMetrics.writeAligned(content, font, SIZE, "Page " + number + " of " + total,
box.right(), yText, Alignment.RIGHT);
content.restoreGraphicsState();
}
}document.getPages()returns aPDPageTreethat can be iterated with an enhancedforloop.- The font is the same
InvoiceLabFontsas the document's. It's no problem to use new glyphs ("P", "g", "f"...) after the content has been drawn: the font subset is calculated when saving, not when writing. PageFooter.HEIGHTis the constant passed to the paginator as its reserve: the footer and the reserve can't get out of sync.- The
drawmethod is public and separate fromnumberPages, in case one day you want to draw the footer in a single pass (when N is known in advance).
Example: the 80-line invoice
Let's put it all together. The invoice has 80 lines, a full header on page 1, a compact one on the rest, "Carried forward" and a numbered footer:
package com.invoicelab.examples;
// imports: model (Invoice, InvoiceLine), pdf (InvoiceHeader, ContentBox, Formats,
// InvoiceLabFonts, Images, Paginator, PageFooter, Table), java.io, java.math, java.nio.file,
// java.util.List, PDDocument and PDRectangle
public class MultipageInvoice {
public static void main(String[] args) throws IOException {
Files.createDirectories(Path.of("output"));
Invoice invoice = SampleData.invoice(80);
InvoiceHeader.Data data = InvoiceHeader.Data.of(invoice);
List<List<String>> rows = InvoiceTableOnePage.rows(invoice);
// Partial sums: cumulative[n] = sum of the amounts of the first n lines
BigDecimal[] cumulative = new BigDecimal[invoice.lines().size() + 1];
cumulative[0] = BigDecimal.ZERO;
for (int i = 0; i < invoice.lines().size(); i++) {
InvoiceLine line = invoice.lines().get(i);
cumulative[i + 1] = cumulative[i].add(line.amount());
}
try (PDDocument document = new PDDocument()) {
InvoiceLabFonts fonts = new InvoiceLabFonts(document);
InvoiceHeader header = new InvoiceHeader(fonts,
Images.loadResource(document, "/img/logo-nebula.png"));
ContentBox a4Box = ContentBox.invoice(PDRectangle.A4);
Table table = new Table(InvoiceTableOnePage.invoiceColumns(), a4Box.width(),
Table.Style.nebula(fonts));
// First pass: content. The paginator is closed BEFORE numbering and saving.
try (Paginator paginator = new Paginator(document, PDRectangle.A4, PageFooter.HEIGHT,
(cs, page, box, n) -> header.draw(cs, page.getMediaBox(), box, data),
(cs, page, box, n) -> header.drawCompact(cs, page.getMediaBox(), box, data))) {
paginator.newPage();
table.drawPaginated(paginator, rows, n -> Formats.euros(cumulative[n]));
System.out.printf("Table finished on page %d, y = %.1f%n",
paginator.pageNumber(), paginator.y());
}
// Second pass: now we know how many pages there are
PageFooter.numberPages(document, fonts, "Nebula Distribution Ltd. · Invoice " + invoice.number());
document.save("output/multipage-invoice.pdf");
System.out.println("Pages: " + document.getNumberOfPages());
}
}
}Points to note:
ContentBox.invoice(PDRectangle.A4)gives us the table width before any page exists: all the pages are A4, so the box is the same.- Two lambdas implement
Paginator.PageHeader. They captureheaderanddata, which are "effectively final" variables (they aren't reassigned), a Java requirement for using them inside a lambda. paginator.newPage()creates the first page: that's where the full header is drawn.- The paginator is closed on leaving its
try, and only then are the pages numbered and the document saved.
Open output/multipage-invoice.pdf: page 1 has the full header and ends with "Carried forward 2.699,20 €"; pages 2 to 4 start with the compact header, the table header and "Brought forward" with the same amount the previous page ended with. No row is split, the zebra continues and every page has the "Page X of 4" footer. After the table there are almost 18 cm left free on page 4: that's where the totals will go in lesson 03-05.
Common Mistakes and Tips
- Saving the document with the paginator still open. The last page's stream hasn't been closed and its content is lost or corrupted. The paginator goes in an inner
tryandsavecomes afterwards. - Storing
paginator.content()orpaginator.y()in local variables at the start of a loop. After a page break they point to the previous page: whatever you draw will appear there (or fail because the stream is closed). Always ask the paginator for them. - Using the two-parameter constructor to add the footer.
new PDPageContentStream(document, page)is equivalent toOVERWRITE: it wipes the page's content and only the footer remains. To add, useAppendMode.APPEND. - Forgetting
resetContext = truewhen appending. If the previous content left a transformation active, the footer appears somewhere else. - Not reserving the footer's space. The last row of each page gets overprinted by "Page X of N".
- Checking only the row and not the "Carried forward". The summary spills below the limit. Reserve space for whatever has to come after.
- Infinite loops of blank pages when an element is taller than a page. Always check that it fits on an empty page and, if not, throw a clear exception.
- Tip: to test pagination, generate invoices with 1, 12, 13, 25, 26 and 80 lines. Bugs show up right at the limits (the row that fits by a few millimetres, the header left on its own).
Exercises
- "Continued on next page". Modify
PageFooter.drawso that, on every page except the last, it writes the text "Continued on next page →" in italics, centred in the footer. - A block that isn't split. After the 80-line table, simulate the future totals block with a light blue 174 × 40 mm box that must never be cut off: if it doesn't fit on the current page, it must move whole to the next one. Try it with 80 and with 46 lines.
- The impossible row. Create an invoice in which one line has a 4,000-character description. What happens when you generate it? Then avoid the problem by limiting descriptions to 3 lines with an ellipsis before creating the rows, with a
limitLines(PDFont font, float size, String text, float width, int maximum)method based onTextMetrics.
Solutions
Solution 1. Add a parameter with the italic font and a block at the end of draw (inside the existing save/restore):
if (number < total) {
float centre = box.left() + box.width() / 2;
TextMetrics.writeAligned(content, italic, SIZE, "Continued on next page →",
centre, yText, Alignment.CENTER);
}In numberPages, get PDFont italic = fonts.italic(); and pass it to draw. The → arrow exists in DejaVu Sans; it couldn't be written with a standard WinAnsi font. This is another advantage of numbering in a second pass: we know which page is the last.
Solution 2.
// Inside the paginator's try, after drawPaginated:
float height = Measures.mm(40);
paginator.ensure(height); // if it doesn't fit whole, break the page
ContentBox box = paginator.box();
Shapes.drawBox(paginator.content(), box.left(), paginator.y() - height, box.width(), height,
Measures.mm(2), NebulaColors.BACKGROUND_BLUE, null, 0);
paginator.moveDown(height);With 80 lines the box fits on page 4, below the table. With 46 lines the table ends near the bottom of page 2 (about 29 mm free) and ensure creates a page 3 with the compact header and the box at the top. The order is essential: ensure first and then ask for box(), content() and y(), which by then belong to the new page.
Solution 3. Without limiting, generation ends with:
That's the desired behaviour: a clear error is better than a PDF with 300 blank pages. The preventive solution:
static String limitLines(PDFont font, float size, String text, float width, int maximum)
throws IOException {
String clean = InvoiceLabFonts.sanitize(font, text);
List<String> lines = TextMetrics.splitIntoLines(font, size, clean, width);
if (lines.size() <= maximum) {
return clean;
}
List<String> first = new ArrayList<>(lines.subList(0, maximum));
String last = TextMetrics.truncateWithEllipsis(font, size,
first.get(maximum - 1) + TextMetrics.ELLIPSIS, width);
first.set(maximum - 1, last);
return String.join(" ", first);
}It's called when creating the rows, with the inner width of the description column: table.columnWidth(1) - 2 * Measures.mm(1.6) and the style's size of 8.5. It's the same technique as exercise 3 in lesson 02-04, now applied outside TextBlock. On a real invoice, it's also a good idea to log a warning that a description has been truncated.
Conclusion
Your documents no longer have a length limit. You've learned to measure before drawing and to decide with ContentBox.fits whether something fits, to reserve space for the footer, to break pages in the safe order (close, create, open, header) and to wrap it all up in Paginator, which is closed with try-with-resources before saving. Table now spreads its rows across pages without splitting them, repeats its header, avoids orphan headers and can show "Carried forward". InvoiceHeader has a compact version for continuation pages, and PageFooter numbers "Page X of N" in a second pass with AppendMode.APPEND and resetContext.
The invoice now takes up as many pages as it needs, but modern invoices usually include more than text and tables: a QR code that lets them be verified and, on delivery notes, a barcode with its number so it can be read with a scanner in the warehouse. PDFBox doesn't generate codes, so in the next lesson we'll use ZXing to calculate them and learn to draw them as sharp vectors, respecting their minimum size and quiet zone.
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
