Export OCR Results to JSON - C# .NET Core

This tutorial shows how to run OCR an image and export the OCR results to JSON in a C# .NET Core application using the LEADTOOLS SDK.

Overview  
Summary This tutorial covers how to save OCR results to a JSON file in a C# .NET Core Console application.
Completion Time 30 minutes
Visual Studio Project Download tutorial project (2 KB)
Platform C# .NET Core Console Application
IDE Visual Studio 2017, 2019
Development License Download LEADTOOLS
Try it in another language

Required Knowledge

Get familiar with the basic steps of creating a project by reviewing the Add References and Set a License tutorial, before working on the Export OCR Results to JSON - C# .NET Core tutorial.

Create the Project and Add LEADTOOLS References

Start with a copy of the project created in the Add References and Set a License tutorial. If you do not have that project, follow the steps in that tutorial to create it.

The references needed depend upon the purpose of the project. References can be added via NuGet packages.

This tutorial requires the following NuGet packages:

For a complete list of which DLL files are required for your application, refer to Files to be Included With Your Application.

Set the License File

The License unlocks the features needed for the project. It must be set before any toolkit function is called. For details, including tutorials for different platforms, refer to Setting a Runtime License.

There are two types of runtime licenses:

Note

Adding LEADTOOLS NuGet references and setting a license are covered in more detail in the Add References and Set a License tutorial.

Initialize the OcrEngine and Set PDF Options

With the project created, the references added, and the license set, coding can begin.

In the Solution Explorer, open Program.cs. Add the following statements to the using block at the top of Program.cs.

C#
using System; 
using System.IO; 
using System.Collections.Generic; 
using Newtonsoft.Json; 
using Leadtools; 
using Leadtools.Document.Writer; 
using Leadtools.Ocr; 

Inside the Main() method, below the set license code, create two new strings named input and outputDir. Set the input string value to the document/image file path. Set the outputDir string value to the file path to the directory you wish to export the JSON file to. For the purposes of this tutorial, the sample document in the following file path is used: C:\LEADTOOLS21\Resources\Images\leadtools.pdf

C#
static void Main(string[] args) 
{ 
   if (!SetLicense()) 
      Console.WriteLine("Error setting license"); 
   else 
      Console.WriteLine("License file set successfully"); 
 
   string input = @"C:\LEADTOOLS21\Resources\Images\leadtools.pdf"; 
   string outputDir = @"C:\LEADTOOLS21\Resources\Images\out"; 
 
   IOcrEngine ocrEngine = InitOcrEngine(); 
   OCRandSaveResults(ocrEngine, input, outputDir); 
} 

Add a new method to the Program class named InitOcrEngine(). Call the InitOcrEngine() method inside the Main() method below the string variables, as shown above. Add the code below to the OCR() method to initialize the IOcrEngine and set the PdfDocumentOptions.

C#
static IOcrEngine InitOcrEngine() 
{ 
   // Initialize OCR engine 
   IOcrEngine ocrEngine = OcrEngineManager.CreateEngine(OcrEngineType.LEAD); 
   ocrEngine.Startup(null, null, null, @"C:\LEADTOOLS21\Bin\Common\OcrLEADRuntime"); 
 
   // Set the PDF output options to overlay the original image over the recognized text 
   PdfDocumentOptions pdfoptions = (PdfDocumentOptions)ocrEngine.DocumentWriterInstance.GetOptions(DocumentFormat.Pdf); 
   pdfoptions.ImageOverText = true; 
   ocrEngine.DocumentWriterInstance.SetOptions(DocumentFormat.Pdf, pdfoptions); 
 
   return ocrEngine; 
} 

Add the Text Recognition and Export to JSON Code

Create a new method in the Program class named OCRandSaveResults(IOcrEngine ocrEngine, string file, string outputDirectory). Call the OCRandSaveResults() method inside the Main() method below the InitOcrEngine() method, as shown in the previous section. Add the code below to the new method to run text recognition and export the OCR results to a JSON file.

C#
static void OCRandSaveResults(IOcrEngine ocrEngine, string file, string outputDirectory) 
{ 
   // Get the filename and create the output directory 
   string fileName = Path.GetFileNameWithoutExtension(file); 
   string outputDir = Path.Combine(outputDirectory, $"{fileName}-results"); 
 
   if (Directory.Exists(outputDir)) 
      Directory.Delete(outputDir, true); 
 
   Directory.CreateDirectory(outputDir); 
 
   // Create the OCR Document 
   using (IOcrDocument ocrDocument = ocrEngine.DocumentManager.CreateDocument()) 
   { 
      // Add the input file from first to last page 
      ocrDocument.Pages.AddPages(file, 1, -1, null); 
 
      // Auto rotate each page 
      ocrDocument.Pages.AutoPreprocess(OcrAutoPreprocessPageCommand.Rotate, null); 
 
      // Recognize the entire document 
      ocrDocument.Pages.Recognize(null); 
 
      // Loop through the pages, create the JSON of each page with the recognized words and save all pages to a file at the end 
      List<OCRResults> results = new List<OCRResults>(); 
 
      foreach (var ocrPage in ocrDocument.Pages) 
      { 
         IOcrPageCharacters pageChars = ocrPage.GetRecognizedCharacters(); 
 
         foreach (IOcrZoneCharacters zoneChars in pageChars) 
         { 
            OCRResults oCRResults = new OCRResults 
            { 
               PageNumber = ocrDocument.Pages.IndexOf(ocrPage) + 1, 
               ZoneNumber = pageChars.IndexOf(zoneChars) + 1, 
               Words = zoneChars.GetWords() 
            }; 
            results.Add(oCRResults); 
         } 
      } 
      // Save the recognized words to JSON 
      var json = JsonConvert.SerializeObject(results, Formatting.Indented); 
      var jsonPath = Path.Combine(outputDir, $"{fileName}-words.json"); 
      File.WriteAllText(jsonPath, json); 
 
      // Save the recognized PDF to a file 
      var outputPath = Path.Combine(outputDir, $"{fileName}-recognized.pdf"); 
      ocrDocument.Save(outputPath, DocumentFormat.Pdf, null); 
   } 
} 

Add a Custom OCRResults Class

At the bottom of Program.cs, add a new custom class named OCRResults. Add the code below to the custom class to store the OCR results.

C#
// Custom class to store only the OCR Results 
class OCRResults 
{ 
   public OCRResults() { } 
   public int PageNumber { get; set; } 
   public int ZoneNumber { get; set; } 
   public IList<OcrWord> Words { get; set; } 
} 

Run the Project

Run the project by pressing F5, or by selecting Debug -> Start Debugging.

If the steps were followed correctly, the console appears and the application will OCR the given file and create a JSON file containing the recognition results in the specified output directory.

Download the resulting JSON here.

Wrap-up

This tutorial showed how to run OCR on a document and export the results to JSON. Also, it covered how to use the IOcrEngine, IOcrDocument, IOcrPageCharacters, and IOcrZoneCharacters interfaces.

See Also

Help Version 21.0.2021.6.17
Products | Support | Contact Us | Intellectual Property Notices
© 1991-2021 LEAD Technologies, Inc. All Rights Reserved.