Locate PDF Keywords with Page Numbers and Coordinates Using Apache PDFBox in Java
This tutorial demonstrates how to use Apache PDFBox to find keywords in PDF documents and retrieve their exact page numbers, coordinates, and bounding boxes, covering character-level position extraction, coordinate system conversion, cross-line matching, highlighting, and handling encrypted or rotated pages.
Why Apache PDFBox for PDF Keyword Location
When building features like contract review, invoice recognition, or electronic signing, a common requirement is to locate a keyword in a PDF — determining its page number and precise position on the page — so you can highlight, annotate, stamp, or navigate to it. Simply extracting text with a library loses all positional information; you need character-level coordinates.
Among Java PDF libraries, Apache PDFBox (Apache 2.0 license) is the most pragmatic choice: free for commercial use, mature community, complete text extraction plus character positions, and stable API. iText (AGPL/commercial) requires a paid license for commercial use; PDFClown (LGPL) is lightweight but poorly documented; JPedal is primarily commercial.
PDFBox Text Extraction and Coordinate Model
Two Extraction Levels
PDFTextStripper : Default whole-page text concatenation — convenient for reading but discards position data .
Character-level positions : Override processTextPosition to capture each TextPosition object, which carries the character, its coordinates, width, height, font, and font size.
Keyword location requires the second approach.
TextPosition Core Fields
getUnicode()— Character content (Unicode) getX() — Character left-edge x (PDF coordinate system) getY() — Character baseline y (PDF coordinate system) getWidth() — Character width getHeight() — Character height getFont() / getFontSizeInPt() — Font and font size
PDF Coordinate System: Origin at Bottom-Left
PDF coordinate system:
Top-left (0, pageHeight)
Bottom-right (pageWidth, 0)
Origin (0,0) at [bottom-left], y axis points up
Screen/image coordinate system:
Origin (0,0) at [top-left], y axis points downPDFBox returns y from the bottom up; conversion to screen coordinates requires flipping.
Page Dimensions
PDPage page = doc.getPage(i);
PDRectangle box = page.getMediaBox();
float pageWidth = box.getWidth();
float pageHeight = box.getHeight();Why Text Gets Fragmented
PDF text is not a continuous string but a sequence of glyph fragments in drawing order:
A single word may split into multiple TextPosition objects.
Different fonts or sizes on the same line create separate segments.
Cross-line and cross-column ordering is even more complex.
Therefore, the first step is to collect character positions in order, then reconstruct a matchable text stream.
Collecting Character Positions + Keyword Matching + Bounding Box Calculation
Step 1: Custom Collector — Record Position per Character
import org.apache.pdfbox.text.PDFTextStripper;
import org.apache.pdfbox.text.TextPosition;
import java.util.ArrayList;
import java.util.List;
public class PositionCollector extends PDFTextStripper {
private final List<TextPosition> positions = new ArrayList<>();
@Override
protected void processTextPosition(TextPosition text) {
positions.add(text);
super.processTextPosition(text); // let parent build default text
}
public List<TextPosition> getPositions() {
return positions;
}
}Step 2: Iterate Pages, Build Character Sequence, Match Keyword
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class KeywordLocator {
public List<Hit> locate(File pdfFile, String keyword) throws IOException {
List<Hit> hits = new ArrayList<>();
try (PDDocument document = PDDocument.load(pdfFile)) {
int total = document.getNumberOfPages();
for (int pageIndex = 0; pageIndex < total; pageIndex++) {
PDPage page = document.getPage(pageIndex);
PositionCollector collector = new PositionCollector();
collector.setStartPage(pageIndex + 1); // 1-based
collector.setEndPage(pageIndex + 1);
collector.getText(document);
List<TextPosition> positions = collector.getPositions();
StringBuilder sb = new StringBuilder();
for (TextPosition p : positions) {
sb.append(p.getUnicode());
}
String pageText = sb.toString();
int cursor = 0;
while (cursor <= pageText.length() - keyword.length()) {
int idx = pageText.indexOf(keyword, cursor);
if (idx < 0) break;
TextPosition start = positions.get(idx);
TextPosition end = positions.get(idx + keyword.length() - 1);
float x = start.getX();
float y = start.getY();
float endX = end.getX() + end.getWidth();
float width = endX - x;
float height = Math.max(start.getHeight(), end.getHeight());
hits.add(new Hit(pageIndex + 1, x, y, width, height, pageText));
cursor = idx + keyword.length();
}
}
}
return hits;
}
}Hit Result Object
public class Hit {
private final int page;
private final float x;
private final float y;
private final float width;
private final float height;
private final String context;
public Hit(int page, float x, float y, float width, float height, String context) {
this.page = page; this.x = x; this.y = y;
this.width = width; this.height = height; this.context = context;
}
// getters
public int getPage() { return page; }
public float getX() { return x; }
public float getY() { return y; }
public float getWidth() { return width; }
public float getHeight() { return height; }
public String getContext() { return context; }
}How the Bounding Box Is Computed
x = start character's x
y = start character's baseline y
width = end character right edge - start character left edge
height = max(start height, end height)If the keyword uses a uniform font size, the start character's width/height suffice; for mixed sizes, using the maximum height is safer.
Usage Example
public class Demo {
public static void main(String[] args) throws IOException {
KeywordLocator locator = new KeywordLocator();
List<Hit> hits = locator.locate(new File("contract.pdf"), "违约责任");
for (Hit hit : hits) {
System.out.printf("Page %d, x=%.1f y=%.1f, w=%.1f h=%.1f%n",
hit.getPage(), hit.getX(), hit.getY(), hit.getWidth(), hit.getHeight());
}
}
}Coordinate Conversion: PDF Coordinates to Screen/Image Coordinates
Why Convert
PDFBox returns PDF coordinates (origin bottom-left, y up); front-end display, image annotation, and OCR boxes typically use top-left origin with y down.
Conversion Formula
// PDF → screen/image
float screenX = pdfX;
float screenY = pageHeight - pdfY - pdfHeight;Complete utility:
public class CoordinateConverter {
/**
* @param pdfX PDF x
* @param pdfY PDF y (baseline, bottom-left origin)
* @param height Keyword height
* @param pageHeight Page height
* @return y in top-left origin coordinate system
*/
public static float toScreenY(float pdfX, float pdfY,
float height, float pageHeight) {
return pageHeight - pdfY - height;
}
}Baseline vs. Character Top
TextPosition.getY()is the baseline , not the character top. When computing the bounding box, height must include the ascent; if annotation boxes misalign, check whether baseline was mistaken for top.
Units
PDF internal unit is point (pt) , 1 pt = 1/72 inch. To convert to pixels, use the rendering DPI: pixel = pt * dpi / 72 The DPI used for rendering must match the DPI used for coordinate conversion, otherwise boxes will shift.
Cross-Line Matching, Highlighting, Encryption, and Rotated Pages
Cross-Line Keyword Matching
The simple indexOf only matches continuous characters on the same line . If a keyword is split by a line break (e.g., "违约\n责任"), it won't match.
Improved approach:
Group TextPosition objects by line (using y coordinate to detect same line).
Match within each line first; for cross-line matches, concatenate adjacent line texts and record positions of the split characters.
Merge the two lines' rectangles for the bounding box (min x, min y, total width, total height).
// Simplified: merge bounding boxes for cross-line match
float boxX = Math.min(firstLine.getX(), secondLine.getX());
float boxY = Math.min(firstLine.getY(), secondLine.getY());
float boxWidth = Math.max(firstLine.getX() + firstLine.getWidth(),
secondLine.getX() + secondLine.getWidth()) - boxX;
float boxHeight = Math.abs(firstLine.getY() - secondLine.getY())
+ Math.max(firstLine.getHeight(), secondLine.getHeight());Adding Highlight Annotations
After locating coordinates, add a highlight annotation directly with PDFBox:
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationHighlight;
import org.apache.pdfbox.pdmodel.common.PDRectangle;
private void addHighlight(PDPage page, Hit hit) {
PDRectangle rect = new PDRectangle(hit.getX(), hit.getY(), hit.getWidth(), hit.getHeight());
PDAnnotationHighlight highlight = new PDAnnotationHighlight();
highlight.setRectangle(rect);
page.getAnnotations().add(highlight);
}Save the modified document:
document.save("contract-highlighted.pdf");Encrypted PDFs
Load with password:
PDDocument document = PDDocument.load(pdfFile, "password".toCharArray());Empty password or restricted-permission documents will refuse text extraction; verify decryption rights first.
Rotated Pages
Pages may have a rotation (90/180/270). TextPosition provides rotation info; coordinates must be transformed according to the page rotation angle:
int rotation = page.getRotation();
// For non-0/360, flip x, y, width, height according to rotation directionGeneral practice: compute in unrotated coordinates, then map the rectangle back to the display coordinate system based on rotation; for strict requirements, refer to PDFBox rendering coordinate utilities.
Normalized Matching
Real-world PDFs often contain full-width/half-width variants, extra spaces, case differences. Normalize before matching:
private static String normalize(String text) {
return text.replaceAll("\\s+", "")
.replace('(', '(').replace(')', ')')
.toLowerCase();
}Important : Normalization is only for matching logic; coordinates still map to original character positions . Do not use normalized string indices to look up positions.
Understanding PDFBox's text position model and coordinate conversion enables you to tackle electronic signing, contract review, OCR annotation, and document extraction. It also helps diagnose issues like garbled extraction, coordinate offsets, and cross-line match failures.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
