using System;
using System.IO;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238
using Windows.Foundation;
using Windows.UI.Core;
using Windows.UI.Notifications;
using Windows.Storage.Pickers;
using Windows.Data.Xml.Dom;
using Leadtools;
using Leadtools.Codecs;
using Leadtools.Controls;
using Leadtools.Forms.DocumentWriters;
using Leadtools.Forms.Ocr;
namespace LEADTOOLSWinRTOCR
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class MainPage : Page
{
// OCR engine instance
private IOcrEngine _ocrEngine;
// Current OCR document
private IOcrDocument _ocrDocument;
// Current OCR page
private IOcrPage _ocrPage;
public MainPage()
{
this.InitializeComponent();
}
// Save LEADTOOLS image formats
private struct ImageFormat
{
public string Name;
public string Extension;
public RasterImageFormat Format;
public ImageFormat(string name, string extension, RasterImageFormat format)
{
Name = name;
Extension = extension;
Format = format;
}
public override string ToString()
{
return Name;
}
};
private static ImageFormat[] _imageFormats =
{
new ImageFormat("PDF", ".pdf", RasterImageFormat.RasPdf),
new ImageFormat("BMP", ".bmp", RasterImageFormat.Bmp),
new ImageFormat("JPEG", ".jpg", RasterImageFormat.Jpeg422),
new ImageFormat("TIFF", ".tif", RasterImageFormat.CcittGroup4),
new ImageFormat("PNG", ".png", RasterImageFormat.Png),
};
/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name="e">Event data that describes how this page was reached. The Parameter
/// property is typically used to configure the page.</param>
protected override void OnNavigatedTo(NavigationEventArgs e)
{
// Initialize LEADTOOLS support
RasterSupport.Initialize();
try
{
// Create an instance of the engine
string strEngineDirectory = Path.Combine(Windows.ApplicationModel.Package.Current.InstalledLocation.Path, @"OCR");
_ocrEngine = OcrEngineManager.CreateEngine(OcrEngineType.Advantage, false);
_ocrEngine.Startup(null, null, string.Empty, strEngineDirectory);
// Create the OCR document
_ocrDocument = _ocrEngine.DocumentManager.CreateDocument();
ShowMessage("OCR engine started");
}
catch (Exception ex)
{
ShowError(ex);
}
}
private void rasterImageViewer1_Loaded(object sender, RoutedEventArgs e)
{
// Set up rubber band as the interactive mode
ImageViewerRubberBandInteractiveMode rubberband = new ImageViewerRubberBandInteractiveMode();
rubberband.RubberBandCompleted += delegate(object rubberBandSender, ImageViewerRubberBandEventArgs rubberBandEventArgs)
{
// Get the rubber band rectangle
Rect bounds = new Rect(rubberBandEventArgs.Point1, rubberBandEventArgs.Point2);
if (bounds.Width > 1 && bounds.Height > 1)
{
// Convert it to image coordinates
bounds = rasterImageViewer1.ConvertRect(CoordinateType.Control, CoordinateType.Image, bounds);
RecognizeText(bounds);
}
};
rasterImageViewer1.DefaultInteractiveMode = rubberband;
}
private async void LoadButton_Click(object sender, RoutedEventArgs e)
{
// Show the file picker
var picker = new FileOpenPicker();
picker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
picker.ViewMode = PickerViewMode.List;
foreach (var imageFormat in _imageFormats)
picker.FileTypeFilter.Add(imageFormat.Extension);
try
{
var file = await picker.PickSingleFileAsync();
if (file == null)
return;
// Create a LEADTOOLS stream from the file
ILeadStream leadStream = LeadStreamFactory.Create(file);
// Get the RasterCodecs object to load the image from the OCR engine
RasterCodecs codecs = _ocrEngine.RasterCodecsInstance;
// Load the image (first page only)
RasterImage rasterImage = await codecs.LoadAsync(leadStream, 0, CodecsLoadByteOrder.BgrOrGray, 1, 1);
(leadStream as IDisposable).Dispose();
// Add it to the OCR engine
// Check if we have previous pages, remove them
_ocrDocument.Pages.Clear();
_ocrPage = _ocrDocument.Pages.AddPage(rasterImage, null);
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, delegate()
{
rasterImageViewer1.Image = rasterImage;
rasterImageViewer1.Zoom(ImageViewerSizeMode.Fit, 1, rasterImageViewer1.DefaultZoomOrigin);
});
}
catch (Exception ex)
{
ShowError(ex);
}
}
private async void OcrPdfButton_Click(object sender, RoutedEventArgs e)
{
TextResults.Text = "";
if (_ocrPage == null)
{
ShowMessage("Load an image first...");
return;
}
try
{
// Pick the output file
var picker = new FileSavePicker();
picker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
picker.FileTypeChoices.Add("PDF", new string[] { ".pdf" });
picker.DefaultFileExtension = ".pdf";
var file = await picker.PickSaveFileAsync();
if(file == null)
return;
// Auto-zone the page
_ocrPage.AutoZone(null);
// Recognize the page
_ocrPage.Recognize(null);
// Create a LEADTOOLS stream from the file
ILeadStream leadStream = LeadStreamFactory.Create(file);
// Set PDF output options, use PDF/A
PdfDocumentOptions options = _ocrEngine.DocumentWriterInstance.GetOptions(DocumentFormat.Pdf) as PdfDocumentOptions;
options.DocumentType = PdfDocumentType.PdfA;
_ocrEngine.DocumentWriterInstance.SetOptions(DocumentFormat.Pdf, options);
// Save the OCR'd document as searchable PDF
await _ocrDocument.SaveAsync(leadStream, DocumentFormat.Pdf, null);
// Show a compeleted message
ShowMessage("Recognized as PDF");
}
catch (Exception ex)
{
ShowError(ex);
}
}
private void OcrTextButton_Click(object sender, RoutedEventArgs e)
{
TextResults.Text = "";
if (_ocrPage == null)
{
ShowMessage("Load an image first...");
return;
}
RecognizeText(Rect.Empty);
}
private void RecognizeText(Rect bounds)
{
try
{
// If we have a bounds, only recognize that area, otherwise, recognize all
if (bounds.IsEmpty)
{
// No area, auto-zone
_ocrPage.AutoZone(null);
}
else
{
// Clear the zones first
_ocrPage.Zones.Clear();
// Add our bounds
OcrZone zone = OcrTypeManager.CreateDefaultOcrZone();
zone.ZoneType = OcrZoneType.Text;
zone.Bounds = LeadRectHelper.Create((int)bounds.X, (int)bounds.Y, (int)bounds.Width, (int)bounds.Height);
_ocrPage.Zones.Add(zone);
}
// Recognize the page and get the results as text
TextResults.Text = _ocrPage.RecognizeText(null);
ShowMessage("Recognized as Text");
}
catch (Exception ex)
{
ShowError(ex);
}
}
private async void ShowMessage(string message)
{
// We will use a toast to show the error message
// Make sure the app is "Toast Capable"
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, delegate()
{
XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(ToastTemplateType.ToastImageAndText01);
XmlNodeList textElements = toastXml.GetElementsByTagName("text");
textElements.Item(0).AppendChild(toastXml.CreateTextNode(message));
// Create a toast from the Xml, then create a ToastNotifier object
// to show the toast
ToastNotification toast = new ToastNotification(toastXml);
// If you have other applications in your package, you can specify
// the AppId of the app to create a ToastNotifier for that application
ToastNotificationManager.CreateToastNotifier().Show(toast);
});
}
private void ShowError(Exception error)
{
// Get the error message
string errorMessage = null;
// Check if it is a LEADTOOLS exception
RasterException rasterException = RasterException.FromHResult(error.HResult);
if (rasterException != null)
errorMessage = string.Format("LEADTOOLS Error: {0}\n{1}", rasterException.Code, rasterException.Message);
else
errorMessage = error.Message;
ShowMessage(errorMessage);
}
}
}