Take the following steps to create and run a program that shows how to add/delete and paint the zones in an OCR document. Remember, the purpose of the tutorials is to provide you with a quick and easy way to generate an OCR program.
Start Visual Studio
Choose File->New->Project from the menu.
In the New Project dialog box, choose either "Visual C# Projects" or "VB Projects" in the Projects Type List, and choose "Windows Application" or "Windows Forms Application" depending on your Visual Studio version from the Templates List.
Type the project name as "OcrTutorial1" in the Project Name field, and then choose OK. If desired, type a new location for your project or select a directory using the Browse button, and then choose OK.
In the "Solution Explorer" window, right-click on the "References" folder, and select "Add Reference..." from the context menu. In the "Add Reference" dialog box, select the ".NET" tab and browse to LEADTOOLS For .NET "<LEADTOOLS_INSTALLDIR>\Bin\DotNet4\Win32" folder and select the following DLLs:
Note: The Leadtools.Codecs.*.dll references added are for the BMP, JPG, CMP, TIF and FAX image file formats. Add any additional file format codec DLL if required in your application.
Switch to Form1 code view (Right-click Form1 in the solution explorer then select View Code) and add the following lines at the beginning of the file after any using or Imports section if there are any:
using Leadtools;using Leadtools.Codecs;using Leadtools.Drawing;using Leadtools.Controls;using Leadtools.Forms.Common;using Leadtools.Ocr;using Leadtools.Document.Writer;
Imports LeadtoolsImports Leadtools.CodecsImports Leadtools.DrawingImports Leadtools.ControlsImports Leadtools.Forms.CommonImports Leadtools.OcrImports Leadtools.Document.Writer
Add the following private variables to the Form1 class:
private ImageViewer _imageViewer;private IOcrEngine _ocrEngine;private IOcrPage _ocrPage;
Private _imageViewer As ImageViewerPrivate _ocrEngine As IOcrEnginePrivate _ocrPage As IOcrPage
Override Form1OnLoad and add the following code:
protected override void OnLoad(EventArgs e){string MY_LICENSE_FILE = @"C:\LEADTOOLS 20\Support\Common\License\leadtools.lic";string MY_DEVELOPER_KEY = System.IO.File.ReadAllText(@"C:\LEADTOOLS 20\Support\Common\License\leadtools.lic.key");RasterSupport.SetLicense(MY_LICENSE_FILE, MY_DEVELOPER_KEY);// Add the image viewer to the form_imageViewer = new ImageViewer();_imageViewer.Dock = DockStyle.Fill;Controls.Add(_imageViewer);_imageViewer.BringToFront();// Show images using their true size_imageViewer.UseDpi = true;// Add ability to pan/zoom with the mouse, but disable double-click-size-mode support because we will use our ownImageViewerPanZoomInteractiveMode panZoomMode = new ImageViewerPanZoomInteractiveMode();panZoomMode.DoubleTapSizeMode = ControlSizeMode.None;_imageViewer.InteractiveModes.Add(panZoomMode);// Initialize the OCR engine_ocrEngine = OcrEngineManager.CreateEngine(OcrEngineType.LEAD, false);// Start up the engine_ocrEngine.Startup(null, null, null, @"C:\LEADTOOLS 20\Bin\Common\OcrLEADRuntime");// Create the OCR page from an imagestring fileName = @"C:\Users\Public\Documents\LEADTOOLS Images\Ocr1.tif";RasterImage rasterImage = _ocrEngine.RasterCodecsInstance.Load(fileName, 1);_ocrPage = _ocrEngine.CreatePage(rasterImage, OcrImageSharingMode.AutoDispose);// Auto-zone this page_ocrPage.AutoZone(null);// Add an extra zone, this is our user-defined oneOcrZone zone = new OcrZone();zone.Name = "Custom zone";zone.ZoneType = OcrZoneType.Text;zone.Bounds = new LeadRect(10, 10, _ocrPage.Width - 20, 100);_ocrPage.Zones.Add(zone);// Show this image in the viewer_imageViewer.Image = _ocrPage.GetRasterImage();Text = "Right-click on any zone to remove it from the page, double-click anywhere to save the result as a PDF file";// Hook to the events we will use_imageViewer.PostRender += _imageViewer_PostRender;_imageViewer.MouseDown += _imageViewer_MouseDown;_imageViewer.MouseDoubleClick += _imageViewer_MouseDoubleClick;base.OnLoad(e);}
Protected Overrides Sub OnLoad(e As EventArgs)' Requires a license file that unlocks 1D barcode read functionality.Dim MY_LICENSE_FILE As String = "C:\LEADTOOLS 20\Support\Common\License\leadtools.lic"Dim MY_DEVELOPER_KEY As String = System.IO.File.ReadAllText("C:\LEADTOOLS 20\Support\Common\License\leadtools.lic.key")RasterSupport.SetLicense(MY_LICENSE_FILE, MY_DEVELOPER_KEY)' Add the image viewer to the form_imageViewer = New ImageViewer()_imageViewer.Dock = DockStyle.FillControls.Add(_imageViewer)_imageViewer.BringToFront()' Show images using their true size_imageViewer.UseDpi = True' Add ability to pan/zoom with the mouse, but disable double-click-size-mode support because we will use our ownDim panZoomMode As New ImageViewerPanZoomInteractiveMode()panZoomMode.DoubleTapSizeMode = ControlSizeMode.None_imageViewer.InteractiveModes.Add(panZoomMode)' Initialize the OCR engine_ocrEngine = OcrEngineManager.CreateEngine(OcrEngineType.LEAD, False)' Start up the engine_ocrEngine.Startup(Nothing, Nothing, Nothing, "C:\LEADTOOLS 20\Bin\Common\OcrLEADRuntime")' Create the OCR page from an imageDim fileName As String = "C:\Users\Public\Documents\LEADTOOLS Images\Ocr1.tif"Dim rasterImage As RasterImage = _ocrEngine.RasterCodecsInstance.Load(fileName, 1)_ocrPage = _ocrEngine.CreatePage(rasterImage, OcrImageSharingMode.AutoDispose)' Auto-zone this page_ocrPage.AutoZone(Nothing)' Add an extra zone, this is the user-defined oneDim zone As New OcrZone()zone.Name = "Custom zone"zone.ZoneType = OcrZoneType.Textzone.Bounds = New LeadRect(10, 10, _ocrPage.Width - 20, 100)_ocrPage.Zones.Add(zone)' Show this image in the viewer_imageViewer.Image = _ocrPage.GetRasterImage()Text = "Right-click on any zone to remove it from the page, double-click anywhere to save the result as a PDF file"' Hook to the events we will useAddHandler _imageViewer.PostRender, AddressOf _imageViewer_PostRenderAddHandler _imageViewer.MouseDown, AddressOf _imageViewer_MouseDownAddHandler _imageViewer.MouseDoubleClick, AddressOf _imageViewer_MouseDoubleClickMyBase.OnLoad(e)End Sub
Override Form1OnFormClosed and add the following code:
protected override void OnFormClosed(FormClosedEventArgs e){// Destroy the page_ocrPage.Dispose();// And the engine_ocrEngine.Dispose();base.OnFormClosed(e);}
Protected Overrides Sub OnFormClosed(e As FormClosedEventArgs)' Destroy the page_ocrPage.Dispose()' And the engine_ocrEngine.Dispose()MyBase.OnFormClosed(e)End Sub
Add the following code to handle the image viewer post render event. Draw our zones:
private void _imageViewer_PostRender(object sender, ImageViewerRenderEventArgs e){// Draw the zonesforeach (OcrZone zone in _ocrPage.Zones){// Get the zone boundaryLeadRect bounds = zone.Bounds;// Convert the bounds to what we see in the viewer// Note that this demo does not have rotation; otherwise, you need to use the four corner pointsbounds = _imageViewer.ConvertRect(null, ImageViewerCoordinateType.Image, ImageViewerCoordinateType.Control, bounds);// If this is our custom zone, draw its border with a red pen, else use a blue penif(zone.Name == "Custom zone")e.PaintEventArgs.Graphics.DrawRectangle(Pens.Red, bounds.X, bounds.Y, bounds.Width - 1, bounds.Height - 1);elsee.PaintEventArgs.Graphics.DrawRectangle(Pens.Blue, bounds.X, bounds.Y, bounds.Width - 1, bounds.Height - 1);}}
Private Sub _imageViewer_PostRender(sender As Object, e As ImageViewerRenderEventArgs)' Draw the zonesFor Each zone As OcrZone In _ocrPage.Zones' Get the zone boundaryDim zoneBounds As LeadRect = zone.Bounds' Convert the bounds to what we see in the viewer' Note that this demo does not have rotation; otherwise, you need to use the four corner pointsbounds = _imageViewer.ConvertRect(Nothing, ImageViewerCoordinateType.Image, ImageViewerCoordinateType.Control, bounds)' If this is our custom zone, draw its border with a red pen, else use a blue penIf zone.Name = "Custom zone" Thene.PaintEventArgs.Graphics.DrawRectangle(Pens.Red, bounds.X, bounds.Y, bounds.Width - 1, bounds.Height - 1)Elsee.PaintEventArgs.Graphics.DrawRectangle(Pens.Blue, bounds.X, bounds.Y, bounds.Width - 1, bounds.Height - 1)End IfNextEnd Sub
Add the following code to handle the viewer mouse down event. Delete zones:
private void _imageViewer_MouseDown(object sender, MouseEventArgs e){// Check if this is a right-button clickif (e.Button != MouseButtons.Right)return;// Convert the point from control to image coordinatesLeadPoint point = new LeadPoint(e.X, e.Y);point = _imageViewer.ConvertPoint(null, ImageViewerCoordinateType.Control, ImageViewerCoordinateType.Image, point);// Use the HitTestZone method to find the zone under the mouse buttonint zoneIndex = _ocrPage.HitTestZone(new LeadPoint(point.X, point.Y));if(zoneIndex != -1){// Remove this zone_ocrPage.Zones.RemoveAt(zoneIndex);// Re-paint the viewer to show the zones left_imageViewer.Invalidate();_imageViewer.Update();// If no zones are left, show a messageif(_ocrPage.Zones.Count == 0)MessageBox.Show(this, "No zones left in the page, saving this document to PDF is disabled now");}}
Private Sub _imageViewer_MouseDown(sender As Object, e As MouseEventArgs)' Check if this is a right-button clickIf e.Button <> MouseButtons.Right Then Return' Convert the point from control to image coordinatesDim point As New LeadPoint(e.X, e.Y)point = _imageViewer.ConvertPoint(Nothing, ImageViewerCoordinateType.Control, ImageViewerCoordinateType.Image, point)' Use the HitTestZone method to find the zone under the mouse buttonDim zoneIndex As Integer = _ocrPage.HitTestZone(New LeadPoint(point.X, point.Y))If zoneIndex <> -1 Then' Remove this zone_ocrPage.Zones.RemoveAt(zoneIndex)' Re-paint the viewer to show the zones left_imageViewer.Invalidate()_imageViewer.Update()' If no zones are left, show a messageIf _ocrPage.Zones.Count = 0 ThenMessageBox.Show(Me, "No zones left in the page, saving this document to PDF is disabled now")End IfEnd IfEnd Sub
Finally add the following code to handle a mouse double-click. Save the document:
private void _imageViewer_MouseDoubleClick(object sender, MouseEventArgs e){// Check if we have any zones in the pageif (_ocrPage.Zones.Count == 0){MessageBox.Show(this, "No zones left in the page, saving this document to PDF is disabled");return;}// Yes, recognizestring pdfFileName = @"C:\Users\Public\Documents\LEADTOOLS Images\Ocr1.pdf";// Try to delete the file if it exists. Might be open by the external application from previous operationif (System.IO.File.Exists(pdfFileName)){try{System.IO.File.Delete(pdfFileName);}catch{MessageBox.Show(this, "The file is probably opened in an external viewer. Close it and try again");return;}}_ocrPage.Recognize(null);// Create a documentusing (IOcrDocument ocrDocument = _ocrEngine.DocumentManager.CreateDocument(null, OcrCreateDocumentOptions.AutoDeleteFile)){// Add the pageocrDocument.Pages.Add(_ocrPage);// Save as PDFocrDocument.Save(pdfFileName, DocumentFormat.Pdf, null);}// Show the documentSystem.Diagnostics.Process.Start(pdfFileName);}
Private Sub _imageViewer_MouseDoubleClick(sender As Object, e As MouseEventArgs)' Check if there are any zones in the pageIf _ocrPage.Zones.Count = 0 ThenMessageBox.Show(Me, "No zones left in the page, saving this document to PDF is disabled")ReturnEnd If' Yes, recognizeDim pdfFileName As String = "C:\Users\Public\Documents\LEADTOOLS Images\Ocr1.pdf"' Try to delete the file if it exists. Might be open by the external application from previous operationIf System.IO.File.Exists(pdfFileName) ThenTrySystem.IO.File.Delete(pdfFileName)CatchMessageBox.Show(Me, "The file is probably opened in an external viewer. Close it and try again")ReturnEnd TryEnd If_ocrPage.Recognize(Nothing)' Create a documentUsing ocrDocument As IOcrDocument = _ocrEngine.DocumentManager.CreateDocument(Nothing, OcrCreateDocumentOptions.AutoDeleteFile)' Add the pageocrDocument.Pages.Add(_ocrPage)' Save as PDFocrDocument.Save(pdfFileName, DocumentFormat.Pdf, Nothing)End Using' Show the documentSystem.Diagnostics.Process.Start(pdfFileName)End Sub
Save this project to use for testing other code samples.
OCR Tutorial - Working with Pages
OCR Tutorial - Recognizing Pages
OCR Tutorial - Working with Recognition Results
OCR Tutorial - Scanning to Searchable PDF
Getting Started (Guide to Example Programs)
Programming with LEADTOOLS .NET OCR
An Overview of OCR Recognition Modules
Creating an OCR Engine Instance
Starting and Shutting Down the OCR Engine
Multi-Threading with LEADTOOLS OCR
OCR Spell Language Dictionaries
Using OMR in LEADTOOLS .NET OCR