Text extraction
Extract page text, Markdown and positioned text blocks with NexPDF for Rust, 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
extract_page_text(page_index) returns the text of a page in reading order, with the layout
reconstructed into lines and paragraphs:
use nexpdf_sdk::Document;
fn main() -> nexpdf_sdk::Result<()> {
let doc = Document::open("contract.pdf")?;
let pages = (0..doc.page_count()? as usize)
.map(|i| doc.extract_page_text(i))
.collect::<nexpdf_sdk::Result<Vec<_>>>()?;
let text = pages.join("\n\n");
println!("{text}");
Ok(())
}The whole document as Markdown
extract_markdown() keeps headings, lists and tables, which makes it a good input for search
indexes and language models:
let markdown = doc.extract_markdown()?;Text blocks with positions
page_blocks_json(page_index) returns the text blocks of a page with their font size and rectangle
in PDF points:
for block in doc.page_blocks_json_value(0)?.as_array().into_iter().flatten() {
let text: String = block["text"].as_str().unwrap_or("").chars().take(60).collect();
println!("{:>5.1}pt {text}", block["size"].as_f64().unwrap_or(0.0));
}Each block has text, size, llx, lly, urx and ury. The loop uses the serde feature;
page_blocks_json returns the same JSON as a String.
Words with exact boxes
page_words_json(page_index, options_json) returns the words of a page with exact boxes, computed
from the fonts' glyph widths and the text state:
let words = doc.page_words_json_value(0, r#"{"glyphs":true}"#)?; // `serde`; or page_words_json
for w in words["words"].as_array().into_iter().flatten() {
println!("{} {} line {} {}°", w["text"], w["bbox"], w["line"], w["angle"]);
}The result is {"page","words":[…]}. 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. options_json may be None; {"glyphs":true} adds
glyphs to each word, each with text, bbox, quad and code.
Passages for a language model
ask_document(question, k, max_chars) 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.
max_chars 0 uses the default limit (200,000 characters). It returns a JSON String, which
serde_json parses:
fn main() -> Result<(), Box<dyn std::error::Error>> {
let doc = nexpdf_sdk::Document::open("contract.pdf")?;
let question = "When does the contract end?";
let result: serde_json::Value = serde_json::from_str(&doc.ask_document(question, 5, 0)?)?;
for p in result["passages"].as_array().into_iter().flatten() {
println!("{} {:.2} {}", p["page"], p["score"].as_f64().unwrap_or(0.0), p["text"]);
}
let prompt = format!(
"Answer from this document:\n{}\n\nQuestion: {question}",
result["context"].as_str().unwrap_or("")
);
println!("{prompt}");
Ok(())
}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