PDF isn't HTML: there are no paragraphs that automatically fit the available width, no text-align: right, and no "this doesn't fit, move it to the next line". showText draws a string from a point and keeps going to the right even if it runs off the page. Everything a word processor does automatically (right-aligning amounts, centring a title, breaking the legal terms into lines, truncating a note that's too long) has to be programmed, and the first step is to measure the text. In this lesson you'll learn to calculate a text's real width and height from the font metrics, to align it left, centre, right and justified, to implement your own line-breaking (word-wrap) algorithm, to control the leading and to truncate with an ellipsis. All of this will end up in two InvoiceLab components: the TextMetrics utility and the TextBlock text box, which returns the height it used up so that elements can be stacked one below another.
Contents
- Measuring the width of a text
- Measuring the height: ascent, descent and cap height
- Aligning left, centre and right
- Aligning amounts
- Breaking text into lines (word-wrap)
- Leading
- Truncating with an ellipsis
- Justifying text
- The
TextBlocktext box - InvoiceLab example: title, totals, notes and legal terms
Measuring the width of a text
Every font describes the width of each glyph in glyph units: thousandths of the font size (an em). PDFBox adds up the widths of the characters in a string with PDFont.getStringWidth(String), which returns the result in those units. To convert it to points:
Example with Helvetica: getStringWidth("Invoice") returns 3168. At 12 pt, the text measures 3168 / 1000 × 12 = 38.02 pt (about 13.4 mm). At 24 pt it would measure exactly twice as much: width is proportional to size.
Let's start the TextMetrics utility class in com.invoicelab.pdf:
package com.invoicelab.pdf;
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;
import org.apache.pdfbox.pdmodel.font.PDFontDescriptor;
/**
* Text measurement and placement. All measurements are returned in points.
*/
public final class TextMetrics {
public static final String ELLIPSIS = "…"; // …
private TextMetrics() {
}
/** Width of the text in points for the given font and size. */
public static float width(PDFont font, float size, String text) throws IOException {
return font.getStringWidth(text) / 1000f * size;
}
// ... the remaining methods will be added in the following sections ...
}Important details:
getStringWidthuses the same encoding asshowText: if the font lacks a character, it also throwsIllegalArgumentException. Always measure the already sanitized text (lesson 02-03), the same text you're going to draw.- The measured width does not include the character spacing (
Tc) or word spacing (Tw) from lesson 02-02. If you use them, add them on:Tc × number of characters. - Kerning (adjustment between pairs such as "AV") isn't applied by
showText, so the measurement matches what gets drawn.
Measuring the height: ascent, descent and cap height
The height of a text doesn't depend on the string but on the font. Every font has a baseline (the line the letters sit on, which is the y you pass to newLineAtOffset) and several measurements relative to it, stored in the font descriptor (PDFontDescriptor), also in thousandths of an em:
flowchart TB
A["Ascent (getAscent): top of letters such as 'd', 'l', 'É'"]
C["Cap height (getCapHeight): top of 'H', 'F', '1'"]
X["x-height (getXHeight): top of 'x', 'a', 'e'"]
B["BASELINE: y of newLineAtOffset"]
D["Descent (getDescent, negative): bottom of 'p', 'g', 'j'"]
A --> C --> X --> B --> D
| Metric | Method | Helvetica | DejaVu Sans |
|---|---|---|---|
| Ascent | getFontDescriptor().getAscent() |
718 | 928 |
| Cap height | getFontDescriptor().getCapHeight() |
718 | 729 |
| x-height | getFontDescriptor().getXHeight() |
523 | — |
| Descent | getFontDescriptor().getDescent() |
−207 | −236 |
Notice that DejaVu Sans is "taller" than Helvetica at the same nominal size: that's why, when you change fonts, it's best to recalculate positions rather than reuse fixed numbers. Let's add the height methods to TextMetrics, always returning positive values in points so we don't have to drag signs around:
/** Distance from the baseline to the top of the letters (positive). */
public static float ascent(PDFont font, float size) {
return descriptor(font).getAscent() / 1000f * size;
}
/** Distance from the baseline to the bottom of the letters (positive). */
public static float descent(PDFont font, float size) {
return -descriptor(font).getDescent() / 1000f * size;
}
/** Height of capital letters (useful for vertically centring uppercase text or numbers). */
public static float capHeight(PDFont font, float size) {
float cap = descriptor(font).getCapHeight();
if (cap <= 0) { // some fonts don't declare it
cap = descriptor(font).getAscent() * 0.7f;
}
return cap / 1000f * size;
}
private static PDFontDescriptor descriptor(PDFont font) {
PDFontDescriptor fd = font.getFontDescriptor();
if (fd == null) {
throw new IllegalArgumentException("Font " + font.getName() + " has no descriptor");
}
return fd;
}What is each one for?
- Ascent: for placing text below a top edge. If you want the tops of the letters to touch
yTop, the baseline goes atyTop - ascent. That's whatTextBlockwill do. - Ascent + descent: the total height of a line of text, from the tallest letter to the lowest.
- Cap height: for vertically centring text inside a box (a cell, a button). Numbers and capital letters have no descenders, so centring with the cap height gives a more visually balanced result.
You may come across the
PDFont.getHeight(int code)method. Avoid it for layout: its result depends on the font type (with Helvetica it returns 718; with aPDType0Font, a number with no obvious relationship). The descriptor is consistent for all of them.
Aligning left, centre and right
With the width sorted out, aligning is simple arithmetic on the starting x coordinate:
| Alignment | Reference x |
x where the text starts |
|---|---|---|
| Left | Left edge | x |
| Centre | Centre | x − width / 2 |
| Right | Right edge | x − width |
We define an enum for the alignment (we'll also use it for tables in module 3):
package com.invoicelab.pdf;
/** Horizontal alignment of a text. */
public enum Alignment {
LEFT, CENTER, RIGHT, JUSTIFIED
}And a TextMetrics method that writes one line aligned relative to a point:
/**
* Writes a line aligned relative to x:
* LEFT = x is the left edge, CENTER = x is the centre, RIGHT = x is the right edge.
* y is the baseline. Opens and closes its own text object.
*/
public static void writeAligned(PDPageContentStream content, PDFont font, float size,
String text, float x, float y, Alignment alignment)
throws IOException {
float textWidth = width(font, size, text);
float xStart = switch (alignment) {
case CENTER -> x - textWidth / 2;
case RIGHT -> x - textWidth;
default -> x; // LEFT (and JUSTIFIED on a single line)
};
content.beginText();
content.setFont(font, size);
content.newLineAtOffset(xStart, y);
content.showText(text);
content.endText();
}- It uses an arrow-style
switch(Java 14+), which returns a value and needs nobreak. - The method opens and closes its own
BT … ET: that way the position is absolute and you don't have to worry aboutnewLineAtOffsetbeing relative. - Justified text on a single line makes no sense; it's treated as left-aligned.
Typical use, centring the title in the content box:
float centre = box.left() + box.width() / 2;
TextMetrics.writeAligned(content, bold, 18, "INVOICE F-2026-0001", centre, y, Alignment.CENTER);Aligning amounts
On an invoice, amounts are always right-aligned: that way the units, the decimals and the decimal comma line up in a column and can be added up at a glance.
Bad (left-aligned) Good (right-aligned)
Taxable base 1.234,50 € Taxable base 1.234,50 €
VAT (21%) 259,25 € VAT (21%) 259,25 €
TOTAL 1.493,75 € TOTAL 1.493,75 €Since Nebula Distribution is a Spanish company, its amounts are formatted Spanish-style: use NumberFormat with the es-ES locale, and BigDecimal for money (never double, which accumulates rounding errors):
NumberFormat euros = NumberFormat.getCurrencyInstance(new Locale("es", "ES"));
String amount = euros.format(new BigDecimal("1234.50")); // "1.234,50 €"The result contains a non-breaking space (U+00A0) between the number and the € sign, so they never end up on different lines. Both WinAnsi and DejaVu Sans include it, so it needs no special handling. With all that in place, writing the totals block is easy: labels left-aligned in one column and amounts right-aligned against the edge of the content box.
String[][] totals = {
{ "Taxable base", euros.format(new BigDecimal("1234.50")) },
{ "VAT (21%)", euros.format(new BigDecimal("259.25")) },
{ "TOTAL", euros.format(new BigDecimal("1493.75")) } };
float xLabels = box.right() - Measures.mm(70);
for (String[] row : totals) {
PDFont f = row[0].equals("TOTAL") ? bold : regular;
y -= 14;
TextMetrics.writeAligned(content, f, 10, row[0], xLabels, y, Alignment.LEFT);
TextMetrics.writeAligned(content, f, 10, row[1], box.right(), y, Alignment.RIGHT);
}Since all the amounts have two decimal places and the digits in almost every font have the same width (tabular figures), right-aligning also lines up the decimal commas in a column.
Breaking text into lines (word-wrap)
The invoice's general terms are paragraphs of several sentences. To fit them into the width of the content box, they have to be broken into lines. We'll use the greedy algorithm, the same one most word processors use: fit as many words on each line as possible.
flowchart TD
A["Next word"] --> B{"Does line + ' ' + word<br/>fit in the width?"}
B -- Yes --> C["Add it to the line"] --> A
B -- No --> D["Close the current line<br/>and start another"]
D --> E{"Does the word on its own<br/>fit in the width?"}
E -- Yes --> F["The word starts the new line"] --> A
E -- No --> G["Split it by characters<br/>(URL, IBAN, long reference)"] --> A
In addition, the algorithm treats the \n line breaks in the original text as end of paragraph. The implementation in TextMetrics:
/**
* Breaks a text into lines no wider than maxWidth (greedy algorithm).
* Treats '\n' line breaks as end of paragraph (returns "" for blank lines).
*/
public static List<String> splitIntoLines(PDFont font, float size, String text, float maxWidth)
throws IOException {
List<String> lines = new ArrayList<>();
for (String paragraph : text.split("\r?\n", -1)) {
String[] words = paragraph.trim().split("\\s+");
StringBuilder line = new StringBuilder();
for (String word : words) {
if (word.isEmpty()) {
continue;
}
String candidate = line.isEmpty() ? word : line + " " + word;
if (width(font, size, candidate) <= maxWidth) {
line.setLength(0);
line.append(candidate);
continue;
}
// The word doesn't fit on the current line: close the line
if (!line.isEmpty()) {
lines.add(line.toString());
line.setLength(0);
}
// Does it fit on its own? If not (a very long URL or IBAN), split it by characters
while (width(font, size, word) > maxWidth) {
int cut = breakPoint(font, size, word, maxWidth);
lines.add(word.substring(0, cut));
word = word.substring(cut);
}
line.append(word);
}
lines.add(line.toString()); // last line of the paragraph (may be "")
}
return lines;
}
/** How many characters from the start of the word fit in maxWidth (at least 1). */
private static int breakPoint(PDFont font, float size, String word, float maxWidth)
throws IOException {
int cut = 1;
while (cut < word.length()
&& width(font, size, word.substring(0, cut + 1)) <= maxWidth) {
cut++;
}
if (Character.isHighSurrogate(word.charAt(cut - 1)) && cut < word.length()) {
cut++; // don't split a surrogate pair
}
return cut;
}Step-by-step explanation:
text.split("\r?\n", -1)separates the paragraphs, accepting both Windows (\r\n) and Unix (\n) line breaks. The-1keeps trailing empty paragraphs (an intentional blank line).paragraph.trim().split("\\s+")separates the words on one or more spaces or tabs: that way double spaces in the original text don't produce double gaps.- For each word the candidate line is built and measured. Measuring the whole line (rather than adding up word widths) avoids rounding errors and accounts for the space.
- If it doesn't fit, the current line is closed and the word starts the next one.
- If the word on its own is wider than the box (an IBAN or a URL), it's split by characters with
breakPoint, which looks for the longest prefix that fits (always at least one character, to avoid an infinite loop if the box is tiny). - At the end of each paragraph its last line is added, even if it's empty: it's a blank line the reader expected.
The algorithm measures the same string many times; for the text in an invoice (a few hundred words) the cost is negligible. If you ever lay out documents hundreds of pages long, you can optimize it by adding up word widths.
The line breaks in the original text are used here to separate paragraphs and never reach
showText, which doesn't accept them. Tabs disappear when splitting on\\s+.
Leading
Leading is the distance between the baselines of two consecutive lines. We'll express it as a factor of the font size, which is how designers think about it:
| Factor | Effect | Use |
|---|---|---|
| 1.0 | Very tight lines; descenders almost touch the capitals of the next line | Single-line labels |
| 1.15-1.25 | Compact | Tables, small print |
| 1.3-1.4 | Comfortable | Running text paragraphs (our default: 1.3) |
| 1.5 or more | Very airy | Text for on-screen reading, drafts |
The height of a block of n lines, from the top of the first line to the bottom of the last, is:
This is the value that will let us stack elements: if a block starts at y and measures height, the next one can start at y − height − gap.
Truncating with an ellipsis
Some texts must take up a single line: a description in a table cell, a customer name in a list, the notes in a compact header. If they don't fit, the usual solution is to cut them off and add an ellipsis (…, the U+2026 character, available in WinAnsi and in DejaVu):
/** Returns the text unchanged if it fits; otherwise shortens it and appends "…" so it fits in maxWidth. */
public static String truncateWithEllipsis(PDFont font, float size, String text, float maxWidth)
throws IOException {
if (width(font, size, text) <= maxWidth) {
return text;
}
float ellipsisWidth = width(font, size, ELLIPSIS);
int end = text.length();
while (end > 0 && width(font, size, text.substring(0, end)) + ellipsisWidth > maxWidth) {
end--;
if (end > 0 && Character.isLowSurrogate(text.charAt(end))) {
end--; // don't split a surrogate pair (emojis, extended CJK)
}
}
return text.substring(0, end).stripTrailing() + ELLIPSIS;
}- If the text fits, it's returned untouched (the most common case, and the fastest).
- If not, characters are removed from the end until text + ellipsis fit.
stripTrailing()avoids results such as"Notes: deliver …", with an ugly space before the ellipsis.- It follows the rule from the previous lesson: never split a character that takes up two
chars.
Truncating hides information. Use it only for text that has a complete source elsewhere (the order, the customer record) and never for legally significant data such as amounts or VAT IDs.
Justifying text
A justified paragraph has both edges straight: every line (except the last one in the paragraph) is stretched to fill the full width by distributing the leftover space among the gaps between words. It's the traditional style for legal terms.
The obvious way would be setWordSpacing (the Tw operator), but as we saw in lessons 02-02 and 02-03, viewers ignore it with PDType0Font fonts, which are the ones InvoiceLab uses. The alternative that works with any font is the TJ operator (showTextWithPositioning), which accepts numbers between text fragments: after each gap we insert a negative offset (which moves things apart) equivalent to the extra space.
For a line with natural width lineWidth in a box of width width, with g gaps between words:
The minus sign and the division by the size come from the definition of TJ (thousandths of the font size; negative = move apart). The implementation is in TextBlock, which we'll look at next. The last line of each paragraph is not justified: stretching a line with two words would produce huge gaps.
The TextBlock text box
Let's bring everything together in a class that represents a fixed-width text block: it takes the font, size and width; it's configured with alignment and line spacing (using chainable methods); and when drawn from a top edge it returns the height it used up.
package com.invoicelab.pdf;
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 text box: breaks the text into lines, aligns it and draws it
* from a top edge, returning the height used up.
*/
public final class TextBlock {
/** An already split line and whether it's the last one of its paragraph (not justified). */
private record Line(String text, boolean endOfParagraph) {
}
private final PDFont font;
private final float size;
private final float width;
private float lineSpacingFactor = 1.3f;
private Alignment alignment = Alignment.LEFT;
public TextBlock(PDFont font, float size, float width) {
this.font = font;
this.size = size;
this.width = width;
}
/** Line spacing as a multiple of the font size (1.0 = no extra space). */
public TextBlock lineSpacing(float factor) {
this.lineSpacingFactor = factor;
return this;
}
public TextBlock alignment(Alignment alignment) {
this.alignment = alignment;
return this;
}
/** Distance between consecutive baselines, in points. */
public float leading() {
return size * lineSpacingFactor;
}
/** Height the text will take up, without drawing it (to decide whether it fits). */
public float measureHeight(String text) throws IOException {
return heightOf(split(text).size());
}
/**
* Draws the text with its top edge at yTop and its left edge at x.
* @return the height used up, in points (to place the next element below it)
*/
public float draw(PDPageContentStream content, String text, float x, float yTop)
throws IOException {
List<Line> lines = split(text);
float yBase = yTop - TextMetrics.ascent(font, size); // first baseline
content.beginText();
content.setFont(font, size);
float xPrevious = 0;
float yPrevious = 0;
for (Line line : lines) {
float lineWidth = TextMetrics.width(font, size, line.text());
float xLine = switch (alignment) {
case CENTER -> x + (width - lineWidth) / 2;
case RIGHT -> x + width - lineWidth;
default -> x; // LEFT and JUSTIFIED
};
// newLineAtOffset is relative: we move by the difference from the previous line
content.newLineAtOffset(xLine - xPrevious, yBase - yPrevious);
xPrevious = xLine;
yPrevious = yBase;
if (alignment == Alignment.JUSTIFIED && !line.endOfParagraph()) {
writeJustified(content, line.text(), lineWidth);
} else if (!line.text().isEmpty()) {
content.showText(line.text());
}
yBase -= leading();
}
content.endText();
return heightOf(lines.size());
}
// ---------------------------------------------------------------- private
private List<Line> split(String text) throws IOException {
List<Line> result = new ArrayList<>();
for (String paragraph : text.split("\r?\n", -1)) {
List<String> lines = TextMetrics.splitIntoLines(font, size, paragraph, width);
for (int i = 0; i < lines.size(); i++) {
result.add(new Line(lines.get(i), i == lines.size() - 1));
}
}
return result;
}
private float heightOf(int lineCount) {
if (lineCount == 0) {
return 0;
}
return TextMetrics.ascent(font, size)
+ (lineCount - 1) * leading()
+ TextMetrics.descent(font, size);
}
/** Distributes the leftover space among the line's gaps using TJ. */
private void writeJustified(PDPageContentStream content, String line, float lineWidth)
throws IOException {
String[] words = line.split(" ");
if (words.length < 2) {
content.showText(line);
return;
}
float extraPerGap = (width - lineWidth) / (words.length - 1);
// In TJ the numbers are in thousandths of the font size; negative = move apart
float adjustment = -extraPerGap * 1000f / size;
List<Object> parts = new ArrayList<>();
for (int i = 0; i < words.length; i++) {
boolean last = (i == words.length - 1);
parts.add(last ? words[i] : words[i] + " ");
if (!last) {
parts.add(adjustment);
}
}
content.showTextWithPositioning(parts.toArray());
}
}The design decisions, one by one:
- The private
Linerecord stores whether the line closes a paragraph. That's whysplitprocesses the paragraphs one at a time: it's the only way to know which is the last line and not justify it. - Chainable methods (
lineSpacingandalignmentreturnthis): they let you writenew TextBlock(f, 8, width).alignment(JUSTIFIED).lineSpacing(1.35f). - The top edge, not the baseline: whoever uses the class thinks in boxes ("this block starts here"). The first baseline is calculated by subtracting the ascent, so the tallest letters touch
yTopexactly. - A single text object for all the lines, with relative
newLineAtOffset: it moves by the difference between the new position and the previous one. This is more efficient than opening aBTper line and produces a more compact stream. measureHeightwithout drawing: essential for deciding before drawing whether a block fits in what's left of the page (withbox.fits(y, height)from lesson 02-01). It will be the basis for pagination in module 3.drawreturns the height used up: the calling code only has to subtract it from itsyto place the next element.
InvoiceLab example: title, totals, notes and legal terms
Let's put all the pieces together on one page: the centred title, the totals block with right-aligned amounts, some notes truncated to a single line and the justified general terms. Notice the y cursor pattern: a y variable that starts at the top edge of the content box and moves down as things are drawn.
package com.invoicelab.examples;
import com.invoicelab.pdf.Alignment;
import com.invoicelab.pdf.TextBlock;
import com.invoicelab.pdf.ContentBox;
import com.invoicelab.pdf.InvoiceLabFonts;
import com.invoicelab.pdf.Measures;
import com.invoicelab.pdf.TextMetrics;
import com.invoicelab.pdf.ReferenceGrid;
import java.io.IOException;
import java.math.BigDecimal;
import java.nio.file.Files;
import java.nio.file.Path;
import java.text.NumberFormat;
import java.util.Locale;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
import org.apache.pdfbox.pdmodel.font.PDFont;
public class TextLayout {
private static final String TERMS =
"Payment must be made within a maximum of 30 days from the issue date of this invoice by "
+ "bank transfer to the account indicated. In the event of late payment, the default interest "
+ "provided for in current legislation on late payment in commercial transactions will be "
+ "applied.\n"
+ "Goods travel at the buyer's expense and risk. Any delivery issue must be reported in "
+ "writing within 48 hours of receipt. "
+ "Nebula Distribution Ltd. is a fictitious company created for training purposes.";
public static void main(String[] args) throws IOException {
Files.createDirectories(Path.of("output"));
NumberFormat euros = NumberFormat.getCurrencyInstance(new Locale("es", "ES"));
try (PDDocument document = new PDDocument()) {
InvoiceLabFonts fonts = new InvoiceLabFonts(document);
PDFont regular = fonts.regular();
PDFont bold = fonts.bold();
PDPage page = new PDPage(PDRectangle.A4);
document.addPage(page);
ContentBox box = ContentBox.invoice(page.getMediaBox());
try (PDPageContentStream content = new PDPageContentStream(document, page)) {
if (Boolean.getBoolean("invoicelab.grid")) {
ReferenceGrid.draw(content, page.getMediaBox());
}
float y = box.top();
// 1) Title centred in the content box
float centre = box.left() + box.width() / 2;
y -= TextMetrics.ascent(bold, 18);
TextMetrics.writeAligned(content, bold, 18, "INVOICE F-2026-0001",
centre, y, Alignment.CENTER);
y -= TextMetrics.descent(bold, 18) + Measures.mm(8);
// 2) Right-aligned amounts (the decimal comma lines up in a column)
String[][] totals = {
{ "Taxable base", euros.format(new BigDecimal("1234.50")) },
{ "VAT (21%)", euros.format(new BigDecimal("259.25")) },
{ "TOTAL", euros.format(new BigDecimal("1493.75")) } };
float xLabels = box.right() - Measures.mm(70);
for (String[] row : totals) {
PDFont f = row[0].equals("TOTAL") ? bold : regular;
y -= 14;
TextMetrics.writeAligned(content, f, 10, row[0], xLabels, y, Alignment.LEFT);
TextMetrics.writeAligned(content, f, 10, row[1], box.right(), y, Alignment.RIGHT);
}
y -= Measures.mm(10);
// 3) Single-line notes, truncated if they don't fit
String notes = "Notes: deliver to unit 3 on the industrial estate, ask for the warehouse "
+ "manager, unloading hours from 8:00 to 14:00, Monday to Friday";
String truncated = TextMetrics.truncateWithEllipsis(regular, 9, notes, box.width());
TextMetrics.writeAligned(content, regular, 9, truncated, box.left(), y,
Alignment.LEFT);
y -= Measures.mm(8);
// 4) Legal terms: justified paragraphs in a fixed-width box
TextBlock title = new TextBlock(bold, 9, box.width());
y -= title.draw(content, "GENERAL TERMS AND CONDITIONS", box.left(), y);
y -= Measures.mm(2);
TextBlock terms = new TextBlock(regular, 8, box.width())
.alignment(Alignment.JUSTIFIED)
.lineSpacing(1.35f);
float height = terms.draw(content, TERMS, box.left(), y);
y -= height;
System.out.printf("Terms: %.1f pt (%.1f mm); next element at y = %.1f%n",
height, Measures.toMm(height), y);
}
document.save("output/text-layout.pdf");
}
}
}Console output:
Things to look out for when you open the PDF:
- The title is exactly centred, with no by-eye calculations.
- The amounts form a perfect column flush with the right margin, with the decimal commas aligned.
- The notes end with "from 8:0…": they don't overflow the box.
- The terms have both edges straight, except for the last line of each paragraph.
- The grid is enabled with the system property we suggested in lesson 02-01: run with
-Dinvoicelab.grid=trueto check the measurements.Boolean.getBoolean(name)returnstrueonly if that property exists and is set to"true".
Common Mistakes and Tips
- Forgetting to divide by 1000.
getStringWidthreturns thousandths of an em; without/ 1000f * sizeyou'll get widths of thousands of points. - Measuring with one font and drawing with another (or at another size). A measurement is only valid for the font + size combination it was made with. Use the same variables in both places.
- Measuring unsanitized text.
getStringWidththrows the same exception asshowTextfor characters with no glyph. - Confusing the baseline with the top edge.
newLineAtOffsettakes the baseline; if you put the "top edge" of a block there, the text will stick out above it. Subtract the ascent. - Justifying with
setWordSpacingusing embedded fonts. It's ignored withPDType0Font; useTJasTextBlockdoes. - Justifying the last line of the paragraph. It produces huge gaps; leave it left-aligned.
- Using
doublefor amounts.0.1 + 0.2isn't0.3indouble. UseBigDecimalandNumberFormatwithes-ES. - Truncating important data. The ellipsis is for descriptive text, never for amounts, VAT IDs or invoice numbers.
- Tip: when something doesn't fit, enable the grid and print the measurements with
Measures.toMm(...): it's much faster than trying numbers blindly.
Exercises
- A truly centred footer. Redo exercise 1 from lesson 02-02 (the footer with "Thank you for choosing Nebula Distribution" and "Invoice F-2026-0001 · Page 1 of 1"), centring both lines exactly in the content box and placing the lowest part of the second line right on the bottom edge of the content box.
- Does it fit or not? Write a snippet that, before drawing the general terms, calculates their height with
measureHeightand usesbox.fits(y, height)to decide: if they fit, draw them; if not, print "The terms move to the next page" to the console (real pagination arrives in module 3). Try it with size 8 and with size 30. - Maximum number of lines. Add a
maxLines(int n)option toTextBlockso that, if the text takes up more thannlines, only the firstnare drawn and the last one ends with an ellipsis. Think of the product descriptions in the invoice table to come.
Solutions
Solution 1.
float centre = box.left() + box.width() / 2;
PDFont italic = fonts.italic();
PDFont regular = fonts.regular();
// The lowest part of the second line touches the bottom edge: its baseline goes up by the descent
float yLine2 = box.bottom() + TextMetrics.descent(regular, 7);
float yLine1 = yLine2 + 11; // 11 pt leading
content.setNonStrokingColor(Color.GRAY);
TextMetrics.writeAligned(content, italic, 9, "Thank you for choosing Nebula Distribution",
centre, yLine1, Alignment.CENTER);
TextMetrics.writeAligned(content, regular, 7, "Invoice F-2026-0001 · Page 1 of 1",
centre, yLine2, Alignment.CENTER);
content.setNonStrokingColor(Color.BLACK);The coordinates are built from the bottom up because the footer is anchored to the bottom edge. Now, if you change the text, the centring stays exact.
Solution 2.
TextBlock terms = new TextBlock(regular, 8, box.width()).alignment(Alignment.JUSTIFIED);
float height = terms.measureHeight(TERMS);
if (box.fits(y, height)) {
y -= terms.draw(content, TERMS, box.left(), y);
} else {
System.out.printf("The terms move to the next page (they need %.0f pt, %.0f pt left)%n",
height, y - box.bottom());
}At size 8 they fit easily; at size 30, the terms take up more than 20 lines and the message appears. Measuring before drawing is the key idea behind pagination.
Solution 3.
private int maxLines = Integer.MAX_VALUE;
public TextBlock maxLines(int n) {
this.maxLines = n;
return this;
}
private List<Line> split(String text) throws IOException {
List<Line> result = new ArrayList<>();
for (String paragraph : text.split("\r?\n", -1)) {
List<String> lines = TextMetrics.splitIntoLines(font, size, paragraph, width);
for (int i = 0; i < lines.size(); i++) {
result.add(new Line(lines.get(i), i == lines.size() - 1));
}
}
if (result.size() > maxLines) {
List<Line> truncated = new ArrayList<>(result.subList(0, maxLines));
Line last = truncated.get(maxLines - 1);
// Append the ellipsis and let truncateWithEllipsis shorten whatever is needed
String withEllipsis = TextMetrics.truncateWithEllipsis(font, size,
last.text() + TextMetrics.ELLIPSIS, width);
truncated.set(maxLines - 1, new Line(withEllipsis, true)); // don't justify
return truncated;
}
return result;
}The trick is to append the ellipsis before truncating: if "line…" fits, truncateWithEllipsis returns it unchanged; if it doesn't, it removes characters from the end (first the ellipsis itself, then letters) and appends … again. Either way the result ends in an ellipsis and respects the width. For example, a product description limited to 2 lines in 60 mm comes out as "Hex head bolt in A2 stainless / steel, M8x40, with nylon…". Since measureHeight also uses split, the measured height takes the limit into account automatically. The last line is marked as end of paragraph so it isn't justified.
Conclusion
You no longer place text by eye: you measure width with getStringWidth / 1000 × size, you know about the baseline and the descriptor's vertical metrics (ascent, descent, cap height), you align left, centre and right (with amounts in a column), you break paragraphs with a greedy algorithm that respects paragraphs and over-long words, you control the leading, you truncate with an ellipsis, and you justify with TJ so it works with embedded fonts. All of this lives in TextMetrics and in TextBlock, whose central idea (draw from a top edge and return the height used up) we'll use to stack each section of the invoice.
The invoice text is now well placed, but a professional invoice also needs graphics: lines that separate sections, a box that highlights the totals, and Nebula Distribution's corporate colour band. In the next lesson we'll draw paths, rectangles and curves, and work with RGB, CMYK and grey colours, transparency and clipping.
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
