In lesson 01-04 we wrote our first line with five almost magical calls: beginText, setFont, newLineAtOffset, showText and endText. Now that we've mastered the coordinate system, it's time to understand what each one does, which PDF operators it generates, and what else text in a PDF can do: multiple lines with leading, absolute positioning with the text matrix, rotated text, colours, rendering modes (fill, stroke, invisible) and spacing adjustments. We'll work with the PDF's 14 standard fonts, which don't need any font file, and we'll discover their big limitation: they only support the characters in the WinAnsiEncoding encoding. As a practical example we'll write the issuer and customer data blocks of invoice F-2026-0001.
Contents
PDPageContentStreamin depth- Text objects:
BTandET - The text operators and their PDFBox methods
- Positioning text:
Td, leading withTLandT* - The text matrix
Tm: absolute position and rotated text - Showing text:
TjandTJ - The 14 standard fonts
- Text size, style and colour
- Rendering modes: fill, stroke, invisible
- Character and word spacing
- The WinAnsiEncoding limitation
- InvoiceLab example: issuer and customer details
PDPageContentStream in depth
PDPageContentStream is the class that writes PDF operators into a page's content stream. Every method you call appends one or more instructions to the stream; when you close it, PDFBox compresses it (if applicable) and links it into the page's /Contents entry. In addition, when you use a font or an image, it automatically registers it in the page's /Resources dictionary under a name such as /F1.
Constructors
| Constructor | Use |
|---|---|
new PDPageContentStream(document, page) |
The usual one for new pages. Replaces any existing content on the page |
new PDPageContentStream(document, page, AppendMode mode, boolean compress) |
Choose whether to overwrite, append to the end or prepend to the existing content, and whether to compress |
new PDPageContentStream(document, page, AppendMode mode, boolean compress, boolean resetContext) |
The same, but it also shields the new content from any graphics state left behind by the previous content |
The AppendMode enum has three values: OVERWRITE (the default), APPEND and PREPEND. They're essential for modifying existing PDFs (adding a stamp to an invoice that has already been generated, for example), and we'll study them in lesson 04-02. As long as we're generating new pages, the two-argument constructor is enough. In 01-05 you already used the variant with compress = false for debugging.
Usage rules
- One open content stream per page at a time. Open, draw and close; don't try to have two
PDPageContentStreaminstances open on the same page. - Close it before saving. Always use
try-with-resourcesfor the content stream, nested inside the one for the document. - Order matters. Whatever is written later is painted on top: a PDF draws in stream order, like layers of paint.
- It isn't thread-safe. Just like
PDDocument, each thread works with its own document.
try (PDDocument document = new PDDocument()) {
PDPage page = new PDPage(PDRectangle.A4);
document.addPage(page);
try (PDPageContentStream content = new PDPageContentStream(document, page)) {
// ... drawing operations ...
} // the stream is closed here and linked into the page
document.save("output/example.pdf");
}Text objects: BT and ET
All text in a PDF lives inside a text object, delimited by the BT (begin text) and ET (end text) operators. In PDFBox they correspond to beginText() and endText().
BT % starts the text object: the text matrix is reset to the identity
/F1 12 Tf % font and size
51.02 762.52 Td % position
(Invoice F-2026-0001) Tj % show text
ET % end of the text objectImportant rules:
- On
BT, the text position goes back to the origin(0, 0). Every text object starts "from scratch". - Inside
BT … ETonly text, text state and colour operators are allowed. You can't draw rectangles or insert images in there, nor usesaveGraphicsState(). - Text objects can't be nested: a
beginText()without itsendText()before the next one throws anIllegalStateException("Error: Nested beginText() calls are not allowed"). - If you close the content stream with a text object still open, PDFBox logs a warning: "You did not call endText(), some viewers won't display your text".
- The text state (font, leading, spacing, rendering mode) is not reset by
BT: it's part of the graphics state and persists until you change it or callrestoreGraphicsState(). That's why, whenever you change a spacing value or the rendering mode, you should set it back to normal when you're done.
The text operators and their PDFBox methods
This table is the lesson's "cheat sheet". Each PDPageContentStream method writes the operator shown:
| Operator | PDFBox method | What it does | Unit |
|---|---|---|---|
BT / ET |
beginText() / endText() |
Opens / closes a text object | — |
Tf |
setFont(font, size) |
Font and size | pt |
Td |
newLineAtOffset(tx, ty) |
Moves the start of the line relative to the start of the current line | pt |
TL |
setLeading(leading) |
Distance between baselines for T* |
pt |
T* |
newLine() |
Moves down one line (uses TL) |
— |
Tm |
setTextMatrix(Matrix) |
Sets the text matrix (absolute position, rotation, scale) | — |
Tj |
showText(String) |
Shows a string | — |
TJ |
showTextWithPositioning(Object[]) |
Shows strings with position adjustments between them | thousandths of an em |
Tc |
setCharacterSpacing(float) |
Extra space after each character | pt |
Tw |
setWordSpacing(float) |
Extra space at each blank space | pt |
Tz |
setHorizontalScaling(float) |
Widens or narrows the text | % (100 = normal) |
Ts |
setTextRise(float) |
Raises or lowers the baseline (superscripts) | pt |
Tr |
setRenderingMode(RenderingMode) |
Fill, stroke, invisible… | — |
Positioning text: Td, leading with TL and T*
newLineAtOffset is relative
The most common mistake with text in PDFBox is thinking that newLineAtOffset(x, y) places the text at the absolute position (x, y). In fact it moves the start of the line by adding (x, y) to the start of the current line. Since BT leaves the position at (0, 0), the first call does look absolute; the second one no longer does:
content.beginText();
content.newLineAtOffset(50, 700); // start of line at (50, 700)
content.showText("First line");
content.newLineAtOffset(0, -14); // relative! now at (50, 686)
content.showText("Second line");
content.newLineAtOffset(50, 700); // typical MISTAKE: now at (100, 1386), off the page
content.showText("Third line");
content.endText();Notice too that newLineAtOffset is measured from the start of the line, not from where the last text ended. That's why newLineAtOffset(0, -14) goes back to column 50 even though "First line" takes up several dozen points.
Leading with setLeading and newLine
To write several lines in a row it's more convenient to set the leading (the distance between the baselines of two consecutive lines) and use newLine(), which moves down exactly that distance and returns to the start of the line:
content.beginText();
content.setFont(helvetica, 10);
content.setLeading(13); // TL: 13 pt between baselines (1.3 x size)
content.newLineAtOffset(50, 700);
content.showText("Nebula Distribution Ltd.");
content.newLine(); // T*: equivalent to newLineAtOffset(0, -13)
content.showText("VAT ID: B00000000");
content.newLine();
content.showText("50001 Zaragoza");
content.endText();Leading of 1.2 to 1.4 times the font size is comfortable to read. If it equals the size, the lines touch; if it's much larger, the block looks like a loose list. In lesson 02-04 we'll calculate the leading from the font's real metrics.
showTextdoes not interpret\nline breaks: PDF text has no notion of a "paragraph". Each line is written with its ownshowText. If you pass a\n, you'll get an exception (we'll see this in the WinAnsiEncoding section).
The text matrix Tm: absolute position and rotated text
Inside a text object there's a text matrix that determines where and how each glyph is drawn, in the same way that the CTM from the previous lesson affects all drawing. Td and T* modify it relatively; Tm replaces it entirely. In PDFBox you use setTextMatrix(Matrix):
content.beginText();
content.setFont(helvetica, 12);
// Absolute position, nothing accumulated: equivalent to "go to (300, 500)"
content.setTextMatrix(Matrix.getTranslateInstance(300, 500));
content.showText("At (300, 500)");
// Another absolute position in the same text object
content.setTextMatrix(Matrix.getTranslateInstance(300, 480));
content.showText("At (300, 480)");
content.endText();And since it's a full matrix, it lets you rotate text. Spanish invoices commonly print the company's registration details vertically in the margin:
content.beginText();
content.setFont(helvetica, 9);
content.setNonStrokingColor(Color.GRAY);
// Rotated 90° (counter-clockwise), with its origin 8 mm to the right of the content box, at the bottom
content.setTextMatrix(Matrix.getRotateInstance(Math.toRadians(90),
box.right() + Measures.mm(8), box.bottom()));
content.showText("Nebula Distribution Ltd. · Registered in the Zaragoza Commercial Register (fictitious details)");
content.endText();The text reads from bottom to top along the right margin. In the stream you'll see 0 1 -1 0 566.9292 56.69291 Tm: that's the rotation matrix [cos 90 sin 90 −sin 90 cos 90 tx ty] with the translation included.
| When to use… | newLineAtOffset (Td) |
setTextMatrix (Tm) |
|---|---|---|
| Position | Relative to the start of the line | Absolute |
| Several lines of a block | Ideal (together with newLine) |
Possible, but more verbose |
| Text at independent positions | You have to open a new BT each time |
Ideal within a single BT |
| Rotated or scaled text | No | Yes |
Why not rotate the text with
transform(the CTM)? That works too (you have to do it outside theBT, betweensaveGraphicsStateandrestoreGraphicsState). The difference is scope: the CTM affects everything drawn afterwards; the text matrix only affects the text in the current object.
Showing text: Tj and TJ
showText(String) writes the Tj operator. PDFBox converts the Java string into the font's codes: ASCII characters appear readable in the stream, as in (VAT ID: B00000000) Tj, and if there are characters such as é or ·, PDFBox writes the string in hexadecimal: <636166E9> Tj (that's "café"). This is normal; it isn't an error.
showTextWithPositioning(Object[]) writes TJ, which alternates strings and numbers. Each number shifts the next fragment, in thousandths of the font size, and in a rather counter-intuitive direction: a positive number moves closer (shifts to the left) and a negative one moves apart.
content.beginText();
content.setFont(bold, 24);
content.newLineAtOffset(x, y);
// "A" and "V" move 120/1000 * 24 = 2.9 pt closer; then a gap of 400/1000 * 24 = 9.6 pt is left
content.showTextWithPositioning(new Object[] { "A", 120f, "V", -400f, "A" });
content.endText();This generates [(A)120 (V)-400 (A)] TJ. It's what word processors use for kerning (adjusting letter pairs such as "AV") and for justified text. We'll rarely use it in our own code, but it's worth recognizing when you extract text from other people's PDFs (module 6).
The 14 standard fonts
The PDF specification defines 14 fonts that every viewer must be able to display without the PDF embedding them. That's why you don't need any .ttf file to use them: the PDF only contains their name. In PDFBox 3 you create them like this:
(In PDFBox 2.x there were constants such as PDType1Font.HELVETICA; they were removed in version 3. If you find that code online, it's outdated.)
| Family | Regular | Bold | Italic | Bold italic | Look |
|---|---|---|---|---|---|
| Times | TIMES_ROMAN |
TIMES_BOLD |
TIMES_ITALIC |
TIMES_BOLD_ITALIC |
Serif, book style |
| Helvetica | HELVETICA |
HELVETICA_BOLD |
HELVETICA_OBLIQUE |
HELVETICA_BOLD_OBLIQUE |
Sans serif, modern |
| Courier | COURIER |
COURIER_BOLD |
COURIER_OBLIQUE |
COURIER_BOLD_OBLIQUE |
Monospaced, typewriter style |
| Symbol | SYMBOL |
— | — | — | Greek letters and mathematical symbols |
| ZapfDingbats | ZAPF_DINGBATS |
— | — | — | Pictograms (✓, ✗, ➔, ☎…) |
The following program generates a sample sheet with all of them:
package com.invoicelab.examples;
import com.invoicelab.pdf.ContentBox;
import com.invoicelab.pdf.Measures;
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;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import org.apache.pdfbox.pdmodel.font.Standard14Fonts;
public class StandardFontSampler {
public static void main(String[] args) throws IOException {
try (PDDocument document = new PDDocument()) {
PDPage page = new PDPage(PDRectangle.A4);
document.addPage(page);
ContentBox box = ContentBox.invoice(page.getMediaBox());
try (PDPageContentStream content = new PDPageContentStream(document, page)) {
PDType1Font label = new PDType1Font(Standard14Fonts.FontName.HELVETICA_OBLIQUE);
content.beginText();
content.newLineAtOffset(box.left(), box.yFromTop(Measures.mm(10)));
content.setLeading(26); // 26 pt between baselines
for (Standard14Fonts.FontName name : Standard14Fonts.FontName.values()) {
content.setFont(label, 8);
content.showText(name.name() + ": ");
content.setFont(new PDType1Font(name), 14);
content.showText(sampleText(name));
content.newLine(); // moves down 26 pt and back to the start of the line
}
content.endText();
}
document.save("output/standard-font-sampler.pdf");
}
}
/** Symbol and ZapfDingbats have no Latin letters: each has its own encoding. */
private static String sampleText(Standard14Fonts.FontName name) {
return switch (name) {
case SYMBOL -> "αβγ ∑ ≤ ≥ ≠"; // αβγ ∑ ≤ ≥ ≠
case ZAPF_DINGBATS -> "✓ ✔ ✗ ➔ ☎"; // ✓ ✔ ✗ ➔ ☎
default -> "Invoice F-2026-0001 · 1.234,56 €";
};
}
}Note several details:
Standard14Fonts.FontName.values()iterates over the 14 fonts in the enum.- Within the same line we can switch fonts between two
showTextcalls: the second piece of text continues exactly where the first one ended. - If you try to write "Invoice" with
SYMBOL, you'll getIllegalArgumentException: U+0049 ('I') is not available in the font Symbol, encoding: SymbolEncoding. Symbol and ZapfDingbats have their own encoding and only contain their own symbols. That's why theswitchpicks a different text for them. - When you run it you may see "Using fallback font LiberationSans for base font Symbol" in the log. It's a PDFBox warning: to measure and render text it needs the font's glyph outlines and, if it can't find the font on the system, it uses a similar one. It doesn't change the generated PDF, which only contains the font's name.
Pros and cons
| Pros | Cons |
|---|---|
| No font files to distribute | They only cover the characters in their encoding (WinAnsi for the text fonts) |
| The resulting PDF is very lightweight | The final look depends on the font the viewer has (Arial or Liberation Sans instead of Helvetica, for example) |
| Perfect for prototypes, tests and internal documents | Forbidden in PDF/A, the long-term archiving format (module 8), because it requires all fonts to be embedded |
| Metrics included in PDFBox: text can be measured | Not very distinctive typography for a brand image |
Text size, style and colour
Size
The size is the second parameter of setFont. A good starting point for business documents:
| Element | Suggested size |
|---|---|
| Document title ("INVOICE") | 18-22 pt |
| Issuer's company name | 12-14 pt |
| Body text (details, invoice lines) | 9-10 pt |
| Small labels, legal small print | 7-8 pt |
Style
In PDF there's no "bold mode": bold and italic are different fonts. To make a word bold, switch to HELVETICA_BOLD before writing it and back to HELVETICA afterwards. (Faking bold by stroking the outline of the text is possible with rendering modes, but the result is worse than a real bold font.)
It's a good idea to create fonts once and reuse the variables, rather than calling new PDType1Font(...) on every line; although standard fonts are lightweight, it keeps the code cleaner and builds a habit that will be mandatory with the embedded fonts in the next lesson.
Colour
Text is painted with the fill colour (non-stroking), the same one used to fill shapes:
content.setNonStrokingColor(new Color(31, 58, 95)); // java.awt.Color: corporate blue
content.setNonStrokingColor(0.5f); // 50% grey
content.setNonStrokingColor(0f, 0f, 0f); // black in RGB (values from 0 to 1)Colour is part of the graphics state: it stays in effect for everything you paint afterwards, including shapes and other text objects, until you change it. The stroke colour (stroking), used by the stroke rendering mode, is set with setStrokingColor. Colour spaces (RGB, CMYK, grey) are covered in lesson 02-05.
Rendering modes: fill, stroke, invisible
The Tr operator, setRenderingMode(RenderingMode), decides what happens with the shape of each letter:
Mode (RenderingMode) |
Tr value |
Effect | Practical use |
|---|---|---|---|
FILL |
0 | Fill (default) | Normal text |
STROKE |
1 | Outline only | Decorative headings, "hollow" watermarks |
FILL_STROKE |
2 | Fill and outline | Text with a border in another colour |
NEITHER |
3 | Invisible | Text layer of OCR'd scanned PDFs: not visible but searchable and copyable |
FILL_CLIP, STROKE_CLIP, FILL_STROKE_CLIP, NEITHER_CLIP |
4-7 | Like the previous ones, and they also use the text as a clipping path | Graphic effects (filling letters with an image) |
content.beginText();
content.setFont(bold, 28);
content.newLineAtOffset(x, y);
content.setNonStrokingColor(Color.LIGHT_GRAY); // fill colour
content.setStrokingColor(Color.DARK_GRAY); // stroke colour
content.showText("FILL ");
content.setRenderingMode(RenderingMode.STROKE);
content.showText("STROKE ");
content.setRenderingMode(RenderingMode.FILL_STROKE);
content.showText("BOTH");
content.setRenderingMode(RenderingMode.NEITHER);
content.showText(" hidden text"); // not visible, but it can be selected and searched
content.setRenderingMode(RenderingMode.FILL); // always restore it!
content.endText();The outline thickness is the graphics state's line width (setLineWidth, lesson 02-05). And remember: the rendering mode persists after endText(); if you forget to go back to FILL, all subsequent text will come out hollow or invisible.
Character and word spacing
| Method | Operator | Effect | Normal value |
|---|---|---|---|
setCharacterSpacing(float) |
Tc |
Adds (or removes, if negative) points after each character | 0 |
setWordSpacing(float) |
Tw |
Adds points at each space | 0 |
setHorizontalScaling(float) |
Tz |
Stretches or compresses glyphs horizontally | 100 |
setTextRise(float) |
Ts |
Shifts the baseline up (positive) or down | 0 |
content.setCharacterSpacing(2); // "S p a c e d"
content.showText("Character spacing = 2");
content.setCharacterSpacing(0); // back to normal
content.newLine();
content.setWordSpacing(10); // wider spaces
content.showText("Word spacing = 10");
content.setWordSpacing(0);Real-world uses in an invoice: slight character spacing (1 pt) on uppercase labels ("ISSUER", "CUSTOMER") gives a more elegant look, and setTextRise lets you write superscripts such as the "st" in "1st".
Note:
setWordSpacingonly works with single-byte encoded fonts, such as the standard ones. With the embedded Unicode fonts from the next lesson, the PDF ignores it. We'll take this into account when justifying text in lesson 02-04.
The WinAnsiEncoding limitation
In PDFBox the standard text fonts (Times, Helvetica, Courier) use the WinAnsiEncoding encoding, which is practically identical to Windows-1252. Each character takes up one byte, so there's only room for about 220 characters. That's enough for Spanish (á é í ó ú ü ñ Ñ ¿ ¡ ç º ª · and the € sign are all there), but not for much more. Check it for yourself:
package com.invoicelab.examples;
import java.io.IOException;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import org.apache.pdfbox.pdmodel.font.Standard14Fonts;
public class WinAnsiLimit {
public static void main(String[] args) throws IOException {
PDType1Font helvetica = new PDType1Font(Standard14Fonts.FontName.HELVETICA);
String[] tests = { "Total 2026: 1.234,56 €", "Ibáñez & Muñoz: ¿café?", "Łódź (Poland)",
"Customer: Ελλάδα", "→ See terms", "Line 1\nLine 2" };
for (String text : tests) {
try {
helvetica.encode(text); // the same thing showText does internally
System.out.println("OK " + text.replace("\n", "\\n"));
} catch (IllegalArgumentException e) {
System.out.println("ERROR " + e.getMessage());
}
}
}
}OK Total 2026: 1.234,56 €
OK Ibáñez & Muñoz: ¿café?
ERROR U+0141 ('Lslash') is not available in the font Helvetica, encoding: WinAnsiEncoding
ERROR U+0395 ('Epsilon') is not available in the font Helvetica, encoding: WinAnsiEncoding
ERROR U+2192 ('arrowright') is not available in the font Helvetica, encoding: WinAnsiEncoding
ERROR U+000A ('controlLF') is not available in the font Helvetica, encoding: WinAnsiEncodingfont.encode(text)converts the text into the font's bytes; it's whatshowTextdoes internally, so it lets us check without drawing anything.- The exception is an
IllegalArgumentException(unchecked): if you don't catch it, invoice generation is aborted and, if it was inside atry-with-resources, the document is closed without being saved. - The message identifies the exact character (
U+0141, the Polish "Ł"). Look at the last case: the\nline break isn't valid either.
Is this serious? For Nebula Distribution, yes: all it takes is a customer called "Łukasz Nowak", an address in Greek, or a sales rep typing an arrow "→" in the notes, and the invoice fails. On top of that, the look depends on the viewer's fonts. The professional solution is to embed TrueType fonts with Unicode support, which is exactly the topic of the next lesson.
InvoiceLab example: issuer and customer details
Let's put it all together in a real piece of the invoice: the title and two blocks in columns with the issuer's details (left) and the customer's details (right half). Each block has a grey, letter-spaced uppercase label, the company name in bold and the remaining lines in regular text. The data is fictitious and, for now, comes from lists; in module 3 it will come from the model classes (Customer, Invoice).
package com.invoicelab.examples;
import com.invoicelab.pdf.ContentBox;
import com.invoicelab.pdf.Measures;
import java.awt.Color;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.List;
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;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import org.apache.pdfbox.pdmodel.font.Standard14Fonts;
public class IssuerCustomerDetails {
private static final float TITLE_SIZE = 9;
private static final float DATA_SIZE = 10;
private static final float LEADING = 13; // 1.3 x data size
public static void main(String[] args) throws IOException {
Files.createDirectories(Path.of("output"));
PDFont regular = new PDType1Font(Standard14Fonts.FontName.HELVETICA);
PDFont bold = new PDType1Font(Standard14Fonts.FontName.HELVETICA_BOLD);
List<String> issuer = List.of(
"Nebula Distribution Ltd.",
"VAT ID: B00000000",
"12 Fictional Street, Unit 3",
"50001 Zaragoza",
"Tel. 976 000 000 · [email protected]");
List<String> customer = List.of(
"Example Hardware Co.",
"VAT ID: J00000000",
"45 Test Avenue",
"22001 Huesca");
try (PDDocument document = new PDDocument()) {
PDPage page = new PDPage(PDRectangle.A4);
document.addPage(page);
ContentBox box = ContentBox.invoice(page.getMediaBox());
float yBlocks = box.yFromTop(Measures.mm(35));
float xCustomer = box.left() + box.width() / 2 + Measures.mm(5);
try (PDPageContentStream content = new PDPageContentStream(document, page)) {
// Document title
content.beginText();
content.setFont(bold, 20);
content.newLineAtOffset(box.left(), box.yFromTop(Measures.mm(8)));
content.showText("INVOICE F-2026-0001");
content.endText();
writeBlock(content, "ISSUER", issuer, box.left(), yBlocks, regular, bold);
writeBlock(content, "CUSTOMER", customer, xCustomer, yBlocks, regular, bold);
}
document.save("output/issuer-customer-details.pdf");
}
}
/**
* Writes a label with its lines underneath. The first line (company name) is in bold.
* (x, y) is the label's baseline.
*/
private static void writeBlock(PDPageContentStream content, String label, List<String> lines,
float x, float y, PDFont regular, PDFont bold) throws IOException {
content.beginText();
content.newLineAtOffset(x, y);
content.setLeading(LEADING);
content.setNonStrokingColor(Color.GRAY);
content.setFont(bold, TITLE_SIZE);
content.setCharacterSpacing(1f); // letter-spaced, tag-style label
content.showText(label);
content.setCharacterSpacing(0f);
content.newLine();
content.setNonStrokingColor(Color.BLACK);
for (int i = 0; i < lines.size(); i++) {
content.setFont(i == 0 ? bold : regular, DATA_SIZE);
content.showText(lines.get(i));
content.newLine();
}
content.endText();
}
}A walk through the code:
- Style constants (
TITLE_SIZE,DATA_SIZE,LEADING): changing the look doesn't mean hunting for stray numbers throughout the code. - Positions calculated with
ContentBox: the title 8 mm below the top margin, the blocks at 35 mm. The customer block starts 5 mm to the right of the centre of the content box. writeBlockis reusable: oneBT … ETper block,newLineAtOffsetjust once to fix the corner, andsetLeading+newLineto move down line by line.- The values that are changed are restored (
setCharacterSpacing(0f), black colour) so they don't affect the following text. - The types are declared as
PDFont(the superclass) rather thanPDType1Font: that way, in the next lesson we'll be able to replace the standard fonts with embedded fonts without touchingwriteBlock.
If you generate the PDF uncompressed (lesson 01-05), you'll see the operators we've studied:
BT
51.02362 685.98425 Td
13 TL
/DeviceRGB cs
0.50196 0.50196 0.50196 sc
/F1 9 Tf
1 Tc
(ISSUER) Tj
0 Tc
T*
0 0 0 sc
/F1 10 Tf
(Nebula Distribution Ltd.) Tj
T*
/F2 10 Tf
(VAT ID: B00000000) Tj
T*
...
ET/F1 is Helvetica-Bold and /F2 is Helvetica, the names PDFBox assigned in the page's resources. The company name appears as a readable string because it only contains ASCII characters; the line with the "·" separator, on the other hand, would be written in hexadecimal.
Common Mistakes and Tips
- Using
newLineAtOffsetas if it were absolute. It's relative to the start of the current line. For absolute positions, open a newbeginText()or usesetTextMatrix. - Forgetting
setFontbeforeshowText. It throwsIllegalStateException: Must call setFont() before showText(). Every new content stream needs its ownsetFont. - Calling
beginText()twice in a row or drawing shapes insideBT … ET. Close the text before drawing anything else. - Not restoring the text state. Spacing, colour and rendering mode persist after
endText(). Set them back to their normal values or wrap the block insaveGraphicsState/restoreGraphicsState(outside theBT). - Passing text containing
\nor\ttoshowText: they aren't printable characters in WinAnsi and throwIllegalArgumentException. Split the text into lines before writing it. - Trusting that customer data will always be "Latin". With standard fonts, any character outside WinAnsi breaks generation. Validate it or switch to embedded fonts (next lesson).
- Old PDFBox 2.x code.
PDType1Font.HELVETICA_BOLDno longer exists; in PDFBox 3 you usenew PDType1Font(Standard14Fonts.FontName.HELVETICA_BOLD). - Tip: declare font variables as
PDFont; your code will then be independent of the concrete font type.
Exercises
- Legal footer. At the bottom of the content box of an A4 page, roughly centred "by eye", write the text "Thank you for choosing Nebula Distribution" in 9 pt
TIMES_ITALICin grey, and just below it (with 11 pt leading) "Invoice F-2026-0001 · Page 1 of 1" in 7 ptHELVETICA. Use a single text object. - "PAID" stamp. Write the word "PAID" in 48 pt
HELVETICA_BOLD, with only its outline in red (line width 1.5), rotated 30 degrees and positioned towards the centre of the page. Make sure any text you write afterwards comes out normally. - Validate before writing. Create a method
static boolean isRenderable(PDFont font, String text)that returnsfalseif the font can't encode the text, and use it to write "Customer: Łukasz Nowak" only if possible, or "Customer: (name cannot be displayed)" otherwise.
Solutions
Solution 1.
PDFont italic = new PDType1Font(Standard14Fonts.FontName.TIMES_ITALIC);
PDFont regular = new PDType1Font(Standard14Fonts.FontName.HELVETICA);
content.beginText();
content.setNonStrokingColor(Color.GRAY);
content.setFont(italic, 9);
content.newLineAtOffset(box.left() + Measures.mm(55), box.bottom() + Measures.mm(6));
content.showText("Thank you for choosing Nebula Distribution");
content.setLeading(11);
content.newLine(); // same column, 11 pt lower
content.setFont(regular, 7);
content.showText("Invoice F-2026-0001 · Page 1 of 1");
content.endText();
content.setNonStrokingColor(Color.BLACK);Centring "by eye" is awkward and fragile: if the text changes, it's no longer centred. In lesson 02-04 we'll learn to measure text so we can centre it precisely. Real pagination ("Page X of N") will arrive in module 3.
Solution 2.
content.saveGraphicsState(); // outside the BT
content.setStrokingColor(Color.RED);
content.setLineWidth(1.5f);
content.beginText();
content.setFont(new PDType1Font(Standard14Fonts.FontName.HELVETICA_BOLD), 48);
content.setRenderingMode(RenderingMode.STROKE);
content.setTextMatrix(Matrix.getRotateInstance(Math.toRadians(30), Measures.cm(7), Measures.cm(12)));
content.showText("PAID");
content.endText();
content.restoreGraphicsState(); // restores colour, line width and FILL modeThe saveGraphicsState/restoreGraphicsState pair wraps the whole block, so the red colour, the line width and the rendering mode (which is part of the graphics state) go back to their previous values without having to restore them one by one. A stamp like this on an existing invoice requires AppendMode.APPEND; we'll do that in lesson 04-02.
Solution 3.
static boolean isRenderable(PDFont font, String text) throws IOException {
try {
font.encode(text);
return true;
} catch (IllegalArgumentException e) {
return false;
}
}
// Usage
String name = "Customer: Łukasz Nowak";
content.showText(isRenderable(helvetica, name) ? name : "Customer: (name cannot be displayed)");With Helvetica the fallback text will be written, because "Ł" isn't in WinAnsi. Hiding the customer's name isn't acceptable on a real invoice, but this check is the basis of the fallback mechanism we'll build in the next lesson with Unicode fonts.
Conclusion
You now know PDF text from the inside: PDPageContentStream writes operators into the page's stream; text lives in BT … ET objects; Tf sets the font and size; Td and T* (with the TL leading) position lines relatively, and Tm allows absolute positions and rotated text; Tj and TJ show the text. You've worked with the 14 standard fonts, their styles, the fill colour, rendering modes and spacing, and you've written the issuer and customer blocks of invoice F-2026-0001.
You've also seen their limit: WinAnsiEncoding doesn't support characters such as Ł, → or the Greek alphabet, and the look of the standard fonts depends on the viewer. In the next lesson we'll solve both problems by embedding TrueType fonts with Unicode support (PDType0Font) and we'll create the InvoiceLabFonts class that every document in the project will use.
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
