Until now InvoiceLab has only written PDFs: invoices, delivery notes, batches, forms. In this module we change direction and learn to read them. The starting point is a very common one: every month Nebula Distribution receives dozens of supplier invoices as PDFs, and someone in the Accounts department types the number, the date, the supplier's VAT ID and the total into the ERP by hand. Those invoices have no form: the data is simply text drawn on the page. In this lesson we'll understand why getting text out of a PDF is harder than it looks, learn to use PDFTextStripper, the PDFBox class that turns pages into plain text, and build a first invoice reader based on regular expressions, with its strengths and its limits.
Contents
- Why extracting text from a PDF is hard
- The sample supplier invoices
- Basic
PDFTextStripper - Reading order:
setSortByPosition - Page ranges, separators and other options
- Extracting page by page and detecting documents without text:
PdfText - Normalising the extracted text
- Extracting data with regular expressions:
SupplierInvoiceReader - The limits of this approach
Why extracting text from a PDF is hard
In lesson 01-03 we saw that a page's content is a content stream: a list of drawing operators. This is roughly what the invoice number of one of our suppliers looks like:
BT
/F1 10 Tf % font F1 at 10 points
400 724 Td % move the text cursor to (400, 724)
(Number: SF-2026/0412) Tj
ETNotice what isn't there: no paragraphs, no lines, no columns, no tables, not even a guarantee that words are separated by spaces. PDF is a presentation format: it stores which glyph is drawn where, not what the text means or in what order it should be read. Any extraction tool has to rebuild the text from individual glyphs and their positions.
flowchart LR
CS["Content stream<br/>BT ... Tj ... ET"] --> Engine["PDFStreamEngine<br/>runs the operators"]
Engine --> TP["TextPosition<br/>one object per glyph:<br/>Unicode, x, y, font, size"]
TP --> Stripper["PDFTextStripper<br/>sorts, groups into words,<br/>lines and paragraphs"]
Stripper --> Text["String"]
Along the way, these problems can crop up:
| Problem | What happens | Does PDFBox solve it? |
|---|---|---|
| Writing order ≠ reading order | The program that generated the PDF may have written the total first and the header afterwards | Yes, with setSortByPosition(true) |
| No spaces | Many generators place each word separately, with no space character | Yes: PDFBox infers spaces from the gaps between glyphs |
| Glyph without Unicode | The PDF stores glyph codes; to know which letter each one is, it needs a /ToUnicode table or a standard encoding. Without one, there's no reliable way to tell |
No. In one test we removed the /ToUnicode from an invoice with embedded DejaVu: the extracted text came out empty and the log filled up with No Unicode mapping for CID+51 warnings |
| Text converted to outlines | Some designers "outline" text (logos, headings): it's no longer glyphs but drawings | No: as far as PDFBox is concerned there is no text |
| Scanned document | Each page is an image; there isn't a single glyph | No: you need OCR, outside PDFBox |
| Ligatures | Fonts such as DejaVu draw "fi" with a single glyph fi |
Yes: getText breaks them up (we'll see in 06-02 a case where this doesn't happen automatically) |
| Hidden text | White text on white, or outside the CropBox | It extracts it anyway: PDFBox doesn't check whether the text is visible |
OCR (Optical Character Recognition) recognises letters in an image. The best-known free tool is Tesseract; from Java it's used through the Tess4J wrapper, and there's also
ocrmypdf, which adds an invisible text layer on top of the image in a scanned PDF. Once that layer is there, everything we'll see in this module works the same way. OCR is beyond the scope of this course, but we'll learn to detect when it's needed.
The last row deserves attention: we checked that white text on a white background, or text placed outside the CropBox (we warned about this in lesson 04-03), appears in the output of getText exactly like visible text. Extracting text is not the same as seeing the page.
The sample supplier invoices
To practise we need invoices that we didn't generate with our own classes. Just as SupplierDocument (module 4) simulated a "difficult" PDF, the helper class com.invoicelab.examples.GenerateSupplierInvoices creates four invoices from fictional suppliers in output/suppliers/, all addressed to Nebula Distribution (VAT ID B00000000) and each with a different layout:
| File | Supplier (tax ID) | Characteristics |
|---|---|---|
supplies-SF-2026-0412.pdf |
Fictional Supplies Inc. (A33333333) | Single column, non-embedded Helvetica, total in "fake bold" (drawn twice with a 0.3 pt offset) |
stationery-PI-000873.pdf |
Imaginary Stationery Ltd. (B44444444) | Two pages, embedded DejaVu, labels above the values in a right-hand column, hyphenated words, logo with transparency on both pages |
transport-2026-017.pdf |
Invented Transport (12345678Z, a sole trader) | A4 page with /Rotate 90 (landscape), Times, date "5 January 2026", the total is written first in the content stream, logo inside a Form XObject and an inline image |
scanned-SF-2026-0412.pdf |
The Supplies invoice, "scanned" | One greyscale JPEG image per page, no text |
The complete class is in the course project; here we're only interested in two fragments. The first is the "fake bold": some old programs simulate bold by painting the same text twice, slightly offset.
// "Fake bold": the same text twice, offset by 0.3 pt (some programs do this)
for (float dx : new float[] { 0f, 0.3f }) {
text(cs, regular, 12, 380 + dx, 525, "INVOICE TOTAL");
text(cs, regular, 12, 490 + dx, 525, "1.234,56 €");
}text(...) is a small helper method that calls beginText, setFont, newLineAtOffset, showText and endText, as in module 2. The amounts keep the Spanish format (thousands with a dot, decimals with a comma) because the suppliers, like Nebula, are Spanish companies. The second fragment is the Transport invoice, which draws on the rotated page using the matrix from Stamper.visibleMatrix (lesson 04-02) and writes the amounts before the header:
cs.transform(Stamper.visibleMatrix(page)); // from here on: 842 x 595, origin bottom-left
// The TOTAL is written first: content stream order is not reading order
text(cs, bold, 13, 560, 150, "Total amount: 89,54 €");
text(cs, regular, 11, 560, 170, "VAT 21%: 15,54 €");
text(cs, regular, 11, 560, 190, "Base: 74,00 €");
// ... then the logo, the header and the customerRun GenerateSupplierInvoices once before continuing with the examples in this module.
Basic PDFTextStripper
The simplest way to extract text takes three lines:
try (PDDocument document = Loader.loadPDF(new File("output/suppliers/transport-2026-017.pdf"))) {
PDFTextStripper stripper = new PDFTextStripper();
String text = stripper.getText(document);
System.out.println(text);
}new PDFTextStripper()creates the stripper with the default configuration. In PDFBox 3 the constructor no longer declaresIOException(in 2.x it did).getText(document)processes all the pages and returns a singleString. There's alsowriteText(document, writer), which writes to aWriter; it's preferable for huge documents, because it doesn't accumulate all the text in memory.- The stripper does not modify the document: you can extract text and then carry on editing and saving it.
This is the result for the Transport invoice:
Total amount: 89,54 €
VAT 21%: 15,54 €
Base: 74,00 €
Invoice No. 2026-017
Huesca, 5 January 2026
Invented Transport
Juan Ejemplo Ficticio - VAT ID 12345678Z
Customer: Nebula Distribution Ltd. (VAT ID B00000000)
Haulage Huesca - Zaragoza, 2 pallets, 03/01/2026 74,00The text is correct, but the order is the content stream's: the total appears at the very top.
Reading order: setSortByPosition
By default, PDFTextStripper respects the order in which the text was written. It's fast and, in well-generated documents, matches the reading order. When it doesn't, setSortByPosition(true) sorts the glyphs by their position on the page: top to bottom and, within each line, left to right.
| Invoice | setSortByPosition(false) (default) |
setSortByPosition(true) |
|---|---|---|
| Transport | Total at the start, header at the end | Invented Transport / Juan Ejemplo Ficticio - VAT ID 12345678Z Invoice No. 2026-017 / … / Total amount: 89,54 € |
| Supplies | Bill to: and INVOICE on separate lines |
Bill to: INVOICE / Nebula Distribution Ltd. Number: SF-2026/0412 (mixes the two columns) |
| Stationery | INVOICE NO. and PI-000873 below it |
CUSTOMER INVOICE NO. / Nebula Distribution Ltd. PI-000873 |
supplier-AP-7731.pdf (module 4), page 2 with /Rotate 90 |
F / ict / ional Sup / … (unreadable) |
Fictional Supplies Inc. - Delivery note AP-7731 - page 2 |
The table shows that neither option is always better:
- Sorting by position fixes documents written "out of order" and rotated pages (page 2 of the delivery note from 04-04 was unreadable without sorting).
- But sorting by position mixes columns: everything at the same height ends up on the same line, even if it belongs to different blocks. In Stationery, the label
INVOICE NO.ends up separated from its value by the customer's name.
In InvoiceLab we'll use position order as the main option and stream order as a second opinion. In lesson 06-02 we'll see a better solution for columns: working with the positions of the words.
Page ranges, separators and other options
PDFTextStripper has quite a few options. These are their default values, checked with PDFBox 3.0.8:
| Method | Default | What it's for |
|---|---|---|
setStartPage(int) / setEndPage(int) |
1 / Integer.MAX_VALUE |
Page range, 1-based and inclusive |
setSortByPosition(boolean) |
false |
Visual order instead of stream order |
setSuppressDuplicateOverlappingText(boolean) |
true |
Removes glyphs repeated at almost the same position |
setLineSeparator(String) |
the system's (\n on Linux, \r\n on Windows) |
End of line |
setWordSeparator(String) |
" " |
What's inserted when PDFBox infers a space |
setParagraphStart/End(String) |
"" / "" |
Paragraph start and end markers |
setPageStart/End(String) |
"" / line separator |
Page start and end markers |
setAddMoreFormatting(boolean) |
false |
Separates paragraphs with blank lines |
setSpacingTolerance, setAverageCharTolerance |
0.5 / 0.3 | Sensitivity when inferring spaces |
setIndentThreshold, setDropThreshold |
2.0 / 2.5 | Sensitivity when detecting paragraphs |
Let's try the most useful ones with the Stationery invoice:
PDFTextStripper stripper = new PDFTextStripper();
stripper.setSortByPosition(true);
stripper.setPageStart("=== PAGE ===\n");
stripper.setPageEnd("=== END ===\n");
stripper.setParagraphStart("<P>");
stripper.setParagraphEnd("</P>");
stripper.setStartPage(2); // only the second sheet
stripper.setEndPage(2);
System.out.println(stripper.getText(document));=== PAGE ===
<P>Imaginary Stationery Ltd.
21 Example Promenade, 31001 Pamplona Sheet 2/2
</P><P>Taxable base: 294,96 EUR
VAT (21%): 61,94 EUR
</P><P>Total payable: 356,90 EUR
</P><P>Payment by direct debit. Fictional company and data.</P>=== END ===Things to note:
- Paragraphs are an inference: PDFBox starts a new one when there's a large vertical jump or an indent. Here it gets it mostly right, but don't trust them blindly.
- The stripper remembers its configuration: if you then call
getTextwithout touching the range, it will keep extracting only page 2. If you reuse a stripper, set the range again every time. - Be careful with
setAddMoreFormatting(true): when you enable it, PDFBox overwritesparagraphEnd,pageStart,articleStartandarticleEndwith the line separator. In our test, with that option on, the=== PAGE ===marker and the</P>tags vanished without any warning. If you use your own markers, don't enable it.
Duplicate text
Remember the "fake bold" of the Supplies total. With the default configuration it's extracted only once; if we turn off suppression:
the line becomes INVOICE TOTAL 1.234,56 €INVOICE TOTAL 1.234,56 €, and a regular expression looking for the total could find odd things. Leave this option set to true unless you have a specific reason (it's slightly slower, but it avoids surprises).
Extracting page by page and detecting documents without text: PdfText
Let's gather what we've learned into a utility class in the new com.invoicelab.extraction package:
package com.invoicelab.extraction;
/** Utilities for extracting plain text with PDFTextStripper. */
public final class PdfText {
/** Minimum number of letters or digits for a page to be considered to "have text". */
private static final int MIN_CHARACTERS = 10;
private PdfText() {
}
/** Stripper configured the way InvoiceLab uses it: visual order and no duplicates. */
public static PDFTextStripper stripper() {
return stripper(true);
}
/** @param sort true = visual order (by position); false = the order it was written in the stream */
public static PDFTextStripper stripper(boolean sort) {
PDFTextStripper stripper = new PDFTextStripper();
stripper.setSortByPosition(sort);
stripper.setSuppressDuplicateOverlappingText(true); // already the default; we make it explicit
stripper.setLineSeparator("\n"); // independent of the operating system
return stripper;
}
/** All the text in the document. */
public static String text(PDDocument document) throws IOException {
return stripper().getText(document);
}
/** All the text, in the chosen order. */
public static String text(PDDocument document, boolean sort) throws IOException {
return stripper(sort).getText(document);
}
/** The text of each page separately (index 0 = page 1). */
public static List<String> byPage(PDDocument document) throws IOException {
PDFTextStripper stripper = stripper();
List<String> pages = new ArrayList<>();
for (int n = 1; n <= document.getNumberOfPages(); n++) {
stripper.setStartPage(n); // the stripper's pages start at 1
stripper.setEndPage(n);
pages.add(stripper.getText(document));
}
return pages;
}
/** Page numbers (1-based) that have no usable text layer. */
public static List<Integer> pagesWithoutText(PDDocument document) throws IOException {
List<Integer> withoutText = new ArrayList<>();
List<String> pages = byPage(document);
for (int i = 0; i < pages.size(); i++) {
long useful = pages.get(i).codePoints().filter(Character::isLetterOrDigit).count();
if (useful < MIN_CHARACTERS) {
withoutText.add(i + 1);
}
}
return withoutText;
}
/** true if at least one page has extractable text. */
public static boolean hasTextLayer(PDDocument document) throws IOException {
return pagesWithoutText(document).size() < document.getNumberOfPages();
}
// normalize(String): in the next section
}Key points for beginners:
- 1-based versus 0-based:
setStartPage(1)is the first page, whiledocument.getPage(0)is also the first page. It's a constant source of bugs; the comments are there as a reminder. setLineSeparator("\n")makes the result identical on Windows and Linux, which simplifies the regular expressions.pagesWithoutTextdoesn't compare against the empty string: a scanned page usually returns a line break (thepageEnd), and an "almost empty" page might contain only a page number. We count letters and digits withCharacter::isLetterOrDigitand require at least 10.byPagereuses the same stripper and sets the range on each iteration, for the reason mentioned earlier.
With the scanned invoice, pagesWithoutText returns [1] and hasTextLayer returns false. With the January batch (lesson 04-04) it returns [2, 4, 8, 12]: the blank sheets added for duplex printing.
Normalising the extracted text
Text coming out of a PDF has "noise" that gets in the way when searching for data: several kinds of spaces, hyphenation, blank lines… Before applying regular expressions it pays to normalise it:
/** Cleans up the extracted text so it can be searched with regular expressions. */
public static String normalize(String text) {
String t = Normalizer.normalize(text, Normalizer.Form.NFKC); // ligatures: "fi" -> "fi"
t = t.replace("\r\n", "\n").replace('\r', '\n');
t = t.replaceAll("[\\u00A0\\u2007\\u202F\\t]", " "); // "odd" spaces -> space
t = t.replaceAll("[\\u2010\\u2011\\u00AD]", "-"); // hyphen variants
t = t.replaceAll("(\\p{L})-\\n(\\p{Ll})", "$1$2"); // "ware-\nhouse" -> "warehouse"
t = t.replaceAll(" {2,}", " "); // repeated spaces
t = t.replaceAll("(?m)^ +| +$", ""); // spaces at the start/end of a line
t = t.replaceAll("\\n{3,}", "\n\n"); // at most one blank line
return t.strip();
}Step by step:
- NFKC is a Unicode normalisation form that replaces "compatibility" characters with their plain equivalents: the ligature
fibecomesfi, full-width digits become normal digits… It has a side effect worth knowing about: the ordinal indicatorºbecomes the lettero, so a Spanish-styleNºbecomesNoandn.ºbecomesn.o. Our regular expressions take this into account. - We unify the line endings.
- The non-breaking space
shows up a lot in amounts formatted the Spanish way: Java'sNumberFormatwrites1.470,85 €with a non-breaking space before the symbol, and our own invoices contain it. We turn it into a normal space. - We replace typographic hyphens (non-breaking hyphen, soft hyphen) with the normal hyphen.
- We join hyphenated words: a letter, a hyphen, a line break and a lowercase letter. In Stationery,
ware-\nhousebecomeswarehouse. The lowercase condition avoids joining things likeB-\n44444444. - We collapse spaces and blank lines.
In the Stationery invoice,
Office sup-is not joined toplies: when sorting by position, the quantity and amount from the same line appear to the right ofsup-(Office sup- 1 294,96), so the hyphen is no longer at the end of the line. Another consequence of mixing columns.
Extracting data with regular expressions: SupplierInvoiceReader
With the text normalised we can now search for the four pieces of data. The result is returned in a record:
/** The result of the reading. Fields that weren't found are left null and generate a warning. */
public record SupplierInvoiceData(String number, LocalDate date, String supplierTaxId, BigDecimal total,
List<String> warnings) {
public boolean complete() {
return warnings.isEmpty();
}
}It's a record nested inside SupplierInvoiceReader. The regular expressions are the heart of the class:
private static final String VALUE = "([A-Z0-9][A-Z0-9/-]*\\d[A-Z0-9/-]*)"; // at least one digit
private static final List<Pattern> NUMBER = List.of(
Pattern.compile("invoice\\s+n[º°o]\\.?\\s*[:.]?\\s*" + VALUE, Pattern.CASE_INSENSITIVE),
Pattern.compile("invoice\\s+(?:number|#)\\s*[:.]?\\s*" + VALUE, Pattern.CASE_INSENSITIVE),
Pattern.compile("\\bnumber\\s*[:.]?\\s*" + VALUE, Pattern.CASE_INSENSITIVE));
private static final String MONTHS = "january|february|march|april|may|june|july|august|september|october"
+ "|november|december";
private static final Pattern NUMERIC_DATE = Pattern.compile("\\b(\\d{1,2})[/.-](\\d{1,2})[/.-](\\d{4})\\b");
private static final Pattern ISO_DATE = Pattern.compile("\\b(\\d{4})-(\\d{2})-(\\d{2})\\b");
private static final Pattern LONG_DATE = Pattern.compile("\\b(\\d{1,2}) (" + MONTHS + ") (\\d{4})\\b",
Pattern.CASE_INSENSITIVE);
private static final Pattern DATE_LABEL = Pattern.compile("(?:invoice\\s+|issue\\s+)?date\\s*[:.]?\\s*$",
Pattern.CASE_INSENSITIVE);
private static final Pattern TAX_ID = Pattern.compile(
"\\b(?:[A-HJNP-SUVW]-?\\d{7}-?[0-9A-J]|\\d{8}-?[A-Z]|[XYZ]-?\\d{7}-?[A-Z])\\b");
private static final Pattern TOTAL = Pattern.compile(
"(?:(?:invoice\\s+)?total(?:\\s+amount|\\s+payable)?)\\s*[:.]?\\s*"
+ "(\\d{1,3}(?:\\.\\d{3})*,\\d{2})\\s*(?:€|EUR)?", Pattern.CASE_INSENSITIVE);How to read them:
| Data | Formats covered | Details |
|---|---|---|
| Number | Invoice No. 2026-017, INVOICE NO. + value, Number: SF-2026/0412 |
Several expressions tried in order. VALUE requires at least one digit, so as not to capture a word (for example, the customer's name). [º°o] accepts No., the ordinal Nº used by Spanish suppliers, the degree sign (a common typo) and the o that NFKC leaves behind. \s includes the line break, so it works when the label is above the value |
| Date | 12/01/2026, 12.01.2026, 2026-01-20, 5 January 2026 |
Three patterns; they're converted to LocalDate |
| Tax ID | Spanish company tax ID (A33333333, B-44444444), DNI (12345678Z), NIE (X1234567L) |
Allows optional hyphens, which are removed afterwards |
| Total | INVOICE TOTAL 1.234,56 €, Total payable: 356,90 EUR, Total amount: 89,54 € |
The amount in Spanish format: thousands with a dot, decimals with a comma |
Number, tax ID and total
static String number(String text) {
for (Pattern pattern : NUMBER) {
Matcher m = pattern.matcher(text);
if (m.find()) {
return m.group(1).toUpperCase(Locale.ROOT);
}
}
return null;
}
/** The first tax ID (NIF/CIF/NIE) that isn't the company's own, without hyphens. */
static String supplierTaxId(String text, Set<String> ownIds) {
Matcher m = TAX_ID.matcher(text);
while (m.find()) {
String taxId = m.group().replace("-", "").toUpperCase(Locale.ROOT);
if (!ownIds.contains(taxId)) {
return taxId;
}
}
return null;
}
/** The LAST amount preceded by a total label (totals usually come at the end). */
static BigDecimal total(String text) {
Matcher m = TOTAL.matcher(text);
String last = null;
while (m.find()) {
last = m.group(1);
}
return last == null ? null : amount(last);
}
/** "1.234,56" -> 1234.56 */
static BigDecimal amount(String text) {
return new BigDecimal(text.replace(".", "").replace(',', '.'));
}- The supplier's tax ID isn't the only one on the invoice: every invoice we receive also contains ours, as the customer. That's why the reader takes our own tax IDs in its constructor (
new SupplierInvoiceReader("B00000000")) and discards them. Without that precaution, in Stationery, where the customer block appears before the supplier's tax ID, we'd get B00000000 (we checked: in Supplies and Transport it would get it right only because the supplier appears first). - For the total we keep the last match: long invoices may have subtotals or a "Total VAT" line earlier on.
amountusesBigDecimal, like all of InvoiceLab's money (module 3). Neverdouble.- The methods are
staticand package-private: that way we'll be able to reuse them in lesson 06-02.
The date: label first
An invoice can contain several dates (issue, due date, date of service). The Transport invoice contains 5 January 2026 (issue) and 03/01/2026 (date of the haulage). The strategy is: if a date is preceded by the label "Date", that one wins; otherwise, the first one that appears in the text.
/** The date preceded by the label "Date"; if there isn't one, the first date in the text. */
static LocalDate date(String text) {
record Candidate(int position, LocalDate date) { }
List<Candidate> candidates = new ArrayList<>();
for (Pattern pattern : List.of(NUMERIC_DATE, ISO_DATE, LONG_DATE)) {
Matcher m = pattern.matcher(text);
while (m.find()) {
LocalDate d = convert(pattern, m);
if (d != null) {
candidates.add(new Candidate(m.start(), d));
}
}
}
candidates.sort((a, b) -> Integer.compare(a.position(), b.position()));
for (Candidate c : candidates) {
String before = text.substring(Math.max(0, c.position() - 25), c.position());
if (DATE_LABEL.matcher(before).find()) {
return c.date();
}
}
return candidates.isEmpty() ? null : candidates.get(0).date();
}
private static LocalDate convert(Pattern pattern, Matcher m) {
try {
if (pattern == ISO_DATE) {
return LocalDate.of(toInt(m.group(1)), toInt(m.group(2)), toInt(m.group(3)));
}
int month = pattern == LONG_DATE
? List.of(MONTHS.split("\\|")).indexOf(m.group(2).toLowerCase(Locale.ROOT)) + 1
: toInt(m.group(2));
return LocalDate.of(toInt(m.group(3)), month, toInt(m.group(1)));
} catch (DateTimeException e) {
return null; // "31/02/2026" or a number that looked like a date
}
}record Candidateis a local record: it only exists inside the method, perfect for throwaway data.DATE_LABELends in$: the label has to be immediately before the date (within the previous 25 characters).LocalDate.ofthrowsDateTimeExceptionfor impossible dates; we discard them instead of breaking the reading.toInt(s)is simplyInteger.parseInt(s).- Numeric dates are read in day/month/year order, the European convention that Spanish suppliers use:
03/01/2026is 3 January, not 1 March.
Two passes and the result
public SupplierInvoiceData read(PDDocument document) throws IOException {
if (!PdfText.hasTextLayer(document)) {
return new SupplierInvoiceData(null, null, null, null,
List.of("The PDF has no text layer (scanned?): needs OCR"));
}
// 1st pass: visual order (the one that works for most layouts)
SupplierInvoiceData visual = analyze(PdfText.normalize(PdfText.text(document, true)));
if (visual.complete()) {
return visual;
}
// 2nd pass: content stream order (sometimes keeps a column's label and value together)
SupplierInvoiceData stream = analyze(PdfText.normalize(PdfText.text(document, false)));
return combine(visual, stream);
}
/** Looks for the data in text that has already been extracted and normalised. */
public SupplierInvoiceData analyze(String text) {
return result(number(text), date(text), supplierTaxId(text), total(text));
}- If the document has no text, there's no point searching for anything: we return an empty result with a clear warning.
combine(a, b)takes each field from the first reading and, if it'snull, the one from the second.result(...)creates the record and adds a warning for eachnullfield ("Invoice number not found", and so on). Both are simple methods in the class.analyze(String)is public so that we can test the regular expressions without a PDF, using hand-written text in a unit test.- There's also a
read(Path)that opens the file withLoader.loadPDFin a try-with-resources block and callsread(PDDocument).
Trying it with all the invoices
public class ReadSupplierInvoices {
public static void main(String[] args) throws IOException {
SupplierInvoiceReader reader = new SupplierInvoiceReader(SampleData.NEBULA.taxId());
try (DirectoryStream<Path> pdfs = Files.newDirectoryStream(Path.of("output/suppliers"), "*.pdf")) {
for (Path pdf : pdfs) {
SupplierInvoiceData d = reader.read(pdf);
System.out.printf("%-32s no.=%-12s date=%-10s taxId=%-9s total=%-8s %s%n", pdf.getFileName(),
d.number(), d.date(), d.supplierTaxId(), d.total(), d.complete() ? "OK" : d.warnings());
}
}
}
}scanned-SF-2026-0412.pdf no.=null date=null taxId=null total=null [The PDF has no text layer (scanned?): needs OCR]
transport-2026-017.pdf no.=2026-017 date=2026-01-05 taxId=12345678Z total=89.54 OK
stationery-PI-000873.pdf no.=PI-000873 date=2026-01-20 taxId=B44444444 total=356.90 OK
supplies-SF-2026-0412.pdf no.=SF-2026/0412 date=2026-01-12 taxId=A33333333 total=1234.56 OKThree invoices read correctly and one scan detected. In Stationery, the number was found by the second pass: in visual order, INVOICE NO. is separated from PI-000873 by the customer's name; in stream order, they appear one after the other.
The limits of this approach
Regular expressions over the full text are the quickest technique to put in place and they work surprisingly well, but you should know their limits before relying on them:
- They depend on vocabulary: a supplier who writes "Inv. Ref." or "Bill No." won't be recognised until we add the pattern.
- They know nothing about columns: when the label and the value are in different columns, the text order can separate them (we saw this with Stationery).
- They confuse similar data: if the supplier prints a third party's tax ID (for example, a factoring company) before its own, we'll take it for the supplier's.
- They don't validate: the reader doesn't check the tax ID's check letter, or that base + VAT = total.
- They can't see: they extract hidden text or text outside the page just like visible text.
For all these reasons, in production the result of SupplierInvoiceReader should be treated as a proposal that a person confirms, at least for new suppliers. In the next lesson we'll learn to use the position of the text to read the invoices of regular suppliers much more precisely.
Common Mistakes and Tips
- Mixing up page numbering:
setStartPage/setEndPagestart at 1;getPage(int)starts at 0. - Reusing a stripper without resetting the range: the configuration persists between calls to
getText. - Enabling
setAddMoreFormatting(true)together with your own markers: it overwritespageStart,paragraphEnd,articleStartandarticleEndwithout warning. - Searching with
" €"or"\\s€": amounts formatted withNumberFormatcontain a non-breaking space () that\sdoesn't match in Java. Normalise first or use\h(any horizontal whitespace). - Forgetting that NFKC turns
ºintoo: after normalising,NºisNo. - Taking the first tax ID in the document: there are almost always at least two (the supplier's and ours).
- Using
doublefor amounts: alwaysBigDecimal. - Accepting an empty extraction as valid: empty text doesn't mean "the invoice has no data", but "this PDF has no text layer" or "the fonts have no
/ToUnicode". Detect the case and raise a warning. - Tip: store the extracted text (for example, alongside the archived PDF). When a pattern fails, you'll be able to reproduce the problem without the PDF and write a test with
analyze(String).
Exercises
- The batch's blank sheets. Write a program that loads
output/batch-2026-01.pdfand shows which pages have no text and how many characters each of the others has. - Taxable base and VAT rate. Add reading of the taxable base (formats
Taxable base 1.020,30,Taxable base: 294,96 EURandBase: 74,00 €) and, for the three invoices with text, calculate the implied VAT amount (total − base) and the rate as a percentage. - Put yourself in the customer's shoes. Use
SupplierInvoiceReaderto read our own invoiceoutput/F-2026-0001.pdfas if you were Example Hardware Co. (VAT ID J00000000). Which four pieces of data do you get? What would happen if you didn't specify any tax ID of your own?
Solutions
Solution 1.
try (PDDocument batch = Loader.loadPDF(new File("output/batch-2026-01.pdf"))) {
List<String> pages = PdfText.byPage(batch);
System.out.println("No text: " + PdfText.pagesWithoutText(batch));
for (int i = 0; i < pages.size(); i++) {
System.out.printf("Page %2d: %,d characters%n", i + 1, pages.get(i).strip().length());
}
}It shows No text: [2, 4, 8, 12], the blank sheets that Pages.padForDuplex added in 04-04. Notice that pagesWithoutText extracts all the pages again internally: if you need both things in a bulk process, extract once with byPage and apply the 10-letters-or-digits criterion yourself.
Solution 2.
private static final Pattern BASE = Pattern.compile(
"(?:taxable\\s+)?base\\s*:?\\s*(\\d{1,3}(?:\\.\\d{3})*,\\d{2})", Pattern.CASE_INSENSITIVE);
SupplierInvoiceReader reader = new SupplierInvoiceReader("B00000000");
for (String f : List.of("supplies-SF-2026-0412", "stationery-PI-000873", "transport-2026-017")) {
try (PDDocument d = Loader.loadPDF(new File("output/suppliers/" + f + ".pdf"))) {
Matcher m = BASE.matcher(PdfText.normalize(PdfText.text(d)));
BigDecimal base = new BigDecimal(m.find() ? m.group(1).replace(".", "").replace(',', '.') : "0");
BigDecimal vat = reader.read(d).total().subtract(base);
BigDecimal rate = vat.multiply(BigDecimal.valueOf(100)).divide(base, 1, RoundingMode.HALF_UP);
System.out.println(f + ": base " + base + ", VAT " + vat + " (" + rate + "%)");
}
}Result: bases 1020.30, 294.96 and 74.00; VAT amounts 214.26, 61.94 and 15.54; all three at 21.0%. A rate other than 21, 10, 4 or 0 (the Spanish VAT rates) is a good alarm bell: either the reader picked the wrong number, or the invoice has several rates and deserves a manual review. divide needs an explicit scale and rounding mode; without them, a division with a recurring decimal throws ArithmeticException. In a real SupplierInvoiceReader, the base would be one more field of the record.
Solution 3.
SupplierInvoiceData[number=F-2026-0001, date=2026-01-15, supplierTaxId=B00000000, total=4193.94, warnings=[]]All four pieces of data are correct: the number is found by the first pattern (INVOICE + line break + No. F-2026-0001), the date via the Date: label, and the total is the last INVOICE TOTAL, on page 2 (the Carried forward on page 1 doesn't contain the word "total"). Without our own tax ID, the result would be the same by coincidence: in our layout the issuer appears before the customer. With the Stationery layout, on the other hand, we'd get the customer's tax ID. Always specify your own tax IDs.
Conclusion
In this lesson you've seen that a PDF stores positioned glyphs rather than structured text, and that extracting text means rebuilding words, lines and reading order. You've learned to use PDFTextStripper and its main options (page range, setSortByPosition, separators, duplicate suppression and the setAddMoreFormatting trap), to detect documents without a text layer that need OCR, and to normalise the result. With PdfText and SupplierInvoiceReader, InvoiceLab can now read the number, the date, the tax ID and the total from the invoices of three different suppliers.
You've also seen the weak spot of plain text: columns get mixed up and a label can end up far from its value. In the next lesson we'll go down a level and work with the position of every character: we'll extract text from specific areas of the page with PDFTextStripperByArea, build per-supplier templates and learn to locate a label and read the value to its right or below it.
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
