Make a scanned PDF searchable in C#
Read the text of scanned pages and lay it over the scans, so the PDF selects, copies and searches.
Short answer
Section titled “Short answer”Load the OCR models with OnnxOcrEngine.Load, then call PdfOcr.MakeSearchable on the document and
save it. Each page’s scan is found, turned upright, read, and every word is laid over it as
invisible text. The pages look the same as before.
#:package PdfNetStack.Ocr@1.2.0using PdfNetStack;using PdfNetStack.Ocr;
// Models: python tools/fetch_ocr_models.py models (checked against pinned SHA-256 hashes).using var engine = OnnxOcrEngine.Load("models", new OnnxOcrEngineOptions { Languages = ["latin", "arabic"] });
PdfDocument doc = PdfDocument.Open("scan.pdf");var ocr = new PdfOcr(engine, new PdfOcrOptions { Languages = ["latin", "arabic"] });PdfOcrReport report = ocr.MakeSearchable(doc); // invisible text laid over each scandoc.Save("scan-searchable.pdf");Console.WriteLine(report.Text);PdfNetStack.Ocris a separate package on NuGet. It runs the PP-OCRv5 mobile models on ONNX Runtime.- Get the models from the
PdfNetStack.Ocr.Modelspackage, or withpython tools/fetch_ocr_models.py models. They are checked against pinned SHA-256 hashes when loaded. - A page qualifies when its scan is one image covering at least half the page. Pages that already
have text are left alone.
Recognizereports the text without changing the document. - ONNX Runtime’s official builds send telemetry by default. The engine turns it off before loading
a model; on Linux and macOS also set
ORT_DISABLE_TELEMETRY=1before the process starts.
Related
Section titled “Related”- OCR
- Extract text
- API: PdfOcr, OnnxOcrEngine