private async void ConvertDocuments(List <string> documentsIds, OcrOutputFormat outputFormat)
        {
            ConversionData conversionData = null;

            _documentConverterHelper.JobOperation += Converter_JobOperation;

            DocumentConverterJobStatus status = DocumentConverterJobStatus.Success;
            Dictionary <string, DocumentConvertResult> results = new Dictionary <string, DocumentConvertResult>();

            foreach (var documentId in documentsIds)
            {
                try
                {
                    LEADDocument document = LEADDocumentHelper.LoadFromCache(documentId);
                    if (document == null)
                    {
                        results.Add(documentId, new DocumentConvertResult(null, DocumentConverterJobStatus.SuccessWithErrors, new Exception($"Unable to load document with ID {documentId} from cache")));
                        continue;
                    }

                    string outputDocumentPath = GetOutputDocumentFilePath(document, outputFormat);
                    conversionData = new ConversionData()
                    {
                        Document                  = document,
                        DocumentViewer            = _documentViewer,
                        FirstPageIndex            = 0,
                        LastPageIndex             = -1,
                        OutputFormat              = outputFormat,
                        OutputDocumentPath        = outputDocumentPath,
                        OutputAnnotationsFileName = Path.ChangeExtension(outputDocumentPath, "xml"),
                        AnnotationsMode           = _annotationsMode,
                        Zones            = null,
                        DocumentScanType = DocumentScanType.Document
                    };

                    status = _documentConverterHelper.Run(conversionData);
                    if (_abort)
                    {
                        status = DocumentConverterJobStatus.Aborted;
                    }

                    List <string> finalOutputDocumentFiles = new List <string>();
                    if (_annotationsMode == DocumentConverterAnnotationsMode.External)
                    {
                        string firstDocumentFilePath = string.Empty;
                        foreach (string file in _documentConverterHelper.OutputDocumentFiles)
                        {
                            if (File.Exists(file))
                            {
                                if (string.IsNullOrWhiteSpace(firstDocumentFilePath))
                                {
                                    firstDocumentFilePath = file;
                                }
                                string outputDocumentFilePath = Path.Combine(_documentsDirectory, Path.GetFileName(file));
                                if (File.Exists(outputDocumentFilePath))
                                {
                                    File.Delete(outputDocumentFilePath);
                                }

                                File.Move(file, outputDocumentFilePath);
                                finalOutputDocumentFiles.Add(outputDocumentFilePath);
                            }
                        }

                        if (!string.IsNullOrWhiteSpace(firstDocumentFilePath))
                        {
                            // Move annotations file to documents directory
                            string tempAnnotationsFilePath = Path.Combine(Path.GetDirectoryName(firstDocumentFilePath), $"{document.Name}.xml");
                            if (File.Exists(tempAnnotationsFilePath))
                            {
                                string outputAnnotationsFilePath = Path.Combine(_documentsDirectory, Path.ChangeExtension(Path.GetFileName(tempAnnotationsFilePath), "xml"));
                                if (File.Exists(outputAnnotationsFilePath))
                                {
                                    File.Delete(outputAnnotationsFilePath);
                                }

                                File.Move(tempAnnotationsFilePath, outputAnnotationsFilePath);
                            }
                        }
                    }
                    else if (_documentConverterHelper.OutputDocumentFiles.Count > 0)
                    {
                        // In case of burning annotation into PDF file, which only occurs when sharing the document while it has annotations objects drawn
                        // don't move the saved temp file into the final documents directory, share the document from the temp folder
                        finalOutputDocumentFiles.Add(_documentConverterHelper.OutputDocumentFiles[0]);
                    }

                    results.Add(documentId, new DocumentConvertResult(finalOutputDocumentFiles, status, _documentConverterHelper.Error));

                    if (_abort)
                    {
                        List <string> convertedFiles = new List <string>();
                        foreach (KeyValuePair <string, DocumentConvertResult> entry in results)
                        {
                            if (entry.Value.OutputDocumentFiles != null && entry.Value.OutputDocumentFiles.Count > 0)
                            {
                                convertedFiles.AddRange(entry.Value.OutputDocumentFiles);
                            }
                        }

                        DocumentConverterHelper.DeleteAllFiles(convertedFiles);
                        break;
                    }
                }
                catch (Exception ex)
                {
                    results.Add(documentId, new DocumentConvertResult(null, DocumentConverterJobStatus.SuccessWithErrors, ex));
                }
            }

            _documentConverterHelper.JobOperation -= Converter_JobOperation;

            // Go back
            _pageClosingEventArgs = new DocumentConvertEventArgs(results, status, outputFormat);
            await PopupNavigation.Instance.PopAsync();
        }
        private async void DocumentConverterPage_PageClosing(object sender, DocumentConvertEventArgs e)
        {
            string oldDocumentId         = _documentViewer.Document.DocumentId;
            DocumentConvertResult result = e.Results[oldDocumentId];

            if (result == null)
            {
                return;
            }

            try
            {
                if (result.Error != null)
                {
                    await Device.InvokeOnMainThreadAsync(async() => { await DisplayAlert("Error", $"Error converting document: {result.Error.Message}", "OK"); });
                }
                else
                {
                    if (result.Status != DocumentConverterJobStatus.Aborted)
                    {
                        await Device.InvokeOnMainThreadAsync(async() =>
                        {
                            try
                            {
                                Exception error = null;
                                LEADDocument convertedDocument = null;
                                // if we have no documents yet or if we are sharing document and burning annotations into the document then this
                                // document is a temp and we shouldn't update the document viewer with it.
                                if (_documents == null || (_shareAfterConversion && _annotationsMode == DocumentConverterAnnotationsMode.Overlay))
                                {
                                    List <Exception> errors = null;
                                    convertedDocument       = LEADDocumentHelper.CreateDocument(result.OutputDocumentFiles, null, null, out errors);
                                    if (errors != null && errors.Count > 0)
                                    {
                                        error = errors[0];
                                    }
                                }
                                else
                                {
                                    convertedDocument = LEADDocumentHelper.ReplaceDocument(oldDocumentId, result.OutputDocumentFiles, _documents, _documentIndexInList, out error);
                                }

                                if (convertedDocument != null)
                                {
                                    if (!(_shareAfterConversion && _annotationsMode == DocumentConverterAnnotationsMode.Overlay))
                                    {
                                        SetDocument(null);
                                        _documentAlreadyConverted = true;
                                        _annObjectsModified       = false;
                                        // Change the SourceDocumentFormat since we converted the document.
                                        SourceDocumentFormat = e.OutputFormat;

                                        SetDocument(convertedDocument);
                                        Document = _documentViewer.Document;
                                    }

                                    if (_shareAfterConversion)
                                    {
                                        _tempFileToDeleteAfterShare = await LEADDocumentHelper.ShareDocument(convertedDocument, null, !string.IsNullOrWhiteSpace(OutputDocumentNameLabel.Text) ? OutputDocumentNameLabel.Text : PageTitle.Text);
                                    }
                                }
                                else if (error != null)
                                {
                                    await Device.InvokeOnMainThreadAsync(async() => { await DisplayAlert("Error", $"Error converting document: {error.Message}", "OK"); });
                                }
                            }
                            catch (Exception ex)
                            {
                                await Device.InvokeOnMainThreadAsync(async() => { await DisplayAlert("Error", $"Error converting document: {ex.Message}", "Ok"); });
                            }
                        });
                    }
                }
            }
            finally
            {
                _annotationsMode = DocumentConverterAnnotationsMode.External;
            }
        }