In the previous lesson SupplierInvoiceReader read three supplier invoices by searching the full text with regular expressions. It worked, but we saw its weak spot: turning the page into plain text loses the geometry, and a label can end up separated from its value when there are columns. In this lesson we'll get that geometry back. First we'll extract text from rectangular areas of the page with PDFTextStripperByArea, which will let us define a template for each regular supplier. Then we'll go down to the level of TextPosition, the object that describes each character, to build TextLocator: a tool that gets every word with its position, font and size, rebuilds lines and columns, reads tables and finds the value to the right of or below a label such as "TOTAL".
Contents
- Two coordinate systems: PDF and "reading"
PDFTextStripperByArea: the text in an area- Per-supplier extraction templates:
SupplierTemplate TextPosition: the information about each character- Rotated pages:
getXversusgetXDirAdj - Subclassing
PDFTextStripper:TextLocator - Rebuilding lines
- Finding a label and reading its value
- Reading a table by columns
- Calibrating a template
Two coordinate systems: PDF and "reading"
In lesson 02-01 we learned that the PDF coordinate system has its origin at the bottom left and that y grows upwards. To draw the Supplies invoice number, the generator called newLineAtOffset(400, 724): 724 points from the bottom edge.
PDFBox's extraction classes use a different system, designed to read the way a person would:
| Aspect | PDF system (generating, 02-01) | Reading system (extracting) |
|---|---|---|
| Origin | Bottom-left corner of the MediaBox (usually) | Top-left corner of the visible area (CropBox) |
Direction of y |
Upwards | Downwards |
/Rotate rotation |
Not applied: you have to work it out (04-02) | Already applied: the page is measured as it's displayed |
| Unit | Point (1/72 inch) | Point |
| Used by | PDPageContentStream, PDRectangle, annotations |
PDFTextStripperByArea, TextPosition (getX, getY, *DirAdj) |
For an A4 page with no CropBox and no rotation, the conversion is simple: yReading = 842 − yPdf. The Supplies number (y = 724 in PDF) is at y ≈ 118 in reading coordinates. But watch out for the other two cases, which we checked with the sample PDFs:
- Offset CropBox: in
supplier-AP-7731.pdf(module 4) the CropBox starts at (20, 30). Text at PDF point (60, 750) appears in reading coordinates at x = 40, y = 62, that is, measured from the top-left corner of the CropBox (30 + 782 − 750 = 62), not of the whole page (which would give 92). - Rotated page: in the Transport invoice (
/Rotate 90), reading coordinates run from 0 to 842 horizontally and from 0 to 595 vertically: those of the landscape page the user sees.
flowchart LR
subgraph PDF["PDF system"]
A["(0,0) bottom-left<br/>y upwards<br/>no /Rotate"]
end
subgraph Reading["Reading system"]
B["(0,0) top-left of the CropBox<br/>y downwards<br/>with /Rotate applied"]
end
PDF -- "PDFTextStripper / TextPosition" --> Reading
Reading -- "Annotations.toPdf (06-05)" --> PDF
PDFTextStripperByArea: the text in an area
PDFTextStripperByArea is a subclass of PDFTextStripper that, instead of returning all the text, splits it into named regions:
try (PDDocument document = Loader.loadPDF(new File("output/suppliers/supplies-SF-2026-0412.pdf"))) {
PDFTextStripperByArea stripper = new PDFTextStripperByArea(); // declares IOException
stripper.setSortByPosition(true);
stripper.addRegion("number", new Rectangle2D.Float(395, 105, 180, 18)); // x, y, width, height
stripper.extractRegions(document.getPage(0)); // ONE page, 0-based
System.out.println("[" + stripper.getTextForRegion("number") + "]");
}addRegion(name, rectangle)defines an area in reading coordinates.Rectangle2D.Float(x, y, width, height)is the standard Java2D class:(x, y)is the top-left corner.extractRegions(PDPage)processes a single page (unlikegetText, which processes the document). For several pages you have to call it several times.getTextForRegion(name)returns the text in that area, with its trailing line break.getRegions()returns the names that have been defined.
If instead of (395, 105) we used (395, 724), the PDF value, the region would sit at the bottom of the page and return just a line break. It's the most common mistake with this class.
Which characters belong to a region
We ran three tests with the same invoice number to find out exactly what criterion PDFBox applies:
| Rectangle (x, y, width, height) | Result | Conclusion |
|---|---|---|
| (438, 117, 120, 2): a 2 pt strip over the baseline | SF-2026/0412 |
It's enough for it to contain each character's origin point |
| (438, 106, 120, 10): the "body" of the letters, stopping short of the baseline | (empty) | If the origin point falls outside, the character is left out even though it looks as if it's inside |
| (470, 106, 120, 15): starts halfway through the value | 6/0412 |
It cuts by character, not by word |
The point being compared is the glyph's origin: its left corner on the baseline. That's why, when designing a region, it's a good idea for it to stick out a few points below the baseline and to have some horizontal margin. Notice also the leading space in the first test: the space between Number: and the value was inside; a strip() takes care of it.
Per-supplier extraction templates: SupplierTemplate
With regions we can describe where each piece of data is on a regular supplier's invoices. If the supplier doesn't change its layout, a template is much more reliable than regular expressions: it doesn't depend on vocabulary or on text order.
package com.invoicelab.extraction;
/** Where each piece of data is on a particular supplier's invoices (zones measured with TextLocator). */
public record SupplierTemplate(String taxId, String name, Map<String, Zone> zones) {
public static final String NUMBER = "number";
public static final String DATE = "date";
public static final String TOTAL = "total";
/** A zone: page (1-based) and rectangle in reading coordinates (origin top-left, in points). */
public record Zone(int page, Rectangle2D area) {
public static Zone of(int page, float x, float y, float width, float height) {
return new Zone(page, new Rectangle2D.Float(x, y, width, height));
}
}
private static final Pattern AMOUNT = Pattern.compile("\\d{1,3}(?:\\.\\d{3})*,\\d{2}");
/** Templates for Nebula Distribution's (fictional) suppliers. */
public static final List<SupplierTemplate> KNOWN = List.of(
new SupplierTemplate("A33333333", "Fictional Supplies Inc.", Map.of(
NUMBER, Zone.of(1, 438, 106, 120, 15),
DATE, Zone.of(1, 420, 120, 110, 15),
TOTAL, Zone.of(1, 485, 305, 80, 16))),
new SupplierTemplate("B44444444", "Imaginary Stationery Ltd.", Map.of(
NUMBER, Zone.of(1, 395, 114, 150, 15),
DATE, Zone.of(1, 395, 146, 150, 15),
TOTAL, Zone.of(2, 145, 166, 80, 16))), // the total is on the second sheet
new SupplierTemplate("12345678Z", "Invented Transport", Map.of(
NUMBER, Zone.of(1, 605, 64, 90, 15), // page with /Rotate 90: coordinates as displayed
DATE, Zone.of(1, 555, 80, 200, 15),
TOTAL, Zone.of(1, 635, 432, 60, 17))));
public static Optional<SupplierTemplate> forTaxId(String taxId) {
return KNOWN.stream().filter(t -> t.taxId().equals(taxId)).findFirst();
}- The template is identified by the supplier's tax ID, which we already know how to read with
SupplierInvoiceReader(06-01). - Each zone states its page: in Stationery the total is on sheet 2.
- The zones cover only the value, not the label, so that we don't have to clean up the text afterwards. We'll see where these numbers come from in the last section.
- In a real system, templates would live in a database or a configuration file, not in the code.
Extraction groups the zones by page so that each page is processed only once:
/** The (raw) text of each zone. */
public Map<String, String> extract(PDDocument document) throws IOException {
Map<String, String> texts = new LinkedHashMap<>();
int pages = document.getNumberOfPages();
for (int page = 1; page <= pages; page++) {
PDFTextStripperByArea stripper = new PDFTextStripperByArea();
stripper.setSortByPosition(true);
for (Map.Entry<String, Zone> e : zones.entrySet()) {
if (e.getValue().page() == page) {
stripper.addRegion(e.getKey(), e.getValue().area());
}
}
if (stripper.getRegions().isEmpty()) {
continue; // nothing to read on this page
}
stripper.extractRegions(document.getPage(page - 1)); // getPage is 0-based
for (String region : stripper.getRegions()) {
texts.put(region, stripper.getTextForRegion(region).strip());
}
}
return texts;
}
/** Reads the invoice with this template and interprets each zone. */
public SupplierInvoiceData read(PDDocument document) throws IOException {
Map<String, String> t = extract(document);
String number = t.getOrDefault(NUMBER, "").isEmpty() ? null : t.get(NUMBER);
Matcher amount = AMOUNT.matcher(t.getOrDefault(TOTAL, ""));
BigDecimal total = amount.find() ? SupplierInvoiceReader.amount(amount.group()) : null;
return SupplierInvoiceReader.result(number, SupplierInvoiceReader.date(t.getOrDefault(DATE, "")),
taxId, total);
}
}Notice the reuse: the date in each zone is interpreted with SupplierInvoiceReader.date (which understands the three formats), the amount with SupplierInvoiceReader.amount, and the result is created with result, which adds the warnings. They're package-private methods: SupplierTemplate is in the same com.invoicelab.extraction package.
The complete flow combines the two lessons: generic reading to identify the supplier and, if we have a template, reading by zones.
SupplierInvoiceData generic = reader.read(document); // 06-01: regex over the whole text
Optional<SupplierTemplate> template = SupplierTemplate.forTaxId(generic.supplierTaxId());
SupplierInvoiceData data = template.isPresent()
? template.get().read(document) // 06-02: fixed zones
: generic;scanned-SF-2026-0412.pdf generic SupplierInvoiceData[number=null, ..., warnings=[The PDF has no text layer (scanned?): needs OCR]]
transport-2026-017.pdf template SupplierInvoiceData[number=2026-017, date=2026-01-05, supplierTaxId=12345678Z, total=89.54, warnings=[]]
stationery-PI-000873.pdf template SupplierInvoiceData[number=PI-000873, date=2026-01-20, supplierTaxId=B44444444, total=356.90, warnings=[]]
supplies-SF-2026-0412.pdf template SupplierInvoiceData[number=SF-2026/0412, date=2026-01-12, supplierTaxId=A33333333, total=1234.56, warnings=[]](This is the output of the ReadWithTemplates example, which walks through the folder like ReadSupplierInvoices.) The rotated Transport page works without doing anything special because the zones are in reading coordinates.
| Regular expressions (06-01) | Zone template (06-02) | |
|---|---|---|
| New suppliers | Yes, if they use a known vocabulary | No: you have to create the template |
| Columns | Problems | No problems |
| Supplier changes its layout | Usually keeps working | Fails (empty zone → warning) |
| Precision | Medium | High |
TextPosition: the information about each character
Under the hood, all these classes work with TextPosition objects: one per glyph drawn. Its most useful methods:
| Method | What it returns |
|---|---|
getUnicode() |
The glyph's text (usually one character; a ligature may be fi) |
getX(), getY() |
The glyph's origin in reading coordinates, with the page rotation applied. getY is the baseline |
getXDirAdj(), getYDirAdj() |
The same, but also corrected for the text direction, so that the text always reads "horizontally" |
getWidthDirAdj() |
The glyph's width in the text direction |
getHeightDir() |
The glyph's approximate height (PDFBox estimates it; it's usually a little less than the font size) |
getFont() |
The PDFont; getFont().getName() gives the name (Helvetica, AAACRO+DejaVuSans…) |
getFontSizeInPt() |
Effective size in points (takes matrix scaling into account) |
getDir() |
Text direction in degrees: 0, 90, 180 or 270 |
getRotation() |
The page's /Rotate |
getPageWidth(), getPageHeight() |
Size of the CropBox (unrotated) |
Actual values for the first character of some lines in our invoices:
| Text | getX |
getY |
getXDirAdj |
getYDirAdj |
getHeightDir |
getFontSizeInPt |
getDir |
getRotation |
|---|---|---|---|---|---|---|---|---|
FICTIONAL SUPPLIES INC. |
50.0 | 51.9 | 50.0 | 51.9 | 9.5 | 16 | 0 | 0 |
| AP-7731, page 1 | 40.0 | 62.0 | 40.0 | 62.0 | 8.1 | 28 | 0 | 0 |
AP-7731, page 2 (/Rotate 90) |
720.0 | 40.0 | 40.0 | 62.0 | 8.1 | 28 | 0 | 90 |
Invoice No. 2026-017 (Transport) |
560.0 | 75.3 | 560.0 | 75.3 | 6.1 | 11 | 90 | 90 |
Two details from the table:
- Delivery note AP-7731 was drawn with
setFont(helvetica, 28)and a 0.5 scale in effect:getFontSizeInPtreturns 28, but the text is displayed at 14 pt. If you need the visual size, usegetTextMatrix().getScalingFactorX(): that matrix already combines the font size with all the transformations, and for the delivery note it returns 14 (for Supplies, 16, the same as the nominal size). getHeightDir(9.5 for 16 pt text) is an estimate. To draw boxes around text it's better to use the font size, as we'll see.
Rotated pages: getX versus getXDirAdj
The previous table shows two different situations with /Rotate 90:
- Transport: the page is rotated and the text was drawn rotated the opposite way (with
Stamper.visibleMatrix). On screen it reads horizontally.getDir= 90 andgetXmatchesgetXDirAdj. - Delivery note AP-7731, page 2: the page is rotated, but the text was drawn "normally". On screen it appears vertical, running top to bottom.
getX/getY(720, 40) say where it is on the page as displayed (a vertical strip near the right-hand edge), whilegetXDirAdj/getYDirAdj(40, 62) "straighten" it as if the reader tilted their head.
Which one should you use?
- To group into lines and read (what
setSortByPositiondoes), the*DirAdjvalues: that way vertical text is rebuilt as a readable line. That's what we'll use inTextLocator. - To know where it is on screen,
getX/getY.PDFTextStripperByAreacompares againstgetX/getY: to capture the vertical text of the delivery note we had to use a vertical region, (700, 20, 40, 400); the region (30, 50, 500, 20), calculated from the DirAdj values, came back empty.
In practice, in the vast majority of documents the text reads horizontally on screen, and then both systems coincide.
Subclassing PDFTextStripper: TextLocator
PDFTextStripper is designed to be extended. As it walks through the page, it calls a series of protected methods that we can override. The most useful one is:
PDFBox calls it with each fragment of text it has rebuilt, together with the list of TextPosition objects for its characters. Careful: a fragment isn't always a word. We checked with Supplies: 8 Imaginary Street - 46001 Valencia - Tax ID: A33333333 arrived in a single call, because the PDF contains the spaces as real characters; on the other hand Bill to: and INVOICE, drawn separately at the same height, arrived in separate calls. So we'll have to split the fragments at the spaces.
package com.invoicelab.extraction;
/**
* Extracts the words on a page with their position, font and size.
* "Reading" coordinates: origin at the top-left of the visible area (CropBox), y downwards,
* already corrected for /Rotate and text direction (the *DirAdj values of TextPosition).
*/
public final class TextLocator extends PDFTextStripper {
/** A word. y = baseline measured from the top; height = approximate height of the glyphs. */
public record Word(String text, int page, float x, float y, float width, float height,
String font, float size) {
public float right() {
return x + width;
}
/** The word's box, in reading coordinates (top-left). */
public Rectangle2D box() {
return new Rectangle2D.Float(x, y - height, width, height);
}
/** "Line" box (from ascent to descent), based on the font size: better for highlighting. */
public Rectangle2D lineBox() {
return new Rectangle2D.Float(x, y - size * 0.8f, width, size);
}
}
/** Words that share (approximately) the same baseline. */
public record Line(float y, List<Word> words) {
public String text() {
return words.stream().map(Word::text).collect(Collectors.joining(" "));
}
}
private final List<Word> words = new ArrayList<>();
private TextLocator() {
setSortByPosition(true);
}
/** Words on a page (1-based, like setStartPage). */
public static List<Word> words(PDDocument document, int page) throws IOException {
TextLocator locator = new TextLocator();
locator.setStartPage(page);
locator.setEndPage(page);
locator.writeText(document, new StringWriter()); // we don't care about the text: only the calls
return List.copyOf(locator.words);
}- The constructor is private: the class is used through the static
wordsmethod, which creates a new locator each time (aPDFTextStripperkeeps state and mustn't be shared between threads). writeText(document, new StringWriter())sets the whole process in motion. We don't care about the resulting text (we throw it into aStringWriter); what matters are the calls towriteStringmade along the way.
Now the overridden method and how each word is built:
@Override
protected void writeString(String text, List<TextPosition> positions) throws IOException {
List<TextPosition> current = new ArrayList<>();
for (TextPosition p : positions) {
if (p.getUnicode().isBlank()) { // a space inside the fragment: closes the word
flushWord(current);
} else {
current.add(p);
}
}
flushWord(current);
super.writeString(text, positions);
}
private void flushWord(List<TextPosition> letters) {
if (letters.isEmpty()) {
return;
}
TextPosition first = letters.get(0);
TextPosition last = letters.get(letters.size() - 1);
StringBuilder text = new StringBuilder();
float height = 0;
for (TextPosition p : letters) {
text.append(p.getUnicode());
height = Math.max(height, p.getHeightDir());
}
float x = first.getXDirAdj();
float width = last.getXDirAdj() + last.getWidthDirAdj() - x;
words.add(new Word(withoutLigatures(text.toString()), getCurrentPageNo(), x, first.getYDirAdj(),
width, height, first.getFont().getName(), first.getFontSizeInPt()));
letters.clear();
}
/** TextPosition returns ligatures as they are ("fi"); getText() already breaks them up, here we do it by hand. */
static String withoutLigatures(String text) {
StringBuilder sb = new StringBuilder();
text.codePoints().forEach(c -> {
if (c >= 0xFB00 && c <= 0xFB06) { // ff fi fl ffi ffl ſt st
sb.append(Normalizer.normalize(Character.toString(c), Normalizer.Form.NFKC));
} else {
sb.appendCodePoint(c);
}
});
return sb.toString();
}- We go through the characters and each space "closes" the current word.
isBlank()recognises normal spaces and tabs, but not the non-breaking space: an amount such as1.470,85 €(with a non-breaking space) stays as one word. That's deliberate: a non-breaking space means precisely "don't split here". - The word's width runs from the origin of the first letter to the end of the last.
getCurrentPageNo()is an inherited method that returns the page being processed (1-based).- We call
super.writeStringso as not to break the parent class's normal behaviour. - Ligatures: when we printed the Stationery words,
Officeappeared with the glyphffi. It's not an extraction error: when writing with an embedded DejaVu font, PDFBox 3 applies the font's ligatures, and the PDF's/ToUnicodetable maps that glyph to the character U+FB03.getText()breaks them up automatically, butTextPosition.getUnicode()returns them as they are, so we do it ourselves. We don't apply NFKC to the whole text because it would also change other characters (Nºwould becomeNo, as we saw in 06-01), and we want to search for labels exactly as they appear.
Rebuilding lines
The words arrive sorted, but loose. To work with labels and values we group them into lines: words whose baselines differ by less than a tolerance.
/** Groups into lines the words whose baselines differ by less than 'tolerance' points. */
public static List<Line> lines(List<Word> words, float tolerance) {
List<Word> sorted = new ArrayList<>(words);
sorted.sort(Comparator.comparing(Word::y).thenComparing(Word::x));
List<Line> lines = new ArrayList<>();
List<Word> current = new ArrayList<>();
float currentY = Float.NaN;
for (Word w : sorted) {
if (!current.isEmpty() && Math.abs(w.y() - currentY) > tolerance) {
lines.add(line(current));
current = new ArrayList<>();
}
if (current.isEmpty()) {
currentY = w.y();
}
current.add(w);
}
if (!current.isEmpty()) {
lines.add(line(current));
}
return lines;
}
private static Line line(List<Word> words) {
words.sort(Comparator.comparing(Word::x));
return new Line(words.get(0).y(), List.copyOf(words));
}With a tolerance of 2 pt, page 1 of Stationery looks like this (excerpt):
y= 111.9 x0= 50.0 CUSTOMER INVOICE NO.
y= 125.9 x0= 50.0 Nebula Distribution Ltd. PI-000873
y= 139.9 x0= 50.0 VAT ID B00000000
y= 143.9 x0=400.0 DATE
y= 153.9 x0= 50.0 12 Fictional Street, Unit 3
y= 157.9 x0=400.0 2026-01-20Tolerance matters: VAT ID B00000000 (139.9) and DATE (143.9) are 4 pt apart and end up on different lines; with a tolerance of 5 pt they would merge. For 8–12 pt text, between 2 and 3 pt usually works well.
Finding a label and reading its value
With the lines in hand, locating a multi-word label is a matter of comparing sequences:
/** First occurrence of a label (one or more words, case-insensitive). */
public static Optional<List<Word>> find(List<Line> lines, String label) {
String[] parts = label.trim().split("\\s+");
for (Line line : lines) {
List<Word> ws = line.words();
for (int i = 0; i + parts.length <= ws.size(); i++) {
boolean matches = true;
for (int k = 0; k < parts.length && matches; k++) {
matches = ws.get(i + k).text().replaceAll("[:.]$", "").equalsIgnoreCase(parts[k]);
}
if (matches) {
return Optional.of(ws.subList(i, i + parts.length));
}
}
}
return Optional.empty();
}replaceAll("[:.]$", "") lets you search for Date and find Date:, or search for INVOICE NO and find INVOICE NO. (the label you search for is written without the final punctuation). On top of find we build the two typical queries for an invoice:
/** Text to the RIGHT of the label, on the same line. */
public static Optional<String> valueRightOf(List<Line> lines, String label) {
return find(lines, label).flatMap(found -> {
Word last = found.get(found.size() - 1);
String value = lines.stream()
.filter(l -> l.words().contains(last))
.flatMap(l -> l.words().stream())
.filter(w -> w.x() > last.right())
.map(Word::text)
.collect(Collectors.joining(" "));
return value.isEmpty() ? Optional.empty() : Optional.of(value);
});
}
/** Text BELOW the label: the first following line that overlaps it horizontally. */
public static Optional<String> valueBelow(List<Line> lines, String label) {
return find(lines, label).flatMap(found -> {
float left = found.get(0).x() - 2;
float right = found.get(found.size() - 1).right() + 40; // values are usually longer
float y = found.get(0).y();
return lines.stream()
.filter(l -> l.y() > y + 1)
.map(l -> l.words().stream()
.filter(w -> w.x() >= left && w.x() <= right)
.map(Word::text)
.collect(Collectors.joining(" ")))
.filter(s -> !s.isEmpty())
.findFirst();
});
}valueRightOftakes the words on the same line whosexstarts after the end of the label.valueBelowlooks in the following lines (greatery= further down) for words that start within the label's horizontal range, ignoring whatever is in other columns.
Actual results:
| Invoice | Query | Result |
|---|---|---|
| Supplies | valueRightOf("INVOICE TOTAL") |
1.234,56 € |
| Supplies | valueRightOf("Date") |
12/01/2026 |
| Stationery, page 1 | valueBelow("INVOICE NO") |
PI-000873 |
| Stationery, page 1 | valueBelow("TAX ID") |
B-44444444 |
| Stationery, page 2 | valueRightOf("Total payable") |
356,90 EUR |
| Transport | valueRightOf("Total amount") |
89,54 € |
Exactly the case that plain text couldn't solve! valueBelow("INVOICE NO") ignores Nebula Distribution Ltd., which is at the same height as PI-000873 but in the left-hand column. Mind you, a badly aimed query returns rubbish with complete confidence: in Supplies, valueBelow("Tax ID") returns M8x40 (box), because Tax ID: is in the middle of an address line and all it finds below is the table. Use each query where it makes sense and validate the result (with the regular expressions from 06-01, for example).
Reading a table by columns
The lines of an invoice form a table: each row is a line and each column a range of x. All we need is the left boundary of each column:
/**
* Table between two heights (reading coordinates). Each word goes into the column whose left
* boundary is the largest one that doesn't exceed its x. Words in the same cell are joined with spaces.
*/
public static List<List<String>> table(List<Line> lines, float yFrom, float yTo, float... bounds) {
List<List<String>> rows = new ArrayList<>();
for (Line line : lines) {
if (line.y() <= yFrom || line.y() >= yTo) {
continue;
}
StringBuilder[] cells = new StringBuilder[bounds.length];
for (int c = 0; c < cells.length; c++) {
cells[c] = new StringBuilder();
}
for (Word w : line.words()) {
int column = 0;
for (int c = 0; c < bounds.length; c++) {
if (w.x() >= bounds[c]) {
column = c;
}
}
if (!cells[column].isEmpty()) {
cells[column].append(' ');
}
cells[column].append(w.text());
}
List<String> row = new ArrayList<>();
for (StringBuilder cell : cells) {
row.add(cell.toString());
}
rows.add(row);
}
return rows;
}For Supplies, the header is at y = 191.9 and the taxable base at y = 281.9; the columns start at x = 50, 140, 360, 420 and 490. We leave a 5 pt margin:
List<Line> lines = TextLocator.lines(TextLocator.words(document, 1), 2f);
System.out.println(TextLocator.table(lines, 195, 250, 45, 135, 355, 415, 485));[[TOR-M8-40, Hex bolt M8x40 (box), 40, 18,40, 736,00],
[TAC-N8, Nylon wall plug 8 mm (bag), 20, 6,95, 139,00],
[BRO-HSS-6, HSS drill bit 6 mm (box of 60), 1, 145,30, 145,30]]Five clean columns, including the multi-word descriptions. This method assumes left-aligned columns; in tables with right-aligned amounts (like those in our own invoices), a long number can start before its header's boundary and fall into the previous column. For those cases it's better to assign each word to the column whose centre is closest, or to use the right-hand boundaries.
Calibrating a template
Where did the SupplierTemplate rectangles come from? From printing the words with their positions. A small "calibration" program is the best tool for creating templates:
try (PDDocument d = Loader.loadPDF(new File("output/suppliers/stationery-PI-000873.pdf"))) {
for (int page = 1; page <= d.getNumberOfPages(); page++) {
for (Word w : TextLocator.words(d, page)) {
System.out.printf("p%d %-14s x=%.1f y=%.1f right=%.1f height=%.1f %s %.0f%n", page, w.text(),
w.x(), w.y(), w.right(), w.height(), w.font(), w.size());
}
}
}p1 PI-000873 x=400.0 y=125.9 right=455.8 height=8.0 AAACRO+DejaVuSans 11
p1 2026-01-20 x=400.0 y=157.9 right=463.9 height=8.0 AAACRO+DejaVuSans 11
p2 356,90 x=151.0 y=177.9 right=197.3 height=8.7 AAADNE+DejaVuSans-Bold 12With this data, the number zone must contain the point (400, 125.9): we choose (395, 114, 150, 15), which runs from y = 114 to y = 129, that is, 12 pt above and 3 pt below the baseline, and is wide enough for longer numbers. The same rule (about 12 pt above the baseline, 3 below and a generous horizontal margin) works for all the zones.
Common Mistakes and Tips
- Using PDF coordinates in
addRegion: regions are in reading coordinates (y downwards from the CropBox). A region at (x, 724) looks at the bottom part of the page. - Regions that don't include the baseline: only the glyph's origin is checked; a region that visually "covers" the text may capture nothing.
- Forgetting that
extractRegionsworks per page and thatgetPageis 0-based while the zones in our template are 1-based. - Assuming that
writeStringreceives words: it receives fragments that may contain spaces. - Comparing text containing ligatures:
TextPosition.getUnicode()may returnffi;"office".equals("office")isfalse. - Relying on
getHeightDirto draw boxes: it's an estimate; use the font size (lineBox). - Mixing
getXandgetXDirAdj: they only differ when the text doesn't read horizontally on screen, but then they differ a lot. - Tip: store templates together with the date of the first invoice on which they were measured. When a template starts returning empty zones, the supplier will have changed its layout, and the generic reading from 06-01 will act as a safety net.
Exercises
- Columns from the header. Instead of writing the boundaries of the Supplies table by hand, calculate them from the header line (the one starting with
Reference) and read the rows between the header and theTaxable baseline. - The total of a multipage invoice. Locate
INVOICE TOTALin our invoiceoutput/F-2026-0001.pdf, which takes up two pages: state which page it's on, its box in reading coordinates and the value to its right. - Template with the generic reading as a fallback. Modify the
ReadWithTemplatesflow so that, if the template leaves a field empty, that field is filled in from the generic result, adding the warning "Template forout of date: ".
Solutions
Solution 1.
static float[] boundsFromHeader(Line header, float margin) {
float[] bounds = new float[header.words().size()];
for (int i = 0; i < bounds.length; i++) {
bounds[i] = header.words().get(i).x() - margin;
}
return bounds;
}
try (PDDocument d = Loader.loadPDF(new File("output/suppliers/supplies-SF-2026-0412.pdf"))) {
List<Line> lines = TextLocator.lines(TextLocator.words(d, 1), 2f);
Line header = lines.stream().filter(l -> l.text().startsWith("Reference")).findFirst().orElseThrow();
Word base = TextLocator.find(lines, "Taxable base").orElseThrow().get(0);
System.out.println(TextLocator.table(lines, header.y() + 1, base.y() - 1,
boundsFromHeader(header, 3)));
}It returns the same three rows of five columns as with the hand-written boundaries. It works because every Supplies heading is a single word (Reference, Description, Qty, Price, Amount); with a heading such as "Unit price" you'd get one column too many. In that case, group the header words that are separated by less than, say, 6 pt before calculating the boundaries.
Solution 2.
try (PDDocument d = Loader.loadPDF(new File("output/F-2026-0001.pdf"))) {
for (int p = 1; p <= d.getNumberOfPages(); p++) {
List<Line> lines = TextLocator.lines(TextLocator.words(d, p), 2f);
int page = p;
TextLocator.find(lines, "INVOICE TOTAL").ifPresent(label ->
System.out.println("Page " + page + ", box " + label.get(0).box() + " -> "
+ TextLocator.valueRightOf(lines, "INVOICE TOTAL").orElse("?")));
}
}Result: Page 2, box [x=317.48,y=476.62,w=50.84,h=8.02] -> 4.193,94 €. The box is that of the first word of the label (INVOICE); if you need the box for the whole label, join the boxes of all the words returned by find. Keep this code: in lesson 06-05 we'll highlight the total with an annotation using precisely these positions. The value contains a non-breaking space before the €, which comes from InvoiceLab's formatting.
Solution 3.
static SupplierInvoiceData withFallback(SupplierTemplate template, SupplierInvoiceData byZones,
SupplierInvoiceData generic) {
List<String> warnings = new ArrayList<>();
String number = byZones.number();
if (number == null) { number = generic.number(); warnings.add(warning(template, "number")); }
LocalDate date = byZones.date();
if (date == null) { date = generic.date(); warnings.add(warning(template, "date")); }
BigDecimal total = byZones.total();
if (total == null) { total = generic.total(); warnings.add(warning(template, "total")); }
if (number == null || date == null || total == null) {
warnings.add("Data also missing from the generic reading");
}
return new SupplierInvoiceData(number, date, template.taxId(), total, List.copyOf(warnings));
}
static String warning(SupplierTemplate t, String field) {
return "Template for " + t.name() + " out of date: " + field;
}The warning doesn't stop you using the data, but it does flag that someone needs to recalibrate the template. To try it out, temporarily move the Supplies TOTAL zone to (485, 405, 80, 16) (100 pt lower): the template will return an empty total, the fallback will fill it in with 1234.56 and the warning will appear. Notice that the SupplierInvoiceData record is public, so we can create it from another package even though result(...) isn't.
Conclusion
In this lesson you've learned to work with the geometry of text. You know the reading coordinate system (origin at the top left of the CropBox, y downwards, rotation applied) and how it differs from the PDF system of 02-01; you know how to extract text from areas with PDFTextStripperByArea and what criterion it follows to decide whether a character is inside; you've created per-supplier templates with SupplierTemplate; and you know TextPosition and the difference between getX and getXDirAdj on rotated pages. With TextLocator you get words with their position, font and size, group them into lines, find labels, read the values to their right or below them, and extract tables by columns.
So far we've only looked at the text in PDFs, but invoices also contain images (logos, stamps, scanned signatures) and depend on fonts that may or may not be embedded. In the next lesson we'll walk through the pages' resources to extract images, find out where and at what size each one is drawn, inventory the fonts and reliably detect scanned documents.
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
