How to extract text from a PDF in Java with PDFBox
Updated · Tested with Java 25, Apache PDFBox 3.0.8
In short
Open the file with Loader.loadPDF, create a PDFTextStripper and call getText(document). That is PDFBox 3; the older PDDocument.load no longer exists. Use PDFTextStripperByArea to read one rectangle of a page. PDFBox reads the text stored in a PDF and returns nothing for a scan.
Apache PDFBox is the standard open-source PDF library for Java, under the Apache licence. Version 3 changed how files are opened, so older examples that call PDDocument.load no longer compile. The examples use company-extract.pdf.
Add PDFBox
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>3.0.8</version>
</dependency>Extract all the text
import java.io.File;
import org.apache.pdfbox.Loader;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.text.PDFTextStripper;
public class ExtractText {
public static void main(String[] args) throws Exception {
try (PDDocument document = Loader.loadPDF(new File(args[0]))) {
PDFTextStripper stripper = new PDFTextStripper();
System.out.println(stripper.getText(document));
}
}
}COMPANY EXTRACT
Company name Harbor Lane Logistics Ltd
Company number 51-482913-6
Status Active
Registered 14 March 2019
Registered office 22 Quay Street, Haifa
Share capital 1,250.50
DirectorsLoader.loadPDF is the version 3 way to open a file. Always close the document; the try block does it.
One page, or a range
stripper.setStartPage(1);
stripper.setEndPage(1);Pages count from 1. document.getNumberOfPages() gives the total.
Extract text from one area of the page
PDFTextStripperByArea reads only what lies inside a rectangle. The rectangle is in points, measured from the top left of the page: x, y, width, height.
import java.awt.geom.Rectangle2D;
import java.io.File;
import org.apache.pdfbox.Loader;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.text.PDFTextStripperByArea;
public class ExtractArea {
public static void main(String[] args) throws Exception {
try (PDDocument document = Loader.loadPDF(new File(args[0]))) {
PDPage page = document.getPage(0);
PDFTextStripperByArea byArea = new PDFTextStripperByArea();
byArea.addRegion("companyNumber", new Rectangle2D.Float(200, 150, 360, 24));
byArea.extractRegions(page);
System.out.println(byArea.getTextForRegion("companyNumber").trim());
}
}
}51-482913-6The rectangle starts at x = 200, just left of where the values begin, and covers the second row of the sample. Fixed rectangles work while every document has the same layout; template-based extraction covers what happens when it shifts.
setSortByPosition: know what it does
By default PDFBox returns text in the order the file stores it. stripper.setSortByPosition(true) sorts it from top to bottom and left to right instead.
On the label-and-value sample both give the same result. On a two-column page they do not:
| Setting | Two-column page |
|---|---|
| Default | Left column, then right column |
setSortByPosition(true) | Both columns joined line by line |
With sorting on, the first line of our sample became Harbor Lane Logistics moved 4,180 kept the increase below the rise in fuel. Turn it on for tables and forms, where a row is a record, and leave it off for pages of running text.
What to expect on harder files
| File | PDFBox 3.0.8 |
|---|---|
| Hebrew | In reading order, including a sentence with an English name and a year |
| Font without a Unicode map | Correct text, read from the font |
| Scan | Empty: there is no text in the file |
| Password-protected | InvalidPasswordException |
PDFBox did better than most on the first two. It applies the Unicode rules for right-to-left text itself, and it reads the font when the file's own table of letters is missing; several other libraries return gibberish for that file. For a protected file, pass the password: Loader.loadPDF(file, "password").
Reading a 200-page file took about half a second, including starting the JVM.
From the command line
The same jar works as a tool, with no code:
java -jar pdfbox-app-3.0.8.jar export:text -i company-extract.pdf -consoleScans and other file types
PDFBox reads what is stored in a PDF. For a scanned page there is nothing stored, and for a Word or Excel file you need a different library (Apache POI).
100sands, too, reads only files that contain text: PDFs and HTML. It does not read scans, Word or Excel files. What it adds is the text in reading order in every language, with a tab between a label and its value, and named fields from documents of a kind you set up once. With Java's built-in HTTP client, the request is a multipart POST to https://api.100sands.com/v1/text with the file in a field named file and your key in the Authorization: Bearer header. The response is JSON with two fields: pages, the page count, and text, with pages separated by a form feed (\f). A scan is refused with status 422 and the code NO_TEXT_IN_FILE. The same request from the command line is in PDF to text from the command line.