Export OCR Results to JSON - Console C#

This tutorial shows how to create a C# Windows Console application that uses the LEADTOOLS SDK to save OCR results to JSON.

Overview  
Summary This tutorial covers how to use LEADTOOLS OCR SDK technology in a C# Windows Console application
Completion Time 30 minutes
Visual Studio Project Download tutorial project (3 KB)
Platform C# Windows Console Application
IDE Visual Studio 2017, 2019
Development License Download LEADTOOLS
Try it in another language
  • C#: .NET Framework (Console)
  • Java: Java

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 - Console C# tutorial.

Create the Project and Add the LEADTOOLS References

In Visual Studio, create a new C# Windows Console project, and add the following necessary LEADTOOLS references.

The references needed depend upon the purpose of the project. References can be added by one or the other of the following two methods (but not both). For this project, the following references are needed:

If using NuGet references, this tutorial requires the following NuGet packages:

If local DLL references are used, the following DLLs are needed. The DLLs are located at <INSTALL_DIR>\LEADTOOLS21\Bin\Dotnet4\x64:

For a complete list of which Codec DLLs are required for specific formats, refer to File Format Support.

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 and local 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 Solution Explorer, open Program.cs. Add statements to the using block at the top:

C#
// Using block at the top 
using System; 
using System.IO; 
using System.Collections.Generic; 
using Newtonsoft.Json; 
using Leadtools; 
using Leadtools.Document.Writer; 
using Leadtools.Ocr; 

Add a new method called InitOcrEngine() to return the IOcrEngine and call it inside the Main method after the SetLicense() method call. Add the below code to initialize the IOcrEngine and set the PdfDocumentOptions.

C#
static void Main(string[] args) 
{ 
   string file = @"C:\LEADTOOLS21\Resources\Images\leadtools.pdf"; 
   string outputDirectory = @"C:\LEADTOOLS21\Resources\Images\out"; 
   SetLicense(); 
   IOcrEngine ocrEngine = InitOcrEngine(); 
} 
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 called OCRandSaveResults(string file) and call it in the Main method after IOcrEngine ocrEngine = InitOcrEngine(); line.

C#
static void Main(string[] args) 
{ 
   string file = @"C:\LEADTOOLS21\Resources\Images\leadtools.pdf"; 
   string outputDirectory = @"C:\LEADTOOLS21\Resources\Images\out"; 
   SetLicense(); 
   IOcrEngine ocrEngine = InitOcrEngine(); 
   OCRandSaveResults(ocrEngine, file, outputDirectory); 
} 
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

Add the below class to the bottom of the namespace.

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 application will OCR a PDF document and create a JSON containing the recognition results in the specified output directory. This tutorial used this sample PDF.

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 and IOcrDocument interfaces.

See Also

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