Recognize Text in Scanned PDFs & Images (OCR)
- 19 minutes to read
The DevExpress optical character recognition (OCR) library is a standalone library that extends the PDF Document API with text recognition capabilities. The library ships as a separate NuGet package. The library recognizes text in scanned PDF documents and images and returns recognized text as text fragments, lines, and words with bounds and confidence values. The library can also create searchable PDF files from recognized images.
The OCR library recognizes text locally. The library includes built-in deep learning models and runs them in ONNX Runtime. You do not need external services or cloud APIs.
How the OCR Library Recognizes Text
The OcrEngine object prepares images and builds recognition results. An OCR provider recognizes text in each image. The built-in DocTrOcrProvider runs docTR deep learning models. You can also implement a custom OCR provider.
The OCR library recognizes text as follows:
- The OCR engine gets images to recognize. Depending on the recognition mode, the engine renders PDF pages or extracts images from pages. The engine can also recognize images that you pass directly. If you specify regions, the engine crops images to the regions.
- If the DocTrOcrProviderOptions.DetectPageOrientation property is
true, the provider detects whether an image is rotated by90,180, or270degrees and straightens the image. - The text detection model finds image areas that contain words.
- The text recognition model reads text in each area and calculates recognition confidence.
- The provider builds text lines and text fragments from recognized words.
- For PDF documents, the OCR engine converts text bounds from image pixels to page coordinates. The engine returns recognition results.
A custom OCR provider replaces steps 2–5 with its own recognition logic.
Supported Languages and Characters
The built-in text recognition model recognizes the following characters:
- Digits (0–9)
- Latin letters (a–z and A–Z)
- Accented letters à, â, é, è, ê, ë, î, ï, ô, ù, û, ü, and ç (lowercase and uppercase)
- Punctuation marks and symbols from the ASCII character set
- The degree sign (°) and currency symbols ($, £, €, ¥, ¢, and ฿)
The built-in model alphabet covers English text and French text (except for the letters æ, œ, and ÿ). The model returns only characters from the alphabet. The model may misrecognize letters outside the alphabet in text from other languages (for example, ä and ß in German or ñ in Spanish). The model does not recognize text in non-Latin scripts (for example, Cyrillic, Greek, or Chinese text).
To recognize characters that the built-in model does not support, assign a custom text recognition model to the DocTrOcrProviderOptions.RecognitionModel property.
Install the OCR Library
Install the DevExpress.Docs.Ocr NuGet package:
dotnet add package DevExpress.Docs.Ocr
OCR API types are in the DevExpress.Docs.Ocr namespace.
Recognize Text in a PDF Document
Follow the steps below to recognize text in a PDF document:
- Create a DocTrOcrProvider object. This built-in OCR provider uses deep learning models to detect and recognize text.
- Pass the provider to the
OcrEngineconstructor to create an OcrEngine object. - Load a PDF document to a PdfDocument object and pass the document to the OcrEngine.RecognizePdfDocument(document, options, cancellationToken, pageIndices) method.
The RecognizePdfDocument method returns a PdfDocumentRecognitionResult object. The PdfDocumentRecognitionResult.PageResults collection contains one item for each recognized page. The RecognizePdfDocument method does not modify the document.
The following code snippet recognizes text on all pages of a PDF document and displays recognized text in the console:
using System;
using System.IO;
using DevExpress.Docs.Ocr;
using DevExpress.Docs.Pdf;
using PdfDocument document = new PdfDocument(File.OpenRead("Document.pdf"));
using DocTrOcrProvider provider = new DocTrOcrProvider();
OcrEngine engine = new OcrEngine(provider);
PdfDocumentRecognitionResult result = engine.RecognizePdfDocument(document);
foreach (PdfPageRecognitionResult pageResult in result.PageResults)
{
Console.WriteLine($"Page {pageResult.PageIndex + 1}:");
foreach (PdfTextFragment fragment in pageResult.TextFragments)
Console.WriteLine(fragment.Text);
}
To recognize text on specific pages, pass page indexes as the pageIndices parameter.
The DocTrOcrProvider constructor loads recognition models into memory. Create a single provider and reuse it to recognize multiple documents. The OcrEngine object does not dispose the provider. To release the models, dispose the provider when you no longer need it.
Select a Recognition Mode
Use the PdfDocumentRecognitionOptions.RecognitionMode property to specify which images the OCR engine recognizes:
| Mode | Description |
|---|---|
| RenderedPage | The OCR engine renders each page to an image and recognizes text in the page image. |
| EmbeddedImages | The OCR engine recognizes text in images on each page and does not render the page. |
In RenderedPage mode, the engine recognizes all text that the rendered page displays. Use the PdfDocumentRecognitionOptions.Resolution property to specify the resolution of rendered page images in DPI. The Resolution property applies to RenderedPage mode.
Use EmbeddedImages mode for scanned documents where page content consists of images. The engine recognizes each image at the original image resolution and ignores other page content.
The following code snippet recognizes text in images embedded in a scanned PDF document:
using System;
using System.IO;
using DevExpress.Docs.Ocr;
using DevExpress.Docs.Pdf;
using PdfDocument document = new PdfDocument(File.OpenRead("Document.pdf"));
using DocTrOcrProvider provider = new DocTrOcrProvider();
OcrEngine engine = new OcrEngine(provider);
PdfDocumentRecognitionOptions options = new PdfDocumentRecognitionOptions()
{
RecognitionMode = PdfDocumentRecognitionMode.EmbeddedImages
};
PdfDocumentRecognitionResult result = engine.RecognizePdfDocument(document, options);
foreach (PdfPageRecognitionResult pageResult in result.PageResults)
{
Console.WriteLine($"Page {pageResult.PageIndex + 1}:");
foreach (PdfTextFragment fragment in pageResult.TextFragments)
Console.WriteLine(fragment.Text);
}
Recognize Text in Page Regions
To recognize text in specific page areas, assign rectangles to the PdfDocumentRecognitionOptions.Regions property. Specify rectangles in the page coordinate system (the origin is at the bottom-left corner of the page, and units are points). The engine applies the regions to each recognized page.
If you specify regions, the PdfPageRecognitionResult.RegionGroups collection contains one PdfRegionGroup object for each region, in the same order as rectangles in the Regions collection. The PdfRegionGroup.TextFragments collection contains text fragments recognized in the region. The PdfPageRecognitionResult.TextFragments collection contains text fragments from all regions.
Call the PdfRegionGroup.GetText() method to get text recognized in the region.
If you do not specify regions, the RegionGroups property gets null.
The following code snippet recognizes text in the top 100 points of the first document page:
using System;
using System.Drawing;
using System.IO;
using System.Threading;
using DevExpress.Docs.Ocr;
using DevExpress.Docs.Pdf;
using PdfDocument document = new PdfDocument(File.OpenRead("Document.pdf"));
using DocTrOcrProvider provider = new DocTrOcrProvider();
OcrEngine engine = new OcrEngine(provider);
RectangleF cropBox = document.Pages[0].CropBox;
PdfDocumentRecognitionOptions options = new PdfDocumentRecognitionOptions()
{
Regions = new[] { new RectangleF(cropBox.X, cropBox.Y + cropBox.Height - 100, cropBox.Width, 100) }
};
PdfDocumentRecognitionResult result =
engine.RecognizePdfDocument(document, options, CancellationToken.None, new[] { 0 });
foreach (PdfRegionGroup regionGroup in result.PageResults[0].RegionGroups)
{
foreach (PdfTextFragment fragment in regionGroup.TextFragments)
Console.WriteLine(fragment.Text);
}
Process Recognition Results
The built-in OCR provider groups recognized words into text lines and groups lines into text fragments (blocks of adjacent text). Text fragments are in reading order. Use PdfTextFragment.Lines and PdfTextFragment.Words properties to access lines and words in a text fragment. The PdfTextLine.Words property gets words in a line.
PdfTextFragment, PdfTextLine, and PdfTextWord classes derive from the PdfTextElement class. Use the following properties to get recognized text, text bounds, and recognition confidence:
| Property | Description |
|---|---|
| PdfTextElement.Text | Recognized text. Text of a fragment contains text of all lines separated by line breaks. Text of a line contains text of all words separated by spaces. |
| PdfTextElement.Bounds | The bounding rectangle in the page coordinate system (the origin is at the bottom-left corner of the page, and units are points). The Regions property uses the same coordinate system. |
| PdfTextElement.Confidence | Recognition confidence from 0 to 1, or null if the OCR provider does not calculate confidence. For a text line or fragment, DocTrOcrProvider sets the lowest confidence of words in the line or fragment. |
The PdfTextFragment.TextRotationAngle property gets the clockwise rotation angle of fragment text in degrees, relative to the unrotated page. If the DetectPageOrientation property is false or the provider cannot determine the orientation, the TextRotationAngle property gets null.
The following code snippet displays text, bounds, and confidence values of words recognized with confidence below 0.8:
using System;
using System.IO;
using DevExpress.Docs.Ocr;
using DevExpress.Docs.Pdf;
using PdfDocument document = new PdfDocument(File.OpenRead("Document.pdf"));
using DocTrOcrProvider provider = new DocTrOcrProvider();
OcrEngine engine = new OcrEngine(provider);
PdfDocumentRecognitionResult result = engine.RecognizePdfDocument(document);
foreach (PdfPageRecognitionResult pageResult in result.PageResults)
{
foreach (PdfTextFragment fragment in pageResult.TextFragments)
{
foreach (PdfTextWord word in fragment.Words)
{
if (word.Confidence < 0.8f)
Console.WriteLine($"Page {pageResult.PageIndex + 1}, {word.Bounds}: {word.Text} ({word.Confidence:P0})");
}
}
}
Recognize Text in Images
Call the OcrEngine.RecognizeImage(image, options, cancellationToken) method to recognize text in a DXImage object. The RecognizeImage method returns an ImageRecognitionResult object.
To recognize text in multiple images, call the OcrEngine.RecognizeImages(images, options, cancellationToken) method. The RecognizeImages method returns an ImageRecognitionResults object. The ImageRecognitionResults.ImageResults collection contains one ImageRecognitionResult object for each image.
Image recognition results have the same structure as PDF recognition results (ImageTextFragment, ImageTextLine, and ImageTextWord objects). The ImageTextElement.Bounds property gets the bounding rectangle in image pixels, with the origin in the top-left corner of the image.
To recognize text in image areas, assign rectangles in pixels to the ImageRecognitionOptions.Regions property and pass the options to the RecognizeImage or RecognizeImages method.
The following code snippet recognizes text in a PNG image and displays text fragments and fragment bounds:
using System;
using System.IO;
using DevExpress.Docs.Ocr;
using DevExpress.Drawing;
using DXImage image = DXImage.FromStream(File.OpenRead("Document.png"));
using DocTrOcrProvider provider = new DocTrOcrProvider();
OcrEngine engine = new OcrEngine(provider);
ImageRecognitionResults results = engine.RecognizeImages(new[] { image });
foreach (ImageRecognitionResult imageResult in results.ImageResults)
{
foreach (ImageTextFragment fragment in imageResult.TextFragments)
Console.WriteLine($"{fragment.Bounds}: {fragment.Text}");
}
Create Searchable PDF Files from Scanned Images
Call the following methods to create a searchable PDF document from recognized images:
- ImageRecognitionResult.ToPdf(options) creates a document with a single page.
- ImageRecognitionResults.ToPdf(options) creates a document with one page for each recognized image.
- ImageRecognitionResult.ToPdfPage(options) creates a page that you can add to an existing document.
Each page contains the image and recognized text as invisible text over the image. PDF viewers do not display the text but can search and select it.
Pass a PdfGenerationOptions object to the ToPdf or ToPdfPage method to configure generated pages:
- PdfGenerationOptions.PageSize
- Specifies the page size in points. If the
PageSizeproperty isnull, the page size matches the image size. If the image is larger than the page, the API scales the image down proportionally to fit the page. - PdfGenerationOptions.AdjustContentRotation
- Specifies whether the API rotates pages so that recognized text is upright. The API uses text rotation angles of recognized text fragments (TextRotationAngle).
- PdfGenerationOptions.Font
- Specifies the font of searchable text.
The following code snippet recognizes text in PNG images from the Images folder and saves the images and recognized text to a searchable PDF file with A4 pages:
using System.IO;
using System.Linq;
using DevExpress.Docs.Ocr;
using DevExpress.Docs.Pdf;
using DevExpress.Drawing;
using DevExpress.Drawing.Printing;
DXImage[] images = Directory.GetFiles("Images", "*.png")
.Select(filePath => DXImage.FromStream(File.OpenRead(filePath)))
.ToArray();
using DocTrOcrProvider provider = new DocTrOcrProvider();
OcrEngine engine = new OcrEngine(provider);
ImageRecognitionResults results = engine.RecognizeImages(images);
using PdfDocument document = results.ToPdf(new PdfGenerationOptions(DXPaperKind.A4));
Directory.CreateDirectory("output");
using FileStream outputStream = File.Create(Path.Combine("output", "Document.pdf"));
document.Save(outputStream);
foreach (DXImage image in images)
image.Dispose();
Configure the OCR Provider
To configure the built-in OCR provider, pass a DocTrOcrProviderOptions object to the DocTrOcrProvider(options) constructor:
- DocTrOcrProviderOptions.ThreadCount
- Specifies the number of threads that each model uses to process an image. If the value is
0, ONNX Runtime selects the number of threads. - DocTrOcrProviderOptions.DetectPageOrientation
- Specifies whether the provider detects images rotated by
90,180, or270degrees and straightens them before recognition. Bounds of recognized text refer to the original image. If all pages are upright, set theDetectPageOrientationproperty tofalseto skip orientation detection.
The following code snippet configures the OCR provider (4 threads, no page orientation detection) and displays text recognized on the first page of a PDF document:
using System;
using System.IO;
using System.Threading;
using DevExpress.Docs.Ocr;
using DevExpress.Docs.Pdf;
using PdfDocument document = new PdfDocument(File.OpenRead("Document.pdf"));
DocTrOcrProviderOptions providerOptions = new DocTrOcrProviderOptions()
{
ThreadCount = 4,
DetectPageOrientation = false
};
using DocTrOcrProvider provider = new DocTrOcrProvider(providerOptions);
OcrEngine engine = new OcrEngine(provider);
PdfDocumentRecognitionResult result =
engine.RecognizePdfDocument(document, null, CancellationToken.None, new[] { 0 });
foreach (PdfTextFragment fragment in result.PageResults[0].TextFragments)
Console.WriteLine(fragment.Text);
Recognize Text in Multiple Threads
A DocTrOcrProvider instance is thread-safe. Multiple threads can share a single provider and call recognition methods simultaneously (for example, to recognize multiple documents in parallel).
The OcrEngine object does not store recognition state between calls and does not synchronize calls to the OCR provider. Multiple threads can share an OcrEngine object if the OCR provider is thread-safe. If you implement a custom OCR provider and share it between threads, ensure that the custom provider is thread-safe.
The DocTrOcrProviderOptions.ThreadCount property specifies the number of threads that each model uses to process a single image. To recognize multiple documents simultaneously, process the documents in separate threads.
The DocTrOcrProvider.Dispose method waits until running recognition operations complete and then releases the models. After you dispose the provider, recognition methods throw an ObjectDisposedException.
The following code snippet recognizes text in PDF files from the Documents folder in parallel and saves recognized text to text files in the output folder:
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using DevExpress.Docs.Ocr;
using DevExpress.Docs.Pdf;
Directory.CreateDirectory("output");
using DocTrOcrProvider provider = new DocTrOcrProvider();
OcrEngine engine = new OcrEngine(provider);
Parallel.ForEach(Directory.GetFiles("Documents", "*.pdf"), filePath =>
{
using PdfDocument document = new PdfDocument(File.OpenRead(filePath));
PdfDocumentRecognitionResult result = engine.RecognizePdfDocument(document);
string text = string.Join(Environment.NewLine,
result.PageResults.SelectMany(page => page.TextFragments).Select(fragment => fragment.Text));
File.WriteAllText(Path.Combine("output", Path.GetFileNameWithoutExtension(filePath) + ".txt"), text);
});
Use Custom Models
To recognize characters that the built-in recognition model does not support, use custom models. The following properties accept custom models:
- DocTrOcrProviderOptions.DetectionModel (a text detection model)
- DocTrOcrProviderOptions.RecognitionModel (a text recognition model)
- DocTrOcrProviderOptions.PageOrientationModel (a page orientation model)
A custom model is a docTR model in ONNX format with a single input and a single output. Pass model data (a byte array or a stream) and model input settings to the constructor of the DocTrCustomModel or DocTrCustomRecognitionModel class:
- Input image height and width in pixels.
- Normalization mean and standard deviation values. Each array contains three values for red, green, and blue channels, as fractions from
0to1. - For a recognition model, the alphabet (characters that the model recognizes) and the model architecture (Crnn or Parseq).
Model publishers usually distribute these settings in a JSON file together with the ONNX model file.
Implement a Custom OCR Provider
To use another OCR engine for text recognition, implement the IOcrProvider interface and pass the implementation to the OcrEngine constructor.
The IOcrProvider.RecognizeText(image, cancellationToken) method receives an image and returns a list of ImageTextFragment objects with bounds in image pixels (the origin is in the top-left corner of the image). Call the following ImageTextFragmentFactory methods to create text fragments, lines, and words:
- ImageTextFragmentFactory.CreateWord(bounds, text, confidence)
- ImageTextFragmentFactory.CreateLineFromWords(bounds, words, confidence) or ImageTextFragmentFactory.CreateLineFromText(bounds, text, confidence) (if the OCR engine does not recognize individual words)
- ImageTextFragmentFactory.CreateFragmentFromLines(bounds, lines, confidence, textRotationAngle) or ImageTextFragmentFactory.CreateFragmentFromText(bounds, text, confidence, textRotationAngle) (if the OCR engine does not recognize individual lines)
Confidence values must be from 0 to 1, or null. The factory methods do not calculate line or fragment confidence from word confidence values. If the OCR engine determines text rotation, pass the clockwise rotation angle in degrees as the textRotationAngle parameter.
The OcrEngine object crops images to regions, converts text bounds to page coordinates, and builds recognition results. The OcrEngine object does not dispose the OCR provider.
The following code snippet implements an OCR provider that runs the PaddleOCR engine and displays text recognized on the first page of a PDF document. PaddleOCR recognizes text lines and does not return individual words. The provider creates a text fragment with a single line for each recognized text region.
The provider uses the following third-party NuGet packages:
- Sdcb.PaddleOCR - a .NET wrapper for PaddleOCR from the PaddleSharp project.
- Sdcb.PaddleOCR.Models.Local and Sdcb.PaddleOCR.Models.LocalV5 - built-in PaddleOCR models.
- Sdcb.PaddleInference.runtime.win64.mkl - the native Paddle Inference runtime for Windows x64.
- OpenCvSharp4.runtime.win - the native runtime of OpenCvSharp, a .NET wrapper for OpenCV. The provider uses OpenCvSharp to convert images to the format that PaddleOCR accepts.
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Threading;
using DevExpress.Docs.Ocr;
using DevExpress.Docs.Pdf;
using DevExpress.Drawing;
using OpenCvSharp;
using Sdcb.PaddleOCR;
using Sdcb.PaddleOCR.Models.Local;
using PdfDocument document = new PdfDocument(File.OpenRead("Document.pdf"));
using PaddleOcrProvider provider = new PaddleOcrProvider();
OcrEngine engine = new OcrEngine(provider);
PdfDocumentRecognitionResult result =
engine.RecognizePdfDocument(document, null, CancellationToken.None, new[] { 0 });
foreach (PdfTextFragment fragment in result.PageResults[0].TextFragments)
Console.WriteLine(fragment.Text);
sealed class PaddleOcrProvider : IOcrProvider
{
readonly PaddleOcrAll ocr = new PaddleOcrAll(LocalFullModels.LatinV5)
{
AllowRotateDetection = false,
Enable180Classification = false
};
readonly ImageTextFragmentFactory factory = new ImageTextFragmentFactory();
public IList<ImageTextFragment> RecognizeText(DXImage image, CancellationToken cancellationToken = default)
{
// Convert the DXImage to an OpenCV image.
using MemoryStream stream = new MemoryStream();
image.Save(stream, DXImageFormat.Png);
using Mat source = Cv2.ImDecode(stream.ToArray(), ImreadModes.Color);
PaddleOcrResult result = ocr.Run(source);
List<ImageTextFragment> fragments = new List<ImageTextFragment>();
foreach (PaddleOcrResultRegion region in result.Regions)
{
if (string.IsNullOrWhiteSpace(region.Text))
continue;
// Clip text bounds to the image.
Rect rect = region.Rect.BoundingRect();
float left = Math.Clamp(rect.X, 0, image.Width - 1);
float top = Math.Clamp(rect.Y, 0, image.Height - 1);
RectangleF bounds = new RectangleF(left, top,
Math.Clamp(rect.Width, 1, image.Width - left),
Math.Clamp(rect.Height, 1, image.Height - top));
float? confidence = float.IsNaN(region.Score) ? null : Math.Clamp(region.Score, 0f, 1f);
ImageTextLine line = factory.CreateLineFromText(bounds, region.Text, confidence);
fragments.Add(factory.CreateFragmentFromLines(bounds, new[] { line }, confidence));
}
return fragments;
}
public void Dispose()
{
ocr.Dispose();
}
}
Cancel Recognition
Pass a CancellationToken to the RecognizePdfDocument, RecognizeImage, or RecognizeImages method to cancel recognition. If you cancel recognition, the API throws an OperationCanceledException.