Search
Find text in a PDF with NexPDF for Java and get the page and rectangle of every match.
License module
Search is part of the viewer module and works without a key.
searchJson(query) searches every page, case-insensitively, and returns a JSON array of hits. The
example parses it with Jackson; any JSON library works.
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.nexdevit.nexpdf.NexPdfDocument;
import java.nio.file.Path;
ObjectMapper json = new ObjectMapper();
try (NexPdfDocument doc = NexPdfDocument.open(Path.of("contract.pdf"))) {
for (JsonNode hit : json.readTree(doc.searchJson("termination"))) {
System.out.println("page " + (hit.get("page").asInt() + 1) + ": " + hit.get("context").asText());
}
}Each hit has:
| Field | Meaning |
|---|---|
page | 0-based page index |
context | The text around the match |
llx, lly, urx, ury | The rectangle of the match in PDF points |
Highlight every match
With the annotations module you can turn the hits into highlight annotations:
for (JsonNode hit : json.readTree(doc.searchJson("termination"))) {
doc.addAnnotation(hit.get("page").asLong(), "Highlight", "#FFD400", 1.0, "",
hit.get("llx").asDouble(), hit.get("lly").asDouble(),
hit.get("urx").asDouble(), hit.get("ury").asDouble());
}
doc.save(Path.of("highlighted.pdf"));Redact every match
To remove the matches permanently instead, use redactMatches. See
Redaction.
Scanned documents
Search finds only real text. Run OCR on scanned pages first.