Text extraction
Extract page text, Markdown and positioned text blocks with NexPDF for Java, and retrieve passages for a language model.
License module
Text extraction, Markdown export and the offline assistant are part of the viewer module and work
without a key.
Plain text of a page
extractPageText(pageIndex) returns the text of a page in reading order, with the layout
reconstructed into lines and paragraphs:
import com.nexdevit.nexpdf.NexPdfDocument;
import java.nio.file.Path;
try (NexPdfDocument doc = NexPdfDocument.open(Path.of("contract.pdf"))) {
StringBuilder text = new StringBuilder();
for (int i = 0; i < doc.pageCount(); i++) {
text.append(doc.extractPageText(i)).append("\n\n");
}
}The whole document as Markdown
extractMarkdown() keeps headings, lists and tables, which makes it a good input for search
indexes and language models:
String markdown = doc.extractMarkdown();Text blocks with positions
pageBlocksJson(pageIndex) returns the text blocks of a page with their font size and rectangle in
PDF points (parsed here with Jackson, one JSON library among many):
ObjectMapper json = new ObjectMapper();
for (JsonNode block : json.readTree(doc.pageBlocksJson(0))) {
String text = block.get("text").asText();
System.out.printf("%5.1fpt %s%n", block.get("size").asDouble(), text.substring(0, Math.min(60, text.length())));
}Each block has text, size, llx, lly, urx and ury.
Words with exact boxes
pageWordsJson(pageIndex, optionsJson) returns every word of a page with its exact box:
JsonNode page = json.readTree(doc.pageWordsJson(0, "{\"glyphs\":true}")); // or null
for (JsonNode w : page.get("words")) {
System.out.println(w.get("text").asText() + " " + w.get("bbox") + " line " + w.get("line"));
}Each word has text, bbox ([llx, lly, urx, ury]), quad (eight numbers: baseline start,
baseline end, top end, top start, so it follows rotated text), font, size, angle and line.
{"glyphs":true} adds glyphs, each with text, bbox, quad and code.
Extracted and copied text is in logical order, also for text the engine wrote with shaping and bidi.
Passages for a language model
askDocument(question, k, maxChars) ranks the passages of the document against a question,
offline, and returns the k best with a page-tagged context you can send to a language model.
maxChars = 0 uses the default limit (200,000 characters).
JsonNode result = json.readTree(doc.askDocument("When does the contract end?", 5, 0));
for (JsonNode p : result.get("passages")) {
System.out.println(p.get("page") + " " + p.get("score").asDouble());
}
String prompt = "Answer from this document:\n" + result.get("context").asText()
+ "\n\nQuestion: When does the contract end?";Scanned documents
Pages that are images have no text to extract. Run OCR first to add a searchable text layer.
Related
- Search
- Conversion for HTML, JSON, XML and CSV output