How to Work with the Aspose.OCR FOSS Core API in .NET

How to Work with the Aspose.OCR FOSS Core API in .NET

Aspose.OCR FOSS for .NET recognizes text in raster images and PDF documents through a small core API: AsposeOcr, OcrInput, OcrOutput, and RecognitionResult. This guide walks through installing the package and using that core API end to end.

Step-by-Step Guide

Step 1: Install the Package

dotnet add package Aspose.OCR.FOSS

Step 2: Import the Namespace

Add the Aspose.OCR namespace to any source file that calls AsposeOcr, OcrInput, or RecognitionResult:

using Aspose.OCR;

This single namespace exposes AsposeOcr, OcrInput, OcrOutput, InputType, and RecognitionResult.


Step 3: Build an OcrInput and Recognize an Image

Construct an AsposeOcr, build an OcrInput with InputType.SingleImage, queue a file with OcrInput.Add(), and call AsposeOcr.Recognize().

var api = new AsposeOcr();
using var input = new OcrInput(InputType.SingleImage);
input.Add("scan.png");
RecognitionResult result = api.Recognize(input)[0];
Console.WriteLine(result.RecognitionText);

Step 4: Read Individual Lines and Bounding Boxes

Each RecognitionResult.LinesResult entry in RecognitionLinesResult holds one line’s text (TextInLine) and its pixel-coordinate bounding box (Line).

foreach (RecognitionResult.LinesResult line in result.RecognitionLinesResult)
{
    System.Drawing.Rectangle bounds = line.Line;
    Console.WriteLine($"x={bounds.X}, y={bounds.Y}: {line.TextInLine}");
}

Step 5: Recognize a Multi-Page PDF

For InputType.PDF, AsposeOcr.Recognize() returns one RecognitionResult per page, in source order.

using var pdfInput = new OcrInput(InputType.PDF);
pdfInput.Add("document.pdf");
OcrOutput output = api.Recognize(pdfInput);

foreach (RecognitionResult page in output)
{
    Console.WriteLine(page.RecognitionText);
}

Common Issues and Fixes

NotSupportedException when calling Recognize(). The OcrInput was constructed with an input type other than InputType.SingleImage or InputType.PDF. Only those two input types are supported.

FileNotFoundException when calling Recognize(). A path added via OcrInput.Add() does not exist on disk. Validate the path before calling Add().

ArgumentNullException when calling Recognize(). null was passed instead of an OcrInput instance. Always construct an OcrInput first.

Empty RecognitionLinesResult. No text line was detected — confirm the source image contains legible, non-rotated Latin-script text.

Frequently Asked Questions

Does OcrOutput preserve file order?

Yes. OcrOutput is a list of RecognitionResult, one per image (or per PDF page), in the order the files were added via OcrInput.Add().

Do I need to dispose OcrInput?

Yes — OcrInput implements IDisposable. Use a using statement or call Dispose() explicitly once recognition is complete.

Can I process both images and PDFs in the same OcrInput?

No — each OcrInput is constructed with a single InputType (SingleImage or PDF) and only accepts files of that type.

See Also