OCR
Recognise scanned pages and add an invisible, searchable text layer with NexPDF for Rust.
License module
OCR needs the ocr module (Enterprise tier).
ocr(options_json) recognises the text of scanned pages and adds it as an invisible text layer, so
the PDF becomes searchable and its text can be extracted. The page images are not changed. It takes
&mut self and returns the report as a JSON String.
use nexpdf_sdk::Document;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let mut doc = Document::open("scan.pdf")?;
let report: serde_json::Value = serde_json::from_str(&doc.ocr(r#"{"languages":"por+eng"}"#)?)?;
println!("{} {} {} {}", report["engine"], report["pages"], report["words"], report["confidence"]);
doc.save("searchable.pdf")?;
Ok(())
}doc.ocr(None) uses every default.
Pages scanned sideways, upside down or slightly skewed are handled: the orientation (0, 90, 180 or 270 degrees) and the skew are detected, the page is read upright and the text layer is mapped back onto the original page. The built-in engine corrects skew up to 20 degrees, the neural engine up to 15 degrees either way (besides quarter turns). The built-in engine also reads ß, œ, æ, ÿ, ì, Ò, Ù and the Catalan middle dot, and drops scanner specks.
Options
| Option | Default | Meaning |
|---|---|---|
engine | auto | builtin, tesseract, neural, or auto: a loaded neural model that reads the requested languages, else Tesseract when it is installed with every requested language, else the built-in engine |
languages | por+eng+spa | Language codes joined with + (Tesseract codes such as chi_sim or ISO 639-1 codes such as ar). The built-in engine reads Latin-script text in any language |
dpi | 300 | Resolution the pages are rendered at for recognition |
pages | every page | 0-based page indices |
force | false | Also process pages that already have text |
The report
| Field | Meaning |
|---|---|
engine | The engine that ran |
pages | Pages recognised |
skipped | Pages skipped because they already had text |
words | Words recognised |
confidence | Average word confidence, 0 to 1 |
text | The recognised text, one string per page |
Other scripts: neural models
The built-in engine reads printed Latin-script text (English, Portuguese, Spanish, French, German and others) with no models. For Chinese, Japanese, Korean, Arabic, Persian, Urdu, Cyrillic, Devanagari, Thai, Greek and other scripts, load neural OCR models at run time. No model is bundled: your application downloads or ships the ones it needs.
You need one text detection model, which serves every language, and one recognition model
per script with its character dictionary (UTF-8 text, one symbol per line). Any PaddleOCR
detection and CTC recognition model exported to ONNX works (PP-OCRv3, v4 and v5). A ready-made set
is monkt/paddleocr-onnx on Hugging Face (Apache-2.0):
| File | Use | languages |
|---|---|---|
detection/v3/det.onnx (2.4 MB) | Detection, mobile | all |
detection/v5/det.onnx (88 MB) | Detection, server | all |
languages/chinese/rec.onnx + dict.txt | Chinese, Japanese | zh+ja+en |
languages/korean/… | Korean | ko |
languages/arabic/… | Arabic, Persian, Urdu | ar+fa+ur |
languages/eslav/… | Cyrillic | ru+uk+be+bg |
languages/hindi/… | Devanagari | hi+mr+ne+sa |
The PaddleOCR model zoo (converted with paddle2onnx) and RapidOCR publish the same models. The
dictionary must be the one the model was trained with; loading checks it.
nexpdf_sdk::ocr_load_model(options_json, model, dictionary) takes the model bytes as &[u8] and
the dictionary as a string; a detection model takes None:
use std::path::Path;
use nexpdf_sdk::Document;
fn main() -> Result<(), Box<dyn std::error::Error>> {
let models = Path::new("models");
nexpdf_sdk::ocr_load_model(
r#"{"kind":"detection"}"#,
&std::fs::read(models.join("detection/v3/det.onnx"))?,
None,
)?;
let dictionary = std::fs::read_to_string(models.join("languages/arabic/dict.txt"))?;
nexpdf_sdk::ocr_load_model(
r#"{"kind":"recognition","languages":"ar+fa+ur","name":"arabic"}"#,
&std::fs::read(models.join("languages/arabic/rec.onnx"))?,
&dictionary,
)?;
println!("{}", nexpdf_sdk::ocr_models_json()?); // kind, name, languages, symbols, size
let mut doc = Document::open("scan-ar.pdf")?;
let report: serde_json::Value = serde_json::from_str(&doc.ocr(r#"{"languages":"ara"}"#)?)?;
println!("{}", report["engine"]); // "neural (arabic)"
doc.save("searchable-ar.pdf")?;
nexpdf_sdk::ocr_unload_models("ar")?; // or None for every model
Ok(())
}Models are loaded once per process and used by every document, on every thread.
ocr_load_model returns 1; a model that cannot be loaded (or a dictionary that does not match
it) is an Err with the engine's message. ocr_unload_models returns the number of models
removed. ocr_load_model options:
| Option | Meaning |
|---|---|
kind | detection, recognition or classification (required) |
languages | Languages a recognition model reads, joined with +, as ISO 639-1 (ar) or Tesseract (ara) codes |
name | Name in listings; loading the same kind and name again replaces the model |
input_height | Recognition input height when the model leaves it open (default 48) |
max_side | Detection: longest side, in pixels, of the page image the detector sees (default 1536) |
An optional text-direction classifier (the PaddleOCR cls model, 0 or 180 degrees, input
3x48x192) decides whether a line is upright or upside down. It takes no dictionary:
nexpdf_sdk::ocr_load_model(
r#"{"kind":"classification"}"#,
&std::fs::read("models/cls.onnx")?,
None,
)?;Without it, the recogniser reads the line both ways and the more confident reading wins.
With several languages ("rus+chi_sim") every matching model reads each line and the most confident
reading wins. Slanted lines are read as rotated boxes (a perspective crop) and the text layer follows
the slant. Arabic word spaces are restored from the gaps in the ink, presentation forms become plain
letters and right-to-left lines are written in logical order. Vertical CJK columns are read right to
left, in the report and in the text layer (Identity-V), and text extraction reads vertical text as
columns from right to left, so the text extracts, searches and copies in reading order. Mobile models (a few MB)
are fast; server models are more accurate and much larger.
On iOS, ship the .onnx files and dictionaries in the app bundle or download them once into
Application Support. On Android, put them in assets/ (mark .onnx as noCompress in Gradle so
they are not inflated twice) or download them into the app's files folder. Either way, read them
into memory and call ocr_load_model once at start-up.
The text layer uses glyph-less TrueType/CID fonts, so convert to PDF/A after OCR when the file must be PDF/A.
Limits
- Curved lines are read only when the curve is gentle.
- With the neural engine, skew beyond 15 degrees is not corrected.
Using Tesseract
The built-in engine needs nothing else. To use Tesseract, install the tesseract program and its
language data on the machine (for example apt install tesseract-ocr tesseract-ocr-por) and pass
"engine":"tesseract" or keep auto.