Skip to Content
NexPDF

OCR

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

English

License module

OCR needs the ocr module (Enterprise tier).

nexpdf_ocr(doc, 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 has no Dart method; call it through dart:ffi. The native reader also offers OCR in its More menu.

import 'dart:convert';
import 'dart:ffi';
import 'package:ffi/ffi.dart';
import 'nexpdf_ffi.dart';

// char *nexpdf_ocr(NexPdfDocument *doc, const char *options_json);
final ocr = nexpdfLib.lookupFunction<Pointer<Utf8> Function(Pointer<Void>, Pointer<Utf8>),
    Pointer<Utf8> Function(Pointer<Void>, Pointer<Utf8>)>('nexpdf_ocr');

final json = using((a) => nexpdfCall(() => takeString(ocr(doc.handle, '{"languages":"por+eng"}'.toNativeUtf8(allocator: a)))));
final report = jsonDecode(json!) as Map<String, Object?>;
print('${report['engine']} ${report['pages']} ${report['words']} ${report['confidence']}');
final searchable = doc.save();

OCR of many pages takes time: run it in a background isolate.

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

Tesseract is the tesseract command-line program. On iOS and Android, use the built-in engine (auto or builtin), which needs nothing else, or neural models for other scripts. On desktop, Tesseract is used when it is installed.

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. They work on every platform, phones included. 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.

sdk.ocrLoadModel(options, model, dictionary: ...), sdk.ocrModels() and sdk.ocrUnloadModels(languages) are Dart methods. Ship small models as Flutter assets and read them with rootBundle:

import 'dart:convert';
import 'dart:typed_data';
import 'package:ffi/ffi.dart';
import 'package:flutter/services.dart';
import 'package:nexpdf_flutter/nexpdf_flutter.dart';
import 'nexpdf_ffi.dart';

Future<Uint8List> asset(String key) async => (await rootBundle.load(key)).buffer.asUint8List();

sdk.ocrLoadModel({'kind': 'detection'}, await asset('assets/ocr/det.onnx'));
sdk.ocrLoadModel({'kind': 'recognition', 'languages': 'ar+fa+ur', 'name': 'arabic'},
    await asset('assets/ocr/arabic/rec.onnx'),
    dictionary: await rootBundle.loadString('assets/ocr/arabic/dict.txt'));

print(sdk.ocrModels());   // kind, name, languages, symbols, size

// ocr: the nexpdf_ocr lookup from the first example
final json = using((a) => nexpdfCall(() => takeString(ocr(doc.handle, '{"languages":"ara"}'.toNativeUtf8(allocator: a)))));
print((jsonDecode(json!) as Map<String, Object?>)['engine']);   // "neural (arabic)"

sdk.ocrUnloadModels('ar');   // or sdk.ocrUnloadModels() for every model

Where to keep the files:

  • iOS: in the app bundle (Flutter assets are), or downloaded once into the app's Application Support folder and read with File(path).readAsBytes().
  • Android: Flutter assets live in the APK. Mark .onnx files as noCompress in the app's Android Gradle configuration so they are not stored compressed and inflated again at load, or download them once into the app's files folder.
  • Larger server models are better downloaded on first use than shipped in the app.

Models are loaded once per process and used by every document. ocrLoadModel throws NexPdfException when a model or dictionary does not load. 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. Without it, upright and upside-down lines are told apart by the recogniser's confidence both ways.

sdk.ocrLoadModel({'kind': 'classification'}, await asset('assets/ocr/cls.onnx'));

With several languages ("rus+chi_sim") every matching model reads each line and the most confident reading wins. Mobile models (a few MB) are fast and the right choice on phones; server models are more accurate and much larger. Run OCR in a background isolate.

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, so the text extracts, searches and copies in reading order.

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.

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

On this page