private void _openDocumentFromFileToolStripMenuItem_Click(object sender, EventArgs e) { using (var dlg = new UI.OpenDocumentFileDialog()) { dlg.DocumentFileName = _preferences.LastDocumentFileName; dlg.FirstPageNumber = _preferences.LastDocumentFirstPageNumber; dlg.LastPageNumber = _preferences.LastDocumentLastPageNumber; dlg.AnnotationsFileName = _preferences.LastAnnotationsFileName; dlg.LoadEmbeddedAnnotations = _preferences.LastFileLoadEmbeddedAnnotations; dlg.LoadAttachmentsMode = _preferences.LastLoadAttachmentsMode; dlg.RenderAnnotations = _preferences.LastRenderAnnotations; if (dlg.ShowDialog(this) == DialogResult.OK) { var options = new LoadDocumentOptions(); options.FirstPageNumber = dlg.FirstPageNumber; options.LastPageNumber = dlg.LastPageNumber; options.AnnotationsUri = !string.IsNullOrEmpty(dlg.AnnotationsFileName) ? new Uri(dlg.AnnotationsFileName) : null; options.LoadEmbeddedAnnotations = dlg.LoadEmbeddedAnnotations; options.LoadAttachmentsMode = dlg.LoadAttachmentsMode; options.RenderAnnotations = dlg.RenderAnnotations; LoadDocumentFromFile(dlg.DocumentFileName, options); } } }
public async Task <HttpResponseMessage> ExtractCheck([FromUri] LeadWebRequest request) { try { AuthenticateRequest(); if (!VerifyCommonParameters(request)) { throw new MalformedRequestException(); } using (var stream = await GetImageStream(request.fileUrl)) { int lastPage = request.LastPage; ValidateFile(stream, ref lastPage); LoadDocumentOptions options = new LoadDocumentOptions() { FirstPageNumber = request.FirstPage, LastPageNumber = lastPage }; RecognitionEngine recognitionEngine = new RecognitionEngine(); recognitionEngine.OcrEngine = ocrEngine; var micrResults = recognitionEngine.ExtractMicr(stream, options, Leadtools.Forms.Commands.BankCheckMicrFontType.Unknown); return(new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(JsonConvert.SerializeObject(micrResults)) }); } } catch (Exception e) { return(GenerateExceptionMessage(e)); } }
public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = "Conversion/ConvertToDocument")] HttpRequestMessage req, TraceWriter log, ExecutionContext context) { try { if (!DemoConfiguration.UnlockSupport(log)) { return(GenerateErrorMessage(ApiError.LicenseNotSet, req)); } var leadParameterObject = ParseLeadWebRequestParameters(req); if (!leadParameterObject.Successful) { return(GenerateErrorMessage(ApiError.InvalidRequest, req)); } var convertToDocuemntParameterObject = ParseConvertToDocumentParameters(req); if (!convertToDocuemntParameterObject.Successful) { return(GenerateErrorMessage(ApiError.InvalidRequest, req)); } var imageReturn = await GetImageStreamAsync(leadParameterObject.LeadWebRequest.fileUrl, req, DemoConfiguration.MaxUrlMbs); if (!imageReturn.Successful) { return(GenerateErrorMessage(imageReturn.ErrorType.Value, req)); } using (imageReturn.Stream) { LoadDocumentOptions options = new LoadDocumentOptions() { FirstPageNumber = leadParameterObject.LeadWebRequest.FirstPage, LastPageNumber = leadParameterObject.LeadWebRequest.LastPage }; ConversionEngine engine = new ConversionEngine { OcrEngine = GetOcrEngine(), Preprocess = false, UseThreads = false }; var filenamelist = engine.Convert(imageReturn.Stream, options, RasterImageFormat.Unknown, convertToDocuemntParameterObject.OutputFormat); var returnRequest = req.CreateResponse(HttpStatusCode.OK); returnRequest.Content = new StringContent(JsonConvert.SerializeObject(filenamelist)); return(returnRequest); } } catch (Exception ex) { log.Error($"API Error occurred for request: {context.InvocationId} \n Details: {JsonConvert.SerializeObject(ex)}"); return(GenerateErrorMessage(ApiError.InternalServerError, req)); } }
public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = "Recognition/ExtractCheck")] HttpRequestMessage req, TraceWriter log, ExecutionContext context) { try { if (!DemoConfiguration.UnlockSupport(log)) { return(GenerateErrorMessage(ApiError.LicenseNotSet, req)); } var leadParameterObject = ParseLeadWebRequestParameters(req); if (!leadParameterObject.Successful) { return(GenerateErrorMessage(ApiError.InvalidRequest, req)); } var imageReturn = await GetImageStreamAsync(leadParameterObject.LeadWebRequest.fileUrl, req, DemoConfiguration.MaxUrlMbs); if (!imageReturn.Successful) { return(GenerateErrorMessage(imageReturn.ErrorType.Value, req)); } using (imageReturn.Stream) { LoadDocumentOptions options = new LoadDocumentOptions() { FirstPageNumber = leadParameterObject.LeadWebRequest.FirstPage, LastPageNumber = leadParameterObject.LeadWebRequest.LastPage }; RecognitionEngine recognitionEngine = new RecognitionEngine { WorkingDirectory = Path.GetTempPath(), OcrEngine = GetOcrEngine() }; var micrResults = recognitionEngine.ExtractMicr(imageReturn.Stream, options, BankCheckMicrFontType.Unknown); var returnRequest = req.CreateResponse(HttpStatusCode.OK); returnRequest.Content = new StringContent(JsonConvert.SerializeObject(micrResults)); return(returnRequest); } } catch (Exception ex) { log.Error($"API Error occurred for request: {context.InvocationId} \n Details: {JsonConvert.SerializeObject(ex)}"); return(GenerateErrorMessage(ApiError.InternalServerError, req)); } }
private void buttonOcrOptions_Click(object sender, EventArgs e) { EngineSettingsDialog dlg = new EngineSettingsDialog(_ocrEngine); dlg.ShowDialog(); _ocrEngine.SettingManager.SetBooleanValue("Recognition.ShareOriginalImage", false);//this demo does not support the sharing mode SaveOcrSettings(_ocrEngine); if (_imageViewer.Image != null) { var result = MessageBox.Show("Do you want to retry the OCR with the updated settings?", "Retry?", MessageBoxButtons.YesNo); if (result == DialogResult.Yes) { try { // OCR the image and get back an RTF file string document = DoOcr(_imageViewer.Image); if (!string.IsNullOrEmpty(document)) { var options = new LoadDocumentOptions() { UseCache = false }; // Load the RTF file var doc = DocumentFactory.LoadFromFile(document, options); doc.AutoDisposeDocuments = true; _svgViewer.SetDocument(doc); _svgViewer.Commands.Run(DocumentViewerCommands.ViewFitPage); } } catch (Exception ex) { RasterException rasex = ex as RasterException; Messager.ShowError(this, ex); } finally { EnableUI(true); } } } }
public async Task <HttpResponseMessage> ConvertToDocument([FromUri] DocumentConversionWebRequest request) { try { AuthenticateRequest(); if (!VerifyCommonParameters(request)) { throw new Exception(); } using (var stream = await GetImageStream(request.fileUrl)) { int lastPage = request.LastPage; ValidateFile(stream, ref lastPage); ConversionEngine conversion = new ConversionEngine() { WorkingDirectory = DemoConfiguration.OutputFileDirectory, OcrEngine = ocrEngine }; LoadDocumentOptions options = new LoadDocumentOptions() { FirstPageNumber = request.FirstPage, LastPageNumber = lastPage }; var fileNameList = conversion.Convert(stream, options, Leadtools.RasterImageFormat.Unknown, request.Format); return(new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(JsonConvert.SerializeObject(fileNameList)) }); } } catch (Exception e) { return(GenerateExceptionMessage(e)); } }
private static LEADDocument AddDocumentToCache(LEADDocument largestDocument, IOcrEngine ocrEngine, Uri documentUri, LoadDocumentOptions loadOptions, DocumentCacheOptions cacheOptions) { // Adds the document to the cache. Note that a new cache entry is created for each different maximumImagePixelSize. var document = DocumentFactory.LoadFromUri(documentUri, loadOptions); try { if (document == null) { throw new InvalidOperationException("Failed to load URI: " + documentUri); } // We will modify this document... bool wasReadOnly = document.IsReadOnly; document.IsReadOnly = false; if (document.Text.TextExtractionMode != DocumentTextExtractionMode.OcrOnly && !document.Images.IsSvgSupported && ocrEngine != null) { document.Text.OcrEngine = ocrEngine; } // Set in the cache options that we want document.CacheOptions = cacheOptions; // prepare the document, caching as much as possible. if (document.IsStructureSupported && !document.Structure.IsParsed) { document.Structure.Parse(); } // Need to cache the SVG with and without getting the back image var loadSvgOptions = new CodecsLoadSvgOptions(); foreach (var page in document.Pages) { // If we have a previous largest document, use the same // SVG and text instead of recreating them (they do not change based on image size) DocumentPage largestDocumentPage = null; if (largestDocument != null) { largestDocumentPage = largestDocument.Pages[page.PageNumber - 1]; } if (cacheOptions == DocumentCacheOptions.None) { // We are done, do not cache the images, svg or text continue; } if ((cacheOptions & DocumentCacheOptions.PageSvg) == DocumentCacheOptions.PageSvg) { // SVG, this does not depend on the image size using (var svg = page.GetSvg(null)) { } using (var svg = page.GetSvg(loadSvgOptions)) { } } if ((cacheOptions & DocumentCacheOptions.PageSvgBackImage) == DocumentCacheOptions.PageSvgBackImage) { // SVG back image, this is different based on the image size using (var svgBack = page.GetSvgBackImage(RasterColor.FromKnownColor(RasterKnownColor.White))) { } } if ((cacheOptions & DocumentCacheOptions.PageImage) == DocumentCacheOptions.PageImage) { // Image, this is different based on the image size using (var image = page.GetImage()) { } } if ((cacheOptions & DocumentCacheOptions.PageThumbnailImage) == DocumentCacheOptions.PageThumbnailImage) { // Thumbnail, this does not depend on the image size but there is no set thumbnail method using (var thumbnailImage = page.GetThumbnailImage()) { } } if ((cacheOptions & DocumentCacheOptions.PageText) == DocumentCacheOptions.PageText) { // Text, this does not depend on the image size if (largestDocumentPage == null) { page.GetText(); } else { var pageText = largestDocumentPage.GetText(); page.SetText(pageText); } } } document.AutoDeleteFromCache = false; document.AutoDisposeDocuments = true; document.AutoSaveToCache = false; // Stop caching document.CacheOptions = DocumentCacheOptions.None; document.IsReadOnly = wasReadOnly; // save it to the regular cache document.SaveToCache(); return(document); } catch (Exception) { if (document != null) { document.Dispose(); } throw; } }
public static PreCacheDocumentResponse AddDocument(ObjectCache cache, PreCacheDocumentRequest request) { var loadOptions = new LoadDocumentOptions(); loadOptions.Cache = cache; loadOptions.UseCache = true; // Get the expiry policy CacheItemPolicy cachePolicy; if (request.ExpiryDate == new DateTime()) { cachePolicy = ServiceHelper.CreateForeverPolicy(); } else { cachePolicy = new CacheItemPolicy() { AbsoluteExpiration = request.ExpiryDate }; } loadOptions.CachePolicy = cachePolicy; // Get the maximum pixel size, if the user did not pass one, use the default values of 4096 and 2048 (used by the DocumentViewerDemo) var maximumImagePixelSizes = request.MaximumImagePixelSizes; if (maximumImagePixelSizes == null || maximumImagePixelSizes.Length == 0) { maximumImagePixelSizes = DefaultSizes; } // Sort the maximum image pixel size from largest to smallest // We will re-use the values from largest to set the smaller images text and SVG since they do // not change Array.Sort( maximumImagePixelSizes, new Comparison <int>((x, y) => y.CompareTo(x))); // Get the safe hash name from the uri var regionName = GetRegionName(request.Uri); // The PreCacheEntries are what will be cached, based on this map of sizes to documentId values. var sizeIdDictionary = new Dictionary <int, string>(); // The PreCacheResponseItems are what we will return as a confirmation. var responseItems = new PreCacheResponseSizeItem[maximumImagePixelSizes.Length]; var ocrEngine = ServiceHelper.GetOCREngine(); // Largest document (to re-use) LEADDocument largestDocument = null; try { // Now load the document and cache it for (var index = 0; index < maximumImagePixelSizes.Length; index++) { // No duplicates if (index > 0 && maximumImagePixelSizes[index] == maximumImagePixelSizes[index - 1]) { continue; } var size = maximumImagePixelSizes[index]; // If it's in the cache, delete it (deletes from PreCache also) string documentId = InternalCheckDocument(regionName, GetKeyName(size)); if (documentId != null) { DocumentHelper.DeleteDocument(documentId, false, false); } // keep track for logging purposes var start = DateTime.Now; // re-use the load options, just change the size loadOptions.MaximumImagePixelSize = size; // Cache the Document var document = AddDocumentToCache(largestDocument, ocrEngine, request.Uri, loadOptions, request.CacheOptions); try { var stop = DateTime.Now; documentId = document.DocumentId; responseItems[index] = new PreCacheResponseSizeItem() { Seconds = Math.Round((stop - start).TotalSeconds, 4), DocumentId = documentId, MaximumImagePixelSize = size, }; // add to our dictionary for updating the pre-cache all at once sizeIdDictionary.Add(size, documentId); } finally { if (largestDocument == null) { largestDocument = document; } else { document.Dispose(); } } } } finally { if (largestDocument != null) { largestDocument.Dispose(); } } // Add all the info to the PreCache AddDocumentToPreCache(regionName, request.Uri, sizeIdDictionary); return(new PreCacheDocumentResponse() { Item = new PreCacheResponseItem() { Uri = request.Uri.ToString(), RegionHash = regionName, Items = responseItems, } }); }
public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = "Recognition/ExtractAllBarcodes")] HttpRequestMessage req, TraceWriter log, ExecutionContext context) { try { if (!DemoConfiguration.UnlockSupport(log)) { return(GenerateErrorMessage(ApiError.LicenseNotSet, req)); } var leadParameterObject = ParseLeadWebRequestParameters(req); if (!leadParameterObject.Successful) { return(GenerateErrorMessage(ApiError.InvalidRequest, req)); } var barcodeList = ExtractBarcodeSymbologies(req); if (barcodeList.Count == 0) { return(GenerateErrorMessage(ApiError.InvalidRequest, req)); } var imageReturn = await GetImageStreamAsync(leadParameterObject.LeadWebRequest.fileUrl, req, DemoConfiguration.MaxUrlMbs); if (!imageReturn.Successful) { return(GenerateErrorMessage(imageReturn.ErrorType.Value, req)); } using (imageReturn.Stream) { LoadDocumentOptions options = new LoadDocumentOptions() { FirstPageNumber = leadParameterObject.LeadWebRequest.FirstPage, LastPageNumber = leadParameterObject.LeadWebRequest.LastPage }; RecognitionEngine recognitionEngine = new RecognitionEngine(); recognitionEngine.WorkingDirectory = Path.GetTempPath(); BarcodeEngine barcodeEngine = new BarcodeEngine(); var barcodeResults = recognitionEngine.ExtractBarcode(imageReturn.Stream, options, barcodeEngine, barcodeList.ToArray(), 0, true); List <BarcodeResultData> results = new List <BarcodeResultData>(); foreach (var pageBarcodeData in barcodeResults) { foreach (var d in pageBarcodeData.BarcodeData) { if (d != null && d.Value != null) { var rect = new Rectangle(d.Bounds.X, d.Bounds.Y, d.Bounds.Width, d.Bounds.Height); results.Add(new BarcodeResultData(pageBarcodeData.PageNumber, d.Symbology.ToString(), d.Value, rect, d.RotationAngle)); } } } var returnRequest = req.CreateResponse(HttpStatusCode.OK); returnRequest.Content = new StringContent(JsonConvert.SerializeObject(results)); return(returnRequest); } } catch (Exception ex) { log.Error($"API Error occurred for request: {context.InvocationId} \n Details: {JsonConvert.SerializeObject(ex)}"); return(GenerateErrorMessage(ApiError.InternalServerError, req)); } }
[HttpPost, HttpGet] // Support GET only for testing public LoadFromUriResponse LoadFromUri(LoadFromUriRequest request) { if (request == null) { throw new ArgumentNullException("request"); } if (request.Uri == null) { throw new ArgumentException("uri must be specified"); } ServiceHelper.CheckUriScheme(request.Uri); if (request.Options != null && request.Options.AnnotationsUri != null) { ServiceHelper.CheckUriScheme(request.Options.AnnotationsUri); } if (request.Resolution < 0) { throw new ArgumentException("Resolution must be a value greater than or equal to zero"); } var cache = ServiceHelper.Cache; var loadOptions = new LoadDocumentOptions(); loadOptions.Cache = cache; loadOptions.UseCache = cache != null; loadOptions.CachePolicy = ServiceHelper.CreatePolicy(); loadOptions.WebClient = null; // Use default if (request.Options != null) { loadOptions.DocumentId = request.Options.DocumentId; loadOptions.AnnotationsUri = request.Options.AnnotationsUri; loadOptions.Name = request.Options.Name; loadOptions.Password = request.Options.Password; loadOptions.LoadEmbeddedAnnotations = request.Options.LoadEmbeddedAnnotations; loadOptions.MaximumImagePixelSize = request.Options.MaximumImagePixelSize; loadOptions.FirstPageNumber = request.Options.FirstPageNumber; loadOptions.LastPageNumber = request.Options.LastPageNumber; } // Get the document name var documentName = request.Uri.ToString(); // Check if this document was uploaded, then hope the user has set LoadDocumentOptions.Name to the original file name if (DocumentFactory.IsUploadDocumentUri(request.Uri) && !string.IsNullOrEmpty(loadOptions.Name)) { // Use that instead documentName = loadOptions.Name; } // Most image file formats have a signature that can be used to detect to detect the type of the file. // However, some formats supported by LEADTOOLS do not, such as plain text files (TXT) or DXF CAD format or // For these, we detect the MIME type from the file extension if available and set it in the load document options and the // documents library will use this value if it fails to detect the file format from the data. if (!string.IsNullOrEmpty(documentName)) { loadOptions.MimeType = RasterCodecs.GetExtensionMimeType(documentName); } LEADDocument document = null; try { // first, check if this is pre-cached if (PreCacheHelper.PreCacheExists) { string documentId = PreCacheHelper.CheckDocument(request.Uri, loadOptions.MaximumImagePixelSize); if (documentId != null) { var precachedDocument = DocumentFactory.LoadFromCache(cache, documentId); // Instead of returning the same pre-cached document, we'll return a cloned version. // This allows the user to make changes (get/set annotations) without affecting the pre-cached version. document = precachedDocument.Clone(cache, new CloneDocumentOptions() { CachePolicy = ServiceHelper.CreatePolicy() }); } } // else, load normally if (document == null) { document = DocumentFactory.LoadFromUri(request.Uri, loadOptions); if (document == null) { // This document was rejected due to its mimeType. throw new InvalidOperationException("Document at URI '" + request.Uri + "' uses a blocked mimeType"); } } CacheController.TrySetCacheUri(document); if (ServiceHelper.AutoUpdateHistory) { document.History.AutoUpdate = true; } ServiceHelper.SetRasterCodecsOptions(document.RasterCodecs, request.Resolution); document.AutoDeleteFromCache = false; document.AutoDisposeDocuments = true; document.AutoSaveToCache = false; document.SaveToCache(); /* * NOTE: Use the line below to add this new document * to the pre-cache. By doing so, everyone loading a document from * that URL will get a copy of the same document from the cache/pre-cache. * * if (!isInPrecache) * PreCacheHelper.AddExistingDocument(request.Uri, document); */ return(new LoadFromUriResponse { Document = document }); } finally { if (document != null) { document.Dispose(); } } }
private void buttonScreenCapture_Click(object sender, EventArgs e) { if (_tsUseHotkey.Checked && !showMessagebox) { MyMessageBox myMessageBox = new MyMessageBox("Hotkey Capture", "Press F11 to start capture"); myMessageBox.Show(this); showMessagebox = myMessageBox.Checked; } EnableUI(false); System.Threading.Thread.Sleep(500); try { // Capture an area from the screen RasterImage image = DoCapture(_tsUseHotkey.Checked); this.BringToFront(); ColorResolutionCommand colorRes = new ColorResolutionCommand(ColorResolutionCommandMode.InPlace, 24, RasterByteOrder.Bgr, RasterDitheringMethod.None, ColorResolutionCommandPaletteFlags.Fixed, null); colorRes.Run(image); EnableUI(true); if (image != null) { ClearDocument(); ClearImage(); // Store the new image _imageViewer.Image = image; // Set the image to the PictureBox UpdateViewer(); // OCR the image and get back an RTF file string document = DoOcr(_imageViewer.Image); if (!string.IsNullOrEmpty(document)) { var options = new LoadDocumentOptions() { UseCache = false }; // Load the RTF file var doc = DocumentFactory.LoadFromFile(document, options); doc.AutoDisposeDocuments = true; _svgViewer.SetDocument(doc); _svgViewer.Commands.Run(DocumentViewerCommands.ViewFitPage); } } } catch (Exception ex) { RasterException rasex = ex as RasterException; if (rasex != null) { if (rasex.Code != RasterExceptionCode.UserAbort) { Messager.ShowError(this, ex); } } else { Messager.ShowError(this, ex); } } finally { EnableUI(true); } }
private static bool Convert(DocumentConverter converter, string inFile, string outFile, DocumentConverterPreferences preferences) { // Setup the load document options var loadDocumentOptions = new LoadDocumentOptions(); // Not using cache loadDocumentOptions.UseCache = false; // Set the input annotation mode or file name loadDocumentOptions.LoadEmbeddedAnnotations = preferences.LoadEmbeddedAnnotation; converter.LoadDocumentOptions = loadDocumentOptions; if (preferences.DocumentFormat == DocumentFormat.Ltd && File.Exists(outFile)) { File.Delete(outFile); } // Create a job var jobData = new DocumentConverterJobData { InputDocumentFileName = inFile, InputDocumentFirstPageNumber = preferences.InputFirstPage, InputDocumentLastPageNumber = preferences.InputLastPage, DocumentFormat = preferences.DocumentFormat, RasterImageFormat = preferences.RasterImageFormat, RasterImageBitsPerPixel = preferences.RasterImageBitsPerPixel, OutputDocumentFileName = outFile, AnnotationsMode = preferences.OutputAnnotationsMode, JobName = preferences.JobName, UserData = null, }; // Create the job var job = converter.Jobs.CreateJob(jobData); var ret = true; // Run it try { Trace.WriteLine("Running job..."); var stopwatch = new Stopwatch(); stopwatch.Start(); converter.Jobs.RunJob(job); stopwatch.Stop(); var elapsed = stopwatch.ElapsedMilliseconds; _totalTime += elapsed; // If we have errors, show them Trace.WriteLine("----------------------------------"); Trace.WriteLine("Status: " + job.Status); Trace.WriteLine("----------------------------------"); Trace.WriteLine("Conversion modes: " + job.ConversionModes); Log(string.Format("{0} - {1} - {2}", job.Status, job.ConversionModes, inFile)); ret = job.Status == DocumentConverterJobStatus.Success; if (job.Errors.Count > 0) { ret = false; // We have errors, show them Trace.WriteLine("Errors found:"); Log("Errors found:"); foreach (var error in job.Errors) { var message = string.Format("Page: {0} - Operation: {1} - Error: {2}", error.InputDocumentPageNumber, error.Operation, error.Error); Trace.WriteLine(message); Log(message); } } Trace.WriteLine("Total conversion time: " + elapsed.ToString()); Log("Total conversion time: " + elapsed.ToString()); Trace.WriteLine("----------------------------"); } catch (OcrException ex) { var message = string.Format("OCR error code: {0} - {1}", ex.Code, ex.Message); Trace.WriteLine(message); Log(string.Format("{0} - {1}", message, inFile)); ret = false; } catch (RasterException ex) { var message = string.Format("LEADTOOLS error code: {0} - {1}", ex.Code, ex.Message); Trace.WriteLine(message); Log(string.Format("{0} - {1}", message, inFile)); ret = false; } catch (Exception ex) { var message = string.Format("Error: {0} - {1}", ex.GetType().FullName, ex.Message); Trace.WriteLine(message); Log(string.Format("{0} - {1}", message, inFile)); ret = false; } return(ret); }
public static LEADDocument CreateDocument(List <string> files, Stream stream, LEADDocument userDocumentToAppendTo, out List <Exception> errors) { errors = new List <Exception>(); // If we are loading from single file then don't create virtual document, just create it directly from file LEADDocument virtualDocument = userDocumentToAppendTo ?? ((stream != null || (files != null && files.Count == 1)) ? null : CreateVirtualDocument()); // Setup the document load options var options = new LoadDocumentOptions(); options.Cache = CacheObject; options.UseCache = !string.IsNullOrWhiteSpace(CacheDirectory); options.MayHaveDifferentPageSizes = true; if (files != null) { int numberOfLoadedFiles = 0; string annotationsFileName = string.Empty; foreach (string imagePath in files) { string filePath = imagePath; try { // Check source file size, if zero then ignore it, will return error later. FileInfo fi = new FileInfo(filePath); if (fi == null || fi.Length == 0) { continue; } numberOfLoadedFiles++; if (Device.RuntimePlatform == Device.iOS) { // The only way to keep the file after loading it from photo gallery on iOS is to save it somewhere else, so copy these files to Cache directory. // only do this for the files that came from gallery and not the already converted document files. string documentsDirectory = Path.Combine(ApplicationDirectory, "Documents"); if (!string.IsNullOrWhiteSpace(CacheDirectory) && !Path.GetDirectoryName(filePath).Equals(documentsDirectory, StringComparison.OrdinalIgnoreCase) && File.Exists(filePath)) { string backupFilePath = Path.Combine(CacheDirectory, Path.GetFileName(filePath)); File.Copy(filePath, backupFilePath, true); filePath = backupFilePath; } } if (string.IsNullOrWhiteSpace(annotationsFileName)) { if (filePath.EndsWith(".svg", StringComparison.OrdinalIgnoreCase)) { // In case of multipage SVG files we need to get the document name from the file names string directory = Path.GetDirectoryName(filePath); string docName = Path.GetFileNameWithoutExtension(filePath); int svgMultiPageSuffixIndex = docName.IndexOf("_Page("); // Check if we have multipage suffix "_Page(X)", if not then this is a single page SVG and we should use original SVG file name if (svgMultiPageSuffixIndex != -1) { docName = docName.Substring(0, docName.IndexOf("_Page(")); } annotationsFileName = Path.Combine(directory, $"{docName}.xml"); } else { annotationsFileName = Path.ChangeExtension(filePath, "xml"); } } if (File.Exists(annotationsFileName)) { options.AnnotationsUri = new Uri(annotationsFileName); } LEADDocument childDocument = null; if (virtualDocument == null) { virtualDocument = DocumentFactory.LoadFromFile(filePath, options); childDocument = virtualDocument; } else { childDocument = DocumentFactory.LoadFromFile(filePath, options); } if (childDocument != null) { childDocument.IsReadOnly = false; childDocument.AutoSaveToCache = true; childDocument.AutoDeleteFromCache = false; if (virtualDocument.DataType == DocumentDataType.Virtual || virtualDocument.DataType == DocumentDataType.Cached) { virtualDocument.Pages.AddRange(childDocument.Pages); } } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); try { if (File.Exists(filePath)) { File.Delete(filePath); } } catch (Exception) { } errors.Add(ex); } } if (numberOfLoadedFiles == 0) { errors.Add(new Exception("Source document has no recognized text")); } } else if (stream != null) { LEADDocument childDocument = null; if (virtualDocument == null) { virtualDocument = DocumentFactory.LoadFromStream(stream, options); childDocument = virtualDocument; } else { childDocument = DocumentFactory.LoadFromStream(stream, options); } if (childDocument != null) { childDocument.IsReadOnly = false; childDocument.AutoSaveToCache = true; childDocument.AutoDeleteFromCache = false; if (virtualDocument.DataType == DocumentDataType.Virtual || virtualDocument.DataType == DocumentDataType.Cached) { virtualDocument.Pages.AddRange(childDocument.Pages); } } } if (virtualDocument != null) { virtualDocument.Name = string.Empty; if (options.UseCache) { virtualDocument.SaveToCache(); } } return(virtualDocument); }
public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = "Recognition/ExtractText")] HttpRequestMessage req, TraceWriter log, ExecutionContext context) { try { if (!DemoConfiguration.UnlockSupport(log)) { return(GenerateErrorMessage(ApiError.LicenseNotSet, req)); } var leadParameterObject = ParseLeadWebRequestParameters(req); if (!leadParameterObject.Successful) { return(GenerateErrorMessage(ApiError.InvalidRequest, req)); } var imageReturn = await GetImageStreamAsync(leadParameterObject.LeadWebRequest.fileUrl, req, DemoConfiguration.MaxUrlMbs); if (!imageReturn.Successful) { return(GenerateErrorMessage(imageReturn.ErrorType.Value, req)); } using (imageReturn.Stream) { LoadDocumentOptions options = new LoadDocumentOptions() { FirstPageNumber = leadParameterObject.LeadWebRequest.FirstPage, LastPageNumber = leadParameterObject.LeadWebRequest.LastPage }; RecognitionEngine recognitionEngine = new RecognitionEngine { WorkingDirectory = Path.GetTempPath(), OcrEngine = GetOcrEngine() }; var documentPageText = recognitionEngine.ExtractText(imageReturn.Stream, options); List <ExtractTextData> PageDataList = new List <ExtractTextData>(); int currentPage = options.FirstPageNumber; foreach (var page in documentPageText) { for (int i = 0; i < page.Words.Count; i++) { var word = page.Words[i]; word.Bounds = word.Bounds.ToLeadRect().ToLeadRectD(); page.Words[i] = word; } for (int i = 0; i < page.Characters.Count; i++) { var character = page.Characters[i]; character.Bounds = character.Bounds.ToLeadRect().ToLeadRectD(); page.Characters[i] = character; } ExtractTextData pageData = new ExtractTextData { PageNumber = currentPage, PageText = page.Text, Words = page.Words, Characters = page.Characters }; PageDataList.Add(pageData); currentPage++; } using (var ms = new MemoryStream()) { using (TextWriter tw = new StreamWriter(ms)) { tw.Write(JsonConvert.SerializeObject(PageDataList)); tw.Flush(); ms.Position = 0; Guid id = Guid.NewGuid(); string baseName = $"ExtractText-{id}.json"; var blobUri = UploadFileToBlobStorage(ms, baseName); var returnRequest = req.CreateResponse(HttpStatusCode.OK); returnRequest.Content = new StringContent(JsonConvert.SerializeObject(blobUri)); return(returnRequest); } } } } catch (Exception ex) { log.Error($"API Error occurred for request: {context.InvocationId} \n Details: {JsonConvert.SerializeObject(ex)}"); return(GenerateErrorMessage(ApiError.InternalServerError, req)); } }
private async Task <HttpResponseMessage> ExtractBarcodes([FromUri] BarcodeWebRequest request, int barcodeAmount) { try { AuthenticateRequest(); if (!VerifyCommonParameters(request)) { throw new MalformedRequestException(); } var symbologyList = new List <BarcodeSymbology>(); if (string.IsNullOrEmpty(request.symbologies))//If no symbology string is passed, default to all symbologies. { symbologyList = Enum.GetValues(typeof(BarcodeSymbology)).OfType <BarcodeSymbology>().ToList(); symbologyList.Remove(BarcodeSymbology.Unknown); } else { symbologyList = ExtractBarcodeSymbologies(request.symbologies); //If the user did supply a list of symbologies, but they could not be parsed, we will deny the request. if (symbologyList.Count == 0) { throw new MalformedRequestException(); } } using (var stream = await GetImageStream(request.fileUrl)) { int lastPage = request.LastPage; ValidateFile(stream, ref lastPage); ConversionEngine conversion = new ConversionEngine(); LoadDocumentOptions options = new LoadDocumentOptions() { FirstPageNumber = request.FirstPage, LastPageNumber = lastPage }; RecognitionEngine recognitionEngine = new RecognitionEngine(); BarcodeEngine barcodeEngine = new BarcodeEngine(); var barcodeList = recognitionEngine.ExtractBarcode(stream, options, barcodeEngine, symbologyList.ToArray(), barcodeAmount, false); List <BarcodeResultData> results = new List <BarcodeResultData>(); foreach (var obj in barcodeList) { foreach (var d in obj.BarcodeData) { var result = new BarcodeResultData(obj.PageNumber, d.Symbology.ToString(), d.Value, new Rectangle(d.Bounds.X, d.Bounds.Y, d.Bounds.Width, d.Bounds.Height), d.RotationAngle);; results.Add(result); } } return(new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(JsonConvert.SerializeObject(results)) }); } } catch (Exception e) { return(GenerateExceptionMessage(e)); } }
private void SetOptions(DocumentConverter converter, ObjectCache cache, LEADDocument document, ConvertRedactionOptions redactionOptions) { converter.SetAnnRenderingEngineInstance(this.AnnRenderingEngine); // Set the RasterCodecs instance, should go into the DocumentFactory class which will be used to load the document if (this.RasterCodecsInstance != null) { DocumentFactory.RasterCodecsTemplate = this.RasterCodecsInstance; } // Set the OCR engine if (this.OcrEngineInstance != null && this.OcrEngineInstance.IsStarted) { converter.SetOcrEngineInstance(this.OcrEngineInstance, false); } if (this.DocumentWriterInstance != null) { converter.SetDocumentWriterInstance(this.DocumentWriterInstance); } // Set pre-processing options converter.Preprocessor.Deskew = this.PreprocessingDeskew; converter.Preprocessor.Invert = this.PreprocessingInvert; converter.Preprocessor.Orient = this.PreprocessingOrient; // Enable trace converter.Diagnostics.EnableTrace = this.EnableTrace; // Setup the load document options var loadDocumentOptions = new LoadDocumentOptions(); // Setup cache loadDocumentOptions.Cache = cache; loadDocumentOptions.UseCache = cache != null; if (document == null) { // Set the input annotation mode or file name loadDocumentOptions.LoadEmbeddedAnnotations = this.LoadEmbeddedAnnotation; if (!this.LoadEmbeddedAnnotation && !string.IsNullOrEmpty(this.InputAnnotationsFileName) && File.Exists(this.InputAnnotationsFileName)) { // We will use this instead of DocumentConverterJobData.InputAnnotationsFileName (this will override it anyway if we give the // document converter a loadDocumentOptions) loadDocumentOptions.AnnotationsUri = new Uri(this.InputAnnotationsFileName); } } converter.LoadDocumentOptions = loadDocumentOptions; // Set options converter.Options.JobErrorMode = this.ErrorMode; if (!string.IsNullOrEmpty(this.PageNumberingTemplate)) { converter.Options.PageNumberingTemplate = this.PageNumberingTemplate; } converter.Options.EnableSvgConversion = this.EnableSvgConversion; converter.Options.SvgImagesRecognitionMode = (this.OcrEngineInstance != null && this.OcrEngineInstance.IsStarted) ? this.SvgImagesRecognitionMode : DocumentConverterSvgImagesRecognitionMode.Disabled; converter.Options.EmptyPageMode = this.EmptyPageMode; converter.Options.UseThreads = this.UseThreads; converter.Diagnostics.EnableTrace = this.EnableTrace; // Set Redaction Options if (redactionOptions != null) { var documentRedactionOptions = new DocumentRedactionOptions(); documentRedactionOptions.ConvertOptions = redactionOptions; if (document != null) { documentRedactionOptions.ViewOptions = document.Annotations.RedactionOptions.ViewOptions; document.Annotations.RedactionOptions = documentRedactionOptions; } else { converter.LoadDocumentOptions.RedactionOptions = documentRedactionOptions; } } }
private async Task <HttpResponseMessage> ParseText([FromUri] LeadWebRequest request, bool additionalInfo) { try { AuthenticateRequest(); if (!VerifyCommonParameters(request)) { throw new MalformedRequestException(); } using (var stream = await GetImageStream(request.fileUrl)) { int lastPage = request.LastPage; ValidateFile(stream, ref lastPage); LoadDocumentOptions options = new LoadDocumentOptions() { FirstPageNumber = request.FirstPage, LastPageNumber = lastPage }; RecognitionEngine recognitionEngine = new RecognitionEngine(); recognitionEngine.OcrEngine = ocrEngine; recognitionEngine.WorkingDirectory = Path.GetTempPath(); var documentPageText = recognitionEngine.ExtractText(stream, options); List <ExtractTextData> PageDataList = new List <ExtractTextData>(); int currentPage = options.FirstPageNumber; if (!additionalInfo) { foreach (var page in documentPageText) { for (int i = 0; i < page.Words.Count; i++) { var word = page.Words[i]; word.Bounds = word.Bounds.ToLeadRect().ToLeadRectD(); page.Words[i] = word; } ExtractTextData pageData = new ExtractTextData { PageNumber = currentPage, PageText = page.Text, Words = page.Words.Select(w => new { w.Value, w.Bounds }).ToList() }; PageDataList.Add(pageData); currentPage++; } } else { foreach (var page in documentPageText) { for (int i = 0; i < page.Words.Count; i++) { var word = page.Words[i]; word.Bounds = word.Bounds.ToLeadRect().ToLeadRectD(); page.Words[i] = word; } for (int i = 0; i < page.Characters.Count; i++) { var character = page.Characters[i]; character.Bounds = character.Bounds.ToLeadRect().ToLeadRectD(); page.Characters[i] = character; } ExtractTextData pageData = new ExtractTextData { PageNumber = currentPage, PageText = page.Text, Words = page.Words, Characters = page.Characters }; PageDataList.Add(pageData); currentPage++; } } using (var ms = new MemoryStream()) { using (TextWriter tw = new StreamWriter(ms)) { tw.Write(JsonConvert.SerializeObject(PageDataList)); tw.Flush(); ms.Position = 0; Guid id = Guid.NewGuid(); string baseName = $"ExtractText-{id}.json"; string urlPath = $"{Url.Request.RequestUri.GetComponents(UriComponents.SchemeAndServer, UriFormat.Unescaped)}/{new DirectoryInfo(DemoConfiguration.OutputFileDirectory).Name}/{baseName}"; string serverFilePath = $"{DemoConfiguration.OutputFileDirectory}{baseName}"; SaveToDisk(ms, serverFilePath); return(new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(urlPath) }); } } } } catch (Exception e) { return(GenerateExceptionMessage(e)); } }