Docs / Guides
OCR and searchable PDFs
SoftZenPdf.Ocr recognises the text in scanned images and pages with the Tesseract 5 engine, and turns scans into searchable PDFs: the page still shows the scan, with the recognised words laid invisibly over it so they can be searched, selected and copied. It works on image files and on existing scanned PDFs.
Installing
OCR is a separate package, so the core SoftZenPdf package stays free of dependencies:
dotnet add package SoftZenPdf.Ocr
It brings in SoftZenPdf and the Tesseract wrapper (Apache 2.0), which includes the native Tesseract and Leptonica libraries for Windows x64 and x86.
Tesseract also needs language data, one .traineddata file per language, which you download
once and ship with your application:
- tessdata_fast: small and quick (English is about 4 MB). A good default.
- tessdata_best: larger and slower, a little more accurate on difficult scans.
Put the files in a folder such as tessdata next to your application, and give that folder to the engine.
Linux: install Tesseract 5 and Leptonica from your distribution (for example
apt install libtesseract5 liblept5 on Debian and Ubuntu). The wrapper looks for the libraries under the
names it uses on Windows, so link them into an x64 folder next to your application as
libtesseract50.so and libleptonica-1.82.0.so. macOS is not supported.
Creating the engine
using SoftZenPdf;
using SoftZenPdf.Ocr;
var engine = new TesseractOcrEngine(new TesseractOcrOptions
{
TessDataPath = "tessdata", // the folder holding eng.traineddata
Languages = ["eng"],
});
- Loading the language data takes a moment, so create one engine and reuse it for every image.
- An engine recognises one image at a time; calls from several threads wait their turn. To recognise images in parallel, create one engine per thread.
- Dispose the engine when you are done, to release the native memory.
- A missing folder or
.traineddatafile throws straight away, naming the file to download.
Recognising an image
Recognize accepts any PdfImage: JPEG, PNG, GIF, BMP or a TIFF page,
with its EXIF or TIFF orientation applied first. The result has paragraphs, lines and words, each with its position in
pixels from the top-left corner and a confidence from 0 to 100:
using SoftZenPdf;
using SoftZenPdf.Ocr;
OcrPage page = engine.Recognize(PdfImage.FromFile("invoice.png"));
Console.WriteLine($"{page.Width}×{page.Height} px, mean confidence {page.MeanConfidence:0}");
foreach (var line in page.Lines)
Console.WriteLine(line.Text);
var total = page.Words.First(w => w.Text == "3,944.00");
Console.WriteLine($"'{total.Text}' at x={total.Bounds.Left}, y={total.Bounds.Top} ({total.Confidence:0}%)");
2480×1400 px, mean confidence 96
INVOICE 2026-0417
Northwind Traders, 42 Harbour Street, Leeds
Date: 14 September 2026
Office chairs, quantity 12, total 1,548.00
Standing desks, quantity 4, total 2,396.00
Amount due: 3,944.00 GBP
'3,944.00' at x=507, y=940 (96%)
page.Text joins words with spaces, lines with line feeds and paragraphs with a blank line. Each line also has a
Baseline, and OcrBounds gives Left, Top, Width, Height,
Right and Bottom, which is what you need to read fields from fixed positions on a form.
Plain text from image files
using SoftZenPdf;
string text = engine.RecognizeText("shipping.tif"); // every page of a multi-page TIFF, separated by form feeds
File.WriteAllText("shipping.txt", text);
RecognizeFile returns one OcrPage per page instead. Without a license key, the plain text starts with an evaluation notice line (see Limits).
Making scans searchable
OcrPdfCreator turns images into a PDF with one page per image (and one per page of a multi-page TIFF). Each page
shows the scan at its own resolution, so a 300 dpi scan of an A4 sheet becomes an A4 page:
using SoftZenPdf;
using SoftZenPdf.Ocr;
var creator = new OcrPdfCreator(engine);
IReadOnlyList<OcrPage> pages = creator.CreatePdf(["invoice.png", "shipping.tif"], "scans-searchable.pdf");
Console.WriteLine($"{pages.Count} pages; first line: {pages[0].Lines.First().Text}");
- Each word is placed on its baseline and stretched to the exact width it has in the scan, so searching highlights the right place and selecting a line selects what you see.
- Spaces and line breaks are real text, so copied text keeps its words and lines.
- The text layer uses a built-in font that embeds in a few hundred bytes and accepts every script, including Cyrillic, Greek, Chinese and Japanese.
- The scans are embedded as they are: JPEGs are not re-encoded, so the file is about the size of the images.
CreateDocument returns the unsaved PdfDocument with the text of each page, so you can set metadata,
add pages or encrypt it before saving. AddPage(document, image) adds a single scanned page to a document you are
building yourself.
Searchable PDF/A for archiving
Set Conformance to create the document in PDF/A-2b mode:
using SoftZenPdf;
using SoftZenPdf.Ocr;
var creator = new OcrPdfCreator(engine, new OcrPdfOptions
{
Conformance = PdfAConformance.PdfA2b,
PageOptions = new ImagePageOptions { PageSize = PageSize.A4, Margin = 36 },
});
var result = creator.CreateDocument(["invoice.png"]);
result.Document.Info.Title = "Invoice 2026-0417";
result.Document.Save("invoice-archive.pdf"); // validated as PDF/A-2b on save
The built-in text layer font is embedded and meets the PDF/A rules, so nothing else is needed. Searchable PDF/A files made from JPEG, PNG and CCITT fax scans, with English and non-Latin text layers, pass the veraPDF PDF/A-2b validator. CMYK JPEGs are refused in PDF/A mode, as they are elsewhere in SoftZenPdf.
Existing scanned PDFs
AddTextLayer makes a PDF from a scanner or copier searchable:
using SoftZenPdf;
using SoftZenPdf.Ocr;
var creator = new OcrPdfCreator(engine);
OcrPdfUpdateResult result = creator.AddTextLayer("scanned.pdf", "scanned-searchable.pdf");
Console.WriteLine($"{result.Pages.Count(p => p is not null)} of {result.Pages.Count} pages recognised");
foreach (var warning in result.Warnings)
Console.WriteLine(warning); // pages left unchanged, and why
- The text is added as an incremental update: the original file is kept byte for byte, with its scans, bookmarks, metadata and form, and a PDF/A file stays PDF/A.
- The largest image on each page is recognised, including images inside form XObjects. Scans that are drawn sideways or upside down, or on pages turned with
/Rotate, are recognised the right way up. - Images can be JPEG, CCITT fax (Group 4 and Group 3) or Flate/LZW-compressed in grey, RGB, CMYK, ICC, indexed, Separation, DeviceN or Lab colour, at 1 to 16 bits per sample.
- Pages that already have text are left alone, so running it twice does not add the text twice. Set
SkipPagesWithText = falseto recognise them anyway. - Encrypted files open with the
passwordargument and need permission to change page content.
Pages left unchanged are null in result.Pages, and result.Warnings says why: the page
already has text, has no image, or uses an image encoding SoftZenPdf cannot decode (JBIG2 or JPEG 2000).
Engine options
using SoftZenPdf;
using SoftZenPdf.Ocr;
using var engine = new TesseractOcrEngine(new TesseractOcrOptions
{
TessDataPath = "tessdata",
Languages = ["eng"], // several, such as ["eng", "deu"], if the scans mix languages
PageSegmentation = OcrPageSegmentation.SparseText,
Resolution = 300, // when the file's own resolution is missing or wrong
MinimumConfidence = 60, // drop words the engine is unsure of
Variables = new Dictionary<string, string> { ["preserve_interword_spaces"] = "1" },
});
| Option | What it does |
|---|---|
Languages | Tesseract language codes, such as eng, deu, fra, ara or chi_sim. Each needs its .traineddata file. Defaults to English. |
PageSegmentation | Auto for whole pages (the default), SingleColumn, SingleBlock, SingleLine or SingleWord for crops, and SparseText for receipts and forms with scattered labels. |
Resolution | The dpi to assume for every image. Without it, the file's resolution is used, or Tesseract estimates it from the text size. |
MinimumConfidence | Leaves out words with a lower confidence (0 to 100). Defaults to 0, which keeps every word. |
Variables | Any other Tesseract variable, such as tessedit_char_whitelist to read only digits. An unknown name throws. |
OcrPdfOptions sets the page layout (PageOptions, as for image pages),
the text layer Font, Conformance and SkipPagesWithText.
Getting good results
- Resolution: scan at 300 dpi. Text smaller than about 20 pixels high is read poorly; below 200 dpi, accuracy drops quickly.
- Language: list every language that appears on the page. A wrong language model is the most common cause of garbled words.
- Layout: use
SparseTextfor receipts, labels and forms, andSingleLineorSingleWordfor regions you have cropped yourself. - Quality: straight, evenly lit, high-contrast scans work best. Photos taken at an angle, heavy JPEG compression and coloured backgrounds lower the confidence.
- Confidence: check
OcrWord.Confidencebefore trusting important values such as amounts and dates.
Checking the text layer
To see where the invisible text sits, draw it in red with a visible font:
using SoftZenPdf;
using SoftZenPdf.Ocr;
var creator = new OcrPdfCreator(engine, new OcrPdfOptions
{
ShowTextLayer = true, // draw the text layer in red
Font = TrueTypeFont.FromFile("NotoSans-Regular.ttf"), // a visible font, so there is something to see
});
creator.CreatePdf(["invoice.png"], "invoice-layer-check.pdf");
Limits
- Windows x64 and x86 work out of the box; Linux needs the system libraries (see Installing); macOS is not supported.
- JBIG2 and JPEG 2000 images in existing PDFs cannot be decoded, and inline images are skipped. Only the largest image on a page is recognised, so scans stored as several strips per page are not fully read.
- Right-to-left text (Arabic, Hebrew) is recognised and placed correctly, but some viewers may copy it in reverse order.
- The text layer is plain text: there are no tags, columns or tables in the structure of the PDF.
SoftZenPdf.Ocr is covered by your SoftZenPdf license. Until a key is set (see Licensing),
saved PDFs carry the evaluation mark and plain text (OcrPage.Text, RecognizeText) starts with an
evaluation notice line; words, lines, positions and confidence are never changed, so you can measure accuracy fully
while you evaluate. Tesseract and its language data are Apache 2.0 licensed.
API: TesseractOcrEngine, OcrPdfCreator, OcrPage, TesseractOcrOptions, OcrPdfOptions.