Search
Find text in a PDF with NexPDF for Rust and get the page and rectangle of every match.
License module
Search is part of the viewer module and works without a key.
search_json(query) searches every page, case-insensitively, and returns a JSON array of hits.
With the serde feature, search_json_value(query) returns it parsed:
use nexpdf_sdk::Document;
fn main() -> nexpdf_sdk::Result<()> {
let doc = Document::open("contract.pdf")?;
for hit in doc.search_json_value("termination")?.as_array().into_iter().flatten() {
println!("page {}: {}", hit["page"].as_u64().unwrap_or(0) + 1, hit["context"]);
}
Ok(())
}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:
let mut doc = Document::open("contract.pdf")?;
let hits = doc.search_json_value("termination")?;
for hit in hits.as_array().into_iter().flatten() {
let f = |k: &str| hit[k].as_f64().unwrap_or(0.0);
let page = hit["page"].as_u64().unwrap_or(0) as usize;
doc.add_annotation(page, "Highlight", "#FFD400", 1.0, "", f("llx"), f("lly"), f("urx"), f("ury"))?;
}
doc.save("highlighted.pdf")?;Redact every match
To remove the matches permanently instead, use redact_matches. See
Redaction.
Scanned documents
Search finds only real text. Run OCR on scanned pages first.