Skip to content

Make a scanned PDF searchable in C#

Since 1.1View as Markdown

Read the text of scanned pages and lay it over the scans, so the PDF selects, copies and searches.

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.

recipe-make-scanned-pdf-searchable.cs
#:package PdfNetStack.Ocr@1.2.0
using 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 scan
doc.Save("scan-searchable.pdf");
Console.WriteLine(report.Text);
  • PdfNetStack.Ocr is a separate package on NuGet. It runs the PP-OCRv5 mobile models on ONNX Runtime.
  • Get the models from the PdfNetStack.Ocr.Models package, or with python 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. Recognize reports 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=1 before the process starts.