Skip to Content
NexPDF

OCR

Recognise scanned pages and add an invisible, searchable text layer with NexPDF for .NET.

English

License module

OCR needs the ocr module (Enterprise tier).

Ocr(optionsJson) 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.

using System.Text.Json.Nodes;
using Nexdevit.NexPdf;

using var doc = NexPdfDocument.Open("scan.pdf");
var report = JsonNode.Parse(doc.Ocr("""{"languages":"por+eng"}"""))!;
Console.WriteLine($"{report["engine"]} {report["pages"]} {report["words"]} {report["confidence"]}");
doc.Save("searchable.pdf");

Options

OptionDefaultMeaning
engineautobuiltin, 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
languagespor+eng+spaLanguage 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
dpi300Resolution the pages are rendered at for recognition
pagesevery page0-based page indices
forcefalseAlso process pages that already have text

The report

FieldMeaning
engineThe engine that ran
pagesPages recognised
skippedPages skipped because they already had text
wordsWords recognised
confidenceAverage word confidence, 0 to 1
textThe 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):

FileUselanguages
detection/v3/det.onnx (2.4 MB)Detection, mobileall
detection/v5/det.onnx (88 MB)Detection, serverall
languages/chinese/rec.onnx + dict.txtChinese, Japanesezh+ja+en
languages/korean/…Koreanko
languages/arabic/…Arabic, Persian, Urduar+fa+ur
languages/eslav/…Cyrillicru+uk+be+bg
languages/hindi/…Devanagarihi+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.

var models = "models";
NexPdfSdk.OcrLoadModel("""{"kind":"detection"}""",
    File.ReadAllBytes(Path.Combine(models, "detection/v3/det.onnx")));
NexPdfSdk.OcrLoadModel("""{"kind":"recognition","languages":"ar+fa+ur","name":"arabic"}""",
    File.ReadAllBytes(Path.Combine(models, "languages/arabic/rec.onnx")),
    File.ReadAllText(Path.Combine(models, "languages/arabic/dict.txt")));

Console.WriteLine(NexPdfSdk.OcrModelsJson());   // kind, name, languages, symbols, size

using (var doc = NexPdfDocument.Open("scan-ar.pdf"))
{
    var report = JsonNode.Parse(doc.Ocr("""{"languages":"ara"}"""))!;
    Console.WriteLine(report["engine"]);         // "neural (arabic)"
    doc.Save("searchable-ar.pdf");
}

NexPdfSdk.OcrUnloadModels("ar");                // or null for every model

Models are loaded once per process and used by every document. OcrLoadModel options:

OptionMeaning
kinddetection, recognition or classification (required)
languagesLanguages a recognition model reads, joined with +, as ISO 639-1 (ar) or Tesseract (ara) codes
nameName in listings; loading the same kind and name again replaces the model
input_heightRecognition input height when the model leaves it open (default 48)
max_sideDetection: longest side, in pixels, of the page image the detector sees (default 1536)

With several languages ("rus+chi_sim") every matching model reads each line and the most confident reading wins. Right-to-left lines are written in logical order (Arabic word spaces are restored from the gaps in the ink and presentation forms become plain letters), and vertical CJK columns are read top to bottom, columns right to left, so the text extracts, searches and copies in reading order. Slanted lines are read along their slant and the text layer follows it. Mobile models (a few MB) are fast; server models are more accurate and much larger.

Text direction model

A classification model is the optional PaddleOCR cls text-direction model (0° or 180°, input 3×48×192). It takes no dictionary:

NexPdfSdk.OcrLoadModel("""{"kind":"classification"}""",
    File.ReadAllBytes(Path.Combine(models, "cls.onnx")));

Without it, the recogniser reads each line both ways and the more confident reading decides whether the line is upright or upside down.

Rotated and skewed scans

Pages scanned sideways, upside down or slightly crooked are read upright: the engine finds the orientation (0°, 90°, 180° or 270°) and the skew, and maps the text layer back onto the original page. The built-in engine corrects skew up to 20°, the neural engine up to 15° (besides quarter turns). The built-in engine also reads ß, œ, æ, ÿ, ì, Ò, Ù and the Catalan middle dot, and ignores scanner specks.

Limits: only gentle curves in curved lines are followed, and skew beyond 15° is not corrected by the neural engine.

The OCR text layer uses glyph-less fonts, so convert to PDF/A after OCR when the file must be PDF/A.

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.

On this page