Skip to Content
NexPDF

OCR

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

English

License module

OCR needs the ocr module (Enterprise tier).

ocr(options) 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.

import { PdfDocument } from '@nexdevit/nexpdf-node';

const doc = await PdfDocument.open('scan.pdf');
const report = doc.ocr({ engine: 'builtin', languages: 'por+eng' });
console.log(report.engine, report.pages, report.words, report.confidence);
await doc.save('searchable.pdf');

Options

OptionDefaultMeaning
engineautoauto uses the loaded neural models whose languages match, else the built-in engine; builtin always uses the built-in engine. Tesseract is not available under WebAssembly
languagespor+eng+spaLanguage codes joined with +. 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: PaddleOCR detection and recognition models in ONNX. 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). See the Python OCR guide for a ready-made set of models.

import { readFile } from 'node:fs/promises';
import { PdfDocument, ocrLoadModel, ocrModelsJson, ocrUnloadModels } from '@nexdevit/nexpdf-node';

ocrLoadModel('{"kind":"detection"}', await readFile('models/detection/v3/det.onnx'), null);
ocrLoadModel('{"kind":"recognition","languages":"ar+fa+ur","name":"arabic"}',
  await readFile('models/languages/arabic/rec.onnx'), await readFile('models/languages/arabic/dict.txt', 'utf8'));

console.log(JSON.parse(ocrModelsJson()));          // kind, name, languages, symbols, size

const doc = await PdfDocument.open('scan-ar.pdf');
const report = doc.ocr({ languages: 'ara' });
console.log(report.engine);                        // "neural (arabic)"
await doc.save('searchable-ar.pdf');

ocrUnloadModels('ar');                             // or null for every model

Models are loaded once per process (per worker thread, which has its own engine) 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)

An optional classification model is the PaddleOCR cls text-direction model (0 or 180 degrees, input 3×48×192). It takes no dictionary (null). Without it, upright and upside-down lines are told apart by the recogniser's confidence both ways.

ocrLoadModel('{"kind":"classification"}', await readFile('models/cls.onnx'), null);

The neural engine reads slanted lines as rotated boxes (the text layer follows the slant). Arabic word spaces are restored from the gaps in the ink, presentation forms are mapped to plain letters and the text is stored in logical order. Vertical CJK columns are read right to left, in the report and in the text layer, and text extraction reads vertical text as columns from right to left.

Orientation and skew

Pages scanned sideways, upside down or slightly skewed are corrected: 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 page images are not changed.

The built-in engine also reads ß, œ, æ, ÿ, ì, Ò, Ù and the Catalan middle dot, and ignores scanner specks.

Limits

  • Curved lines are read only when the curve is gentle.
  • With the neural engine, skew beyond 15 degrees is not corrected.
  • The OCR text layer uses glyph-less fonts, so convert to PDF/A after OCR when the file must be PDF/A.

Long jobs

ocr() is synchronous and blocks the event loop until it finishes. In a server, run it in a worker_threads worker or a separate job queue, and activate the license in that worker too.

For Tesseract, use a native SDK such as Python.

On this page