Пример #1
0
        public bool SavePdf(string fileName, DateTime dateTime, ICollection<IScannedImage> images, PdfSettings pdfSettings, string ocrLanguageCode, Func<int, bool> progressCallback)
        {
            var subFileName = fileNamePlaceholders.SubstitutePlaceholders(fileName, dateTime);
            if (File.Exists(subFileName))
            {
                if (overwritePrompt.ConfirmOverwrite(subFileName) != DialogResult.Yes)
                {
                    return false;
                }
            }

            try
            {
                pdfExporter.Export(subFileName, images, pdfSettings, ocrLanguageCode, progressCallback);
                return true;
            }
            catch (UnauthorizedAccessException)
            {
                errorOutput.DisplayError(MiscResources.DontHavePermission);
            }
            catch (IOException ex)
            {
                Log.ErrorException(MiscResources.ErrorSaving, ex);
                errorOutput.DisplayError(MiscResources.ErrorSaving);
            }
            return false;
        }
Пример #2
0
 public virtual void SetUp()
 {
     pdfExporter = GetPdfExporter();
     settings = new PdfSettings
     {
         Metadata =
         {
             Author = "Test Author",
             Creator = "Test Creator",
             Keywords = "Test Keywords",
             Subject = "Test Subject",
             Title = "Test Title"
         }
     };
     images = new List<Bitmap> {
         ColorBitmap(100, 100, Color.Red),
         ColorBitmap(100, 100, Color.Yellow),
         ColorBitmap(200, 100, Color.Green),
     }.Select(bitmap =>
     {
         using (bitmap)
         {
             return (IScannedImage)new ScannedImage(bitmap, ScanBitDepth.C24Bit, false, -1);
         }
     }).ToList();
     if (!Directory.Exists("test"))
     {
         Directory.CreateDirectory("test");
     }
     if (File.Exists(PDF_PATH))
     {
         File.Delete(PDF_PATH);
     }
 }
Пример #3
0
        public bool Export(string path, IEnumerable <ScannedImage> images, PdfSettings settings, string ocrLanguageCode, Func <int, bool> progressCallback)
        {
            var document = new PdfDocument();

            document.Info.Author   = settings.Metadata.Author;
            document.Info.Creator  = settings.Metadata.Creator;
            document.Info.Keywords = settings.Metadata.Keywords;
            document.Info.Subject  = settings.Metadata.Subject;
            document.Info.Title    = settings.Metadata.Title;

            if (settings.Encryption.EncryptPdf &&
                (!string.IsNullOrEmpty(settings.Encryption.OwnerPassword) || !string.IsNullOrEmpty(settings.Encryption.UserPassword)))
            {
                document.SecuritySettings.DocumentSecurityLevel = PdfDocumentSecurityLevel.Encrypted128Bit;
                if (!string.IsNullOrEmpty(settings.Encryption.OwnerPassword))
                {
                    document.SecuritySettings.OwnerPassword = settings.Encryption.OwnerPassword;
                }
                if (!string.IsNullOrEmpty(settings.Encryption.UserPassword))
                {
                    document.SecuritySettings.UserPassword = settings.Encryption.UserPassword;
                }
                document.SecuritySettings.PermitAccessibilityExtractContent = settings.Encryption.AllowContentCopyingForAccessibility;
                document.SecuritySettings.PermitAnnotations      = settings.Encryption.AllowAnnotations;
                document.SecuritySettings.PermitAssembleDocument = settings.Encryption.AllowDocumentAssembly;
                document.SecuritySettings.PermitExtractContent   = settings.Encryption.AllowContentCopying;
                document.SecuritySettings.PermitFormsFill        = settings.Encryption.AllowFormFilling;
                document.SecuritySettings.PermitFullQualityPrint = settings.Encryption.AllowFullQualityPrinting;
                document.SecuritySettings.PermitModifyDocument   = settings.Encryption.AllowDocumentModification;
                document.SecuritySettings.PermitPrint            = settings.Encryption.AllowPrinting;
            }


            bool useOcr = false;

            if (ocrLanguageCode != null)
            {
                if (ocrEngine.CanProcess(ocrLanguageCode))
                {
                    useOcr = true;
                }
                else
                {
                    Log.Error("OCR files not available for '{0}'.", ocrLanguageCode);
                }
            }

            bool result = useOcr
                ? BuildDocumentWithOcr(progressCallback, document, images, ocrLanguageCode)
                : BuildDocumentWithoutOcr(progressCallback, document, images);

            if (!result)
            {
                return(false);
            }

            PathHelper.EnsureParentDirExists(path);
            document.Save(path);
            return(true);
        }
Пример #4
0
        public bool Export(string path, IEnumerable<ScannedImage> images, PdfSettings settings, string ocrLanguageCode, Func<int, bool> progressCallback)
        {
            var document = new PdfDocument();
            document.Info.Author = settings.Metadata.Author;
            document.Info.Creator = settings.Metadata.Creator;
            document.Info.Keywords = settings.Metadata.Keywords;
            document.Info.Subject = settings.Metadata.Subject;
            document.Info.Title = settings.Metadata.Title;

            if (settings.Encryption.EncryptPdf
                && (!string.IsNullOrEmpty(settings.Encryption.OwnerPassword) || !string.IsNullOrEmpty(settings.Encryption.UserPassword)))
            {
                document.SecuritySettings.DocumentSecurityLevel = PdfDocumentSecurityLevel.Encrypted128Bit;
                if (!string.IsNullOrEmpty(settings.Encryption.OwnerPassword))
                {
                    document.SecuritySettings.OwnerPassword = settings.Encryption.OwnerPassword;
                }
                if (!string.IsNullOrEmpty(settings.Encryption.UserPassword))
                {
                    document.SecuritySettings.UserPassword = settings.Encryption.UserPassword;
                }
                document.SecuritySettings.PermitAccessibilityExtractContent = settings.Encryption.AllowContentCopyingForAccessibility;
                document.SecuritySettings.PermitAnnotations = settings.Encryption.AllowAnnotations;
                document.SecuritySettings.PermitAssembleDocument = settings.Encryption.AllowDocumentAssembly;
                document.SecuritySettings.PermitExtractContent = settings.Encryption.AllowContentCopying;
                document.SecuritySettings.PermitFormsFill = settings.Encryption.AllowFormFilling;
                document.SecuritySettings.PermitFullQualityPrint = settings.Encryption.AllowFullQualityPrinting;
                document.SecuritySettings.PermitModifyDocument = settings.Encryption.AllowDocumentModification;
                document.SecuritySettings.PermitPrint = settings.Encryption.AllowPrinting;
            }

            bool useOcr = false;
            if (ocrLanguageCode != null)
            {
                if (ocrEngine.CanProcess(ocrLanguageCode))
                {
                    useOcr = true;
                }
                else
                {
                    Log.Error("OCR files not available for '{0}'.", ocrLanguageCode);
                }
            }

            bool result = useOcr
                ? BuildDocumentWithOcr(progressCallback, document, images, ocrLanguageCode)
                : BuildDocumentWithoutOcr(progressCallback, document, images);
            if (!result)
            {
                return false;
            }

            PathHelper.EnsureParentDirExists(path);
            document.Save(path);
            return true;
        }
Пример #5
0
 public void TearDown()
 {
     pdfExporter = null;
     settings = null;
     foreach (IScannedImage img in images)
     {
         img.Dispose();
     }
     images = null;
 }
Пример #6
0
        public bool Start(string fileName, DateTime dateTime, ICollection<ScannedImage> images, PdfSettings pdfSettings, string ocrLanguageCode, bool email)
        {
            ProgressTitle = email ? MiscResources.EmailPdfProgress : MiscResources.SavePdfProgress;
            var subFileName = fileNamePlaceholders.SubstitutePlaceholders(fileName, dateTime);
            Status = new OperationStatus
            {
                StatusText = string.Format(MiscResources.SavingFormat, Path.GetFileName(subFileName)),
                MaxProgress = images.Count
            };
            cancel = false;

            if (File.Exists(subFileName))
            {
                if (overwritePrompt.ConfirmOverwrite(subFileName) != DialogResult.Yes)
                {
                    return false;
                }
            }

            thread = threadFactory.StartThread(() =>
            {
                try
                {
                    Status.Success = pdfExporter.Export(subFileName, images, pdfSettings, ocrLanguageCode, i =>
                    {
                        Status.CurrentProgress = i;
                        InvokeStatusChanged();
                        return !cancel;
                    });
                }
                catch (UnauthorizedAccessException)
                {
                    InvokeError(MiscResources.DontHavePermission);
                }
                catch (Exception ex)
                {
                    Log.ErrorException(MiscResources.ErrorSaving, ex);
                    InvokeError(MiscResources.ErrorSaving);
                }
                InvokeFinished();
            });

            return true;
        }
Пример #7
0
 private void UpdateValues(PdfSettings pdfSettings)
 {
     txtDefaultFileName.Text = pdfSettings.DefaultFileName;
     txtTitle.Text = pdfSettings.Metadata.Title;
     txtAuthor.Text = pdfSettings.Metadata.Author;
     txtSubject.Text = pdfSettings.Metadata.Subject;
     txtKeywords.Text = pdfSettings.Metadata.Keywords;
     cbEncryptPdf.Checked = pdfSettings.Encryption.EncryptPdf;
     txtOwnerPassword.Text = pdfSettings.Encryption.OwnerPassword;
     txtUserPassword.Text = pdfSettings.Encryption.UserPassword;
     cbAllowContentCopyingForAccessibility.Checked = pdfSettings.Encryption.AllowContentCopyingForAccessibility;
     cbAllowAnnotations.Checked = pdfSettings.Encryption.AllowAnnotations;
     cbAllowDocumentAssembly.Checked = pdfSettings.Encryption.AllowDocumentAssembly;
     cbAllowContentCopying.Checked = pdfSettings.Encryption.AllowContentCopying;
     cbAllowFormFilling.Checked = pdfSettings.Encryption.AllowFormFilling;
     cbAllowFullQualityPrinting.Checked = pdfSettings.Encryption.AllowFullQualityPrinting;
     cbAllowDocumentModification.Checked = pdfSettings.Encryption.AllowDocumentModification;
     cbAllowPrinting.Checked = pdfSettings.Encryption.AllowPrinting;
 }
Пример #8
0
        public bool Export(string path, IEnumerable<ScannedImage> images, PdfSettings settings, string ocrLanguageCode, Func<int, bool> progressCallback)
        {
            var forced = appConfigManager.Config.ForcePdfCompat;
            var compat = forced == PdfCompat.Default ? settings.Compat : forced;

            var document = new PdfDocument();
            document.Info.Author = settings.Metadata.Author;
            document.Info.Creator = settings.Metadata.Creator;
            document.Info.Keywords = settings.Metadata.Keywords;
            document.Info.Subject = settings.Metadata.Subject;
            document.Info.Title = settings.Metadata.Title;

            if (settings.Encryption.EncryptPdf
                && (!string.IsNullOrEmpty(settings.Encryption.OwnerPassword) || !string.IsNullOrEmpty(settings.Encryption.UserPassword)))
            {
                document.SecuritySettings.DocumentSecurityLevel = PdfDocumentSecurityLevel.Encrypted128Bit;
                if (!string.IsNullOrEmpty(settings.Encryption.OwnerPassword))
                {
                    document.SecuritySettings.OwnerPassword = settings.Encryption.OwnerPassword;
                }
                if (!string.IsNullOrEmpty(settings.Encryption.UserPassword))
                {
                    document.SecuritySettings.UserPassword = settings.Encryption.UserPassword;
                }
                document.SecuritySettings.PermitAccessibilityExtractContent = settings.Encryption.AllowContentCopyingForAccessibility;
                document.SecuritySettings.PermitAnnotations = settings.Encryption.AllowAnnotations;
                document.SecuritySettings.PermitAssembleDocument = settings.Encryption.AllowDocumentAssembly;
                document.SecuritySettings.PermitExtractContent = settings.Encryption.AllowContentCopying;
                document.SecuritySettings.PermitFormsFill = settings.Encryption.AllowFormFilling;
                document.SecuritySettings.PermitFullQualityPrint = settings.Encryption.AllowFullQualityPrinting;
                document.SecuritySettings.PermitModifyDocument = settings.Encryption.AllowDocumentModification;
                document.SecuritySettings.PermitPrint = settings.Encryption.AllowPrinting;
            }
            
            bool useOcr = false;
            if (ocrLanguageCode != null)
            {
                if (ocrEngine.CanProcess(ocrLanguageCode))
                {
                    useOcr = true;
                }
                else
                {
                    Log.Error("OCR files not available for '{0}'.", ocrLanguageCode);
                }
            }

            bool result = useOcr
                ? BuildDocumentWithOcr(progressCallback, document, compat, images, ocrLanguageCode)
                : BuildDocumentWithoutOcr(progressCallback, document, compat, images);
            if (!result)
            {
                return false;
            }

            var now = DateTime.Now;
            document.Info.CreationDate = now;
            document.Info.ModificationDate = now;
            if (compat == PdfCompat.PdfA1B)
            {
                PdfAHelper.SetCidStream(document);
                PdfAHelper.DisableTransparency(document);
            }
            if (compat != PdfCompat.Default)
            {
                PdfAHelper.SetColorProfile(document);
                PdfAHelper.SetCidMap(document);
                PdfAHelper.CreateXmpMetadata(document, compat);
            }

            PathHelper.EnsureParentDirExists(path);
            document.Save(path);
            return true;
        }
Пример #9
0
        private bool DoExportToPdf(string path, bool email)
        {
            var metadata = options.UseSavedMetadata ? pdfSettingsContainer.PdfSettings.Metadata : new PdfMetadata();
            metadata.Creator = ConsoleResources.NAPS2;
            if (options.PdfTitle != null)
            {
                metadata.Title = options.PdfTitle;
            }
            if (options.PdfAuthor != null)
            {
                metadata.Author = options.PdfAuthor;
            }
            if (options.PdfSubject != null)
            {
                metadata.Subject = options.PdfSubject;
            }
            if (options.PdfKeywords != null)
            {
                metadata.Keywords = options.PdfKeywords;
            }

            var encryption = options.UseSavedEncryptConfig ? pdfSettingsContainer.PdfSettings.Encryption : new PdfEncryption();
            if (options.EncryptConfig != null)
            {
                try
                {
                    using (Stream configFileStream = File.OpenRead(options.EncryptConfig))
                    {
                        var serializer = new XmlSerializer(typeof(PdfEncryption));
                        encryption = (PdfEncryption)serializer.Deserialize(configFileStream);
                    }
                }
                catch (Exception ex)
                {
                    Log.ErrorException(ConsoleResources.CouldntLoadEncryptionConfig, ex);
                    errorOutput.DisplayError(ConsoleResources.CouldntLoadEncryptionConfig);
                }
            }

            var pdfSettings = new PdfSettings { Metadata = metadata, Encryption = encryption };

            bool useOcr = !options.DisableOcr && (options.EnableOcr || options.OcrLang != null || userConfigManager.Config.EnableOcr);
            string ocrLanguageCode = useOcr ? (options.OcrLang ?? userConfigManager.Config.OcrLanguageCode) : null;

            var op = operationFactory.Create<SavePdfOperation>();
            int i = -1;
            op.StatusChanged += (sender, args) =>
            {
                if (op.Status.CurrentProgress > i)
                {
                    OutputVerbose(ConsoleResources.ExportingPage, op.Status.CurrentProgress + 1, scannedImages.Count);
                    i = op.Status.CurrentProgress;
                }
            };
            op.Start(path, startTime, scannedImages, pdfSettings, ocrLanguageCode, email);
            op.WaitUntilFinished();
            return op.Status.Success;
        }
Пример #10
0
        public async Task <bool> Export(string path, ICollection <ScannedImage.Snapshot> snapshots, PdfSettings settings, OcrParams ocrParams, ProgressHandler progressCallback, CancellationToken cancelToken)
        {
            return(await Task.Factory.StartNew(() =>
            {
                var forced = appConfigManager.Config.ForcePdfCompat;
                var compat = forced == PdfCompat.Default ? settings.Compat : forced;

                var document = new PdfDocument();
                document.Info.Author = settings.Metadata.Author;
                document.Info.Creator = settings.Metadata.Creator;
                document.Info.Keywords = settings.Metadata.Keywords;
                document.Info.Subject = settings.Metadata.Subject;
                document.Info.Title = settings.Metadata.Title;

                if (settings.Encryption.EncryptPdf &&
                    (!string.IsNullOrEmpty(settings.Encryption.OwnerPassword) || !string.IsNullOrEmpty(settings.Encryption.UserPassword)))
                {
                    document.SecuritySettings.DocumentSecurityLevel = PdfDocumentSecurityLevel.Encrypted128Bit;
                    if (!string.IsNullOrEmpty(settings.Encryption.OwnerPassword))
                    {
                        document.SecuritySettings.OwnerPassword = settings.Encryption.OwnerPassword;
                    }

                    if (!string.IsNullOrEmpty(settings.Encryption.UserPassword))
                    {
                        document.SecuritySettings.UserPassword = settings.Encryption.UserPassword;
                    }

                    document.SecuritySettings.PermitAccessibilityExtractContent = settings.Encryption.AllowContentCopyingForAccessibility;
                    document.SecuritySettings.PermitAnnotations = settings.Encryption.AllowAnnotations;
                    document.SecuritySettings.PermitAssembleDocument = settings.Encryption.AllowDocumentAssembly;
                    document.SecuritySettings.PermitExtractContent = settings.Encryption.AllowContentCopying;
                    document.SecuritySettings.PermitFormsFill = settings.Encryption.AllowFormFilling;
                    document.SecuritySettings.PermitFullQualityPrint = settings.Encryption.AllowFullQualityPrinting;
                    document.SecuritySettings.PermitModifyDocument = settings.Encryption.AllowDocumentModification;
                    document.SecuritySettings.PermitPrint = settings.Encryption.AllowPrinting;
                }

                IOcrEngine ocrEngine = null;
                if (ocrParams?.LanguageCode != null)
                {
                    var activeEngine = ocrManager.ActiveEngine;
                    if (activeEngine == null)
                    {
                        Log.Error("Supported OCR engine not installed.", ocrParams.LanguageCode);
                    }
                    else if (!activeEngine.CanProcess(ocrParams.LanguageCode))
                    {
                        Log.Error("OCR files not available for '{0}'.", ocrParams.LanguageCode);
                    }
                    else
                    {
                        ocrEngine = activeEngine;
                    }
                }

                bool result = ocrEngine != null
                    ? BuildDocumentWithOcr(progressCallback, cancelToken, document, compat, snapshots, ocrEngine, ocrParams)
                    : BuildDocumentWithoutOcr(progressCallback, cancelToken, document, compat, snapshots);
                if (!result)
                {
                    return false;
                }

                var now = DateTime.Now;
                document.Info.CreationDate = now;
                document.Info.ModificationDate = now;
                if (compat == PdfCompat.PdfA1B)
                {
                    PdfAHelper.SetCidStream(document);
                    PdfAHelper.DisableTransparency(document);
                }

                if (compat != PdfCompat.Default)
                {
                    PdfAHelper.SetColorProfile(document);
                    PdfAHelper.SetCidMap(document);
                    PdfAHelper.CreateXmpMetadata(document, compat);
                }

                PathHelper.EnsureParentDirExists(path);
                document.Save(path);
                return true;
            }, TaskCreationOptions.LongRunning));
        }
Пример #11
0
        public bool SavePdf(string fileName, DateTime dateTime, ICollection <IScannedImage> images, PdfSettings pdfSettings, string ocrLanguageCode, Func <int, bool> progressCallback)
        {
            var subFileName = fileNamePlaceholders.SubstitutePlaceholders(fileName, dateTime);

            if (File.Exists(subFileName))
            {
                if (overwritePrompt.ConfirmOverwrite(subFileName) != DialogResult.Yes)
                {
                    return(false);
                }
            }

            try
            {
                pdfExporter.Export(subFileName, images, pdfSettings, ocrLanguageCode, progressCallback);
                return(true);
            }
            catch (UnauthorizedAccessException)
            {
                errorOutput.DisplayError(MiscResources.DontHavePermission);
            }
            catch (IOException ex)
            {
                Log.ErrorException(MiscResources.ErrorSaving, ex);
                errorOutput.DisplayError(MiscResources.ErrorSaving);
            }
            return(false);
        }
Пример #12
0
        public bool Start(string fileName, DateTime dateTime, ICollection <ScannedImage> images, PdfSettings pdfSettings, OcrParams ocrParams, bool email, EmailMessage emailMessage)
        {
            ProgressTitle = email ? MiscResources.EmailPdfProgress : MiscResources.SavePdfProgress;
            var subFileName = fileNamePlaceholders.SubstitutePlaceholders(fileName, dateTime);

            Status = new OperationStatus
            {
                StatusText  = string.Format(MiscResources.SavingFormat, Path.GetFileName(subFileName)),
                MaxProgress = images.Count
            };

            if (Directory.Exists(subFileName))
            {
                // Not supposed to be a directory, but ok...
                subFileName = fileNamePlaceholders.SubstitutePlaceholders(Path.Combine(subFileName, "$(n).pdf"), dateTime);
            }
            if (File.Exists(subFileName))
            {
                if (overwritePrompt.ConfirmOverwrite(subFileName) != DialogResult.Yes)
                {
                    return(false);
                }
            }

            var snapshots = images.Select(x => x.Preserve()).ToList();

            RunAsync(async() =>
            {
                bool result = false;
                try
                {
                    result = await pdfExporter.Export(subFileName, snapshots, pdfSettings, ocrParams, OnProgress, CancelToken);
                }
                catch (UnauthorizedAccessException ex)
                {
                    InvokeError(MiscResources.DontHavePermission, ex);
                }
                catch (IOException ex)
                {
                    if (File.Exists(subFileName))
                    {
                        InvokeError(MiscResources.FileInUse, ex);
                    }
                    else
                    {
                        Log.ErrorException(MiscResources.ErrorSaving, ex);
                        InvokeError(MiscResources.ErrorSaving, ex);
                    }
                }
                catch (Exception ex)
                {
                    Log.ErrorException(MiscResources.ErrorSaving, ex);
                    InvokeError(MiscResources.ErrorSaving, ex);
                }
                finally
                {
                    snapshots.ForEach(s => s.Dispose());
                    GC.Collect();
                }

                if (result && email && emailMessage != null)
                {
                    Status.StatusText      = MiscResources.UploadingEmail;
                    Status.CurrentProgress = 0;
                    Status.MaxProgress     = 1;
                    Status.ProgressType    = OperationProgressType.MB;
                    InvokeStatusChanged();

                    try
                    {
                        result = await emailProviderFactory.Default.SendEmail(emailMessage, OnProgress, CancelToken);
                    }
                    catch (OperationCanceledException)
                    {
                    }
                    catch (Exception ex)
                    {
                        Log.ErrorException(MiscResources.ErrorEmailing, ex);
                        InvokeError(MiscResources.ErrorEmailing, ex);
                    }
                }

                return(result);
            });
            Success.ContinueWith(task =>
            {
                if (task.Result)
                {
                    if (email)
                    {
                        Log.Event(EventType.Email, new EventParams
                        {
                            Name       = MiscResources.EmailPdf,
                            Pages      = snapshots.Count,
                            FileFormat = ".pdf"
                        });
                    }
                    else
                    {
                        Log.Event(EventType.SavePdf, new EventParams
                        {
                            Name       = MiscResources.SavePdf,
                            Pages      = snapshots.Count,
                            FileFormat = ".pdf"
                        });
                    }
                }
            }, TaskContinuationOptions.OnlyOnRanToCompletion);

            return(true);
        }
Пример #13
0
        public bool Start(string fileName, DateTime dateTime, ICollection <ScannedImage> images, PdfSettings pdfSettings, OcrParams ocrParams, bool email, EmailMessage emailMessage)
        {
            ProgressTitle = email ? MiscResources.EmailPdfProgress : MiscResources.SavePdfProgress;
            Status        = new OperationStatus
            {
                MaxProgress = images.Count
            };

            if (Directory.Exists(fileNamePlaceholders.SubstitutePlaceholders(fileName, dateTime)))
            {
                // Not supposed to be a directory, but ok...
                fileName = Path.Combine(fileName, "$(n).pdf");
            }

            var singleFile  = !pdfSettings.SinglePagePdf || images.Count == 1;
            var subFileName = fileNamePlaceholders.SubstitutePlaceholders(fileName, dateTime);

            if (singleFile)
            {
                if (File.Exists(subFileName) && overwritePrompt.ConfirmOverwrite(subFileName) != DialogResult.Yes)
                {
                    return(false);
                }
            }

            var snapshots       = images.Select(x => x.Preserve()).ToList();
            var snapshotsByFile = pdfSettings.SinglePagePdf ? snapshots.Select(x => new[] { x }).ToArray() : new[] { snapshots.ToArray() };

            RunAsync(async() =>
            {
                bool result = false;
                try
                {
                    int digits = (int)Math.Floor(Math.Log10(snapshots.Count)) + 1;
                    int i      = 0;
                    foreach (var snapshotArray in snapshotsByFile)
                    {
                        subFileName       = fileNamePlaceholders.SubstitutePlaceholders(fileName, dateTime, true, i, singleFile ? 0 : digits);
                        Status.StatusText = string.Format(MiscResources.SavingFormat, Path.GetFileName(subFileName));
                        InvokeStatusChanged();
                        if (singleFile && IsFileInUse(subFileName, out var ex))
                        {
                            InvokeError(MiscResources.FileInUse, ex);
                            break;
                        }

                        var progress = singleFile ? OnProgress : (ProgressHandler)((j, k) => { });
                        result       = await pdfExporter.Export(subFileName, snapshotArray, pdfSettings, ocrParams, progress, CancelToken);
                        if (!result || CancelToken.IsCancellationRequested)
                        {
                            break;
                        }
                        emailMessage?.Attachments.Add(new EmailAttachment
                        {
                            FilePath       = subFileName,
                            AttachmentName = Path.GetFileName(subFileName)
                        });
                        if (i == 0)
                        {
                            FirstFileSaved = subFileName;
                        }
                        i++;
                        if (!singleFile)
                        {
                            OnProgress(i, snapshotsByFile.Length);
                        }
                    }
                }
                catch (UnauthorizedAccessException ex)
                {
                    InvokeError(MiscResources.DontHavePermission, ex);
                }
                catch (IOException ex)
                {
                    if (File.Exists(subFileName))
                    {
                        InvokeError(MiscResources.FileInUse, ex);
                    }
                    else
                    {
                        Log.ErrorException(MiscResources.ErrorSaving, ex);
                        InvokeError(MiscResources.ErrorSaving, ex);
                    }
                }
                catch (Exception ex)
                {
                    Log.ErrorException(MiscResources.ErrorSaving, ex);
                    InvokeError(MiscResources.ErrorSaving, ex);
                }
                finally
                {
                    snapshots.ForEach(s => s.Dispose());
                    GC.Collect();
                }

                if (result && !CancelToken.IsCancellationRequested && email && emailMessage != null)
                {
                    Status.StatusText      = MiscResources.UploadingEmail;
                    Status.CurrentProgress = 0;
                    Status.MaxProgress     = 1;
                    Status.ProgressType    = OperationProgressType.MB;
                    InvokeStatusChanged();

                    try
                    {
                        result = await emailProviderFactory.Default.SendEmail(emailMessage, OnProgress, CancelToken);
                    }
                    catch (OperationCanceledException)
                    {
                    }
                    catch (Exception ex)
                    {
                        Log.ErrorException(MiscResources.ErrorEmailing, ex);
                        InvokeError(MiscResources.ErrorEmailing, ex);
                    }
                }

                return(result);
            });
            Success.ContinueWith(task =>
            {
                if (task.Result)
                {
                    if (email)
                    {
                        Log.Event(EventType.Email, new Event
                        {
                            Name       = MiscResources.EmailPdf,
                            Pages      = snapshots.Count,
                            FileFormat = ".pdf"
                        });
                    }
                    else
                    {
                        Log.Event(EventType.SavePdf, new Event
                        {
                            Name       = MiscResources.SavePdf,
                            Pages      = snapshots.Count,
                            FileFormat = ".pdf"
                        });

                        if (pdfSettings.ShowFolder)
                        {
                            String filePath = Path.GetDirectoryName(fileName);
                            Process.Start("explorer.exe", filePath);
                        }
                    }
                }
            }, TaskContinuationOptions.OnlyOnRanToCompletion);

            return(true);
        }
Пример #14
0
        public bool Start(string fileName, DateTime dateTime, ICollection <ScannedImage> images, PdfSettings pdfSettings, string ocrLanguageCode, bool email)
        {
            ProgressTitle = email ? MiscResources.EmailPdfProgress : MiscResources.SavePdfProgress;
            var subFileName = fileNamePlaceholders.SubstitutePlaceholders(fileName, dateTime);

            Status = new OperationStatus
            {
                StatusText  = string.Format(MiscResources.SavingFormat, Path.GetFileName(subFileName)),
                MaxProgress = images.Count
            };
            cancel = false;

            if (Directory.Exists(subFileName))
            {
                // Not supposed to be a directory, but ok...
                subFileName = fileNamePlaceholders.SubstitutePlaceholders(Path.Combine(subFileName, "$(n).pdf"), dateTime);
            }
            if (File.Exists(subFileName))
            {
                if (overwritePrompt.ConfirmOverwrite(subFileName) != DialogResult.Yes)
                {
                    return(false);
                }
            }

            thread = threadFactory.StartThread(() =>
            {
                try
                {
                    Status.Success = pdfExporter.Export(subFileName, images, pdfSettings, ocrLanguageCode, i =>
                    {
                        Status.CurrentProgress = i;
                        InvokeStatusChanged();
                        return(!cancel);
                    });
                }
                catch (UnauthorizedAccessException ex)
                {
                    InvokeError(MiscResources.DontHavePermission, ex);
                }
                catch (IOException ex)
                {
                    if (File.Exists(subFileName))
                    {
                        InvokeError(MiscResources.FileInUse, ex);
                    }
                    else
                    {
                        Log.ErrorException(MiscResources.ErrorSaving, ex);
                        InvokeError(MiscResources.ErrorSaving, ex);
                    }
                }
                catch (Exception ex)
                {
                    Log.ErrorException(MiscResources.ErrorSaving, ex);
                    InvokeError(MiscResources.ErrorSaving, ex);
                }
                GC.Collect();
                InvokeFinished();
            });

            return(true);
        }
Пример #15
0
        public bool Export(string path, IEnumerable <ScannedImage> images, PdfSettings settings, string ocrLanguageCode, Func <int, bool> progressCallback)
        {
            var document = new PdfDocument();

            document.Info.Author   = settings.Metadata.Author;
            document.Info.Creator  = settings.Metadata.Creator;
            document.Info.Keywords = settings.Metadata.Keywords;
            document.Info.Subject  = settings.Metadata.Subject;
            document.Info.Title    = settings.Metadata.Title;

            if (settings.Encryption.EncryptPdf &&
                (!string.IsNullOrEmpty(settings.Encryption.OwnerPassword) || !string.IsNullOrEmpty(settings.Encryption.UserPassword)))
            {
                document.SecuritySettings.DocumentSecurityLevel = PdfDocumentSecurityLevel.Encrypted128Bit;
                if (!string.IsNullOrEmpty(settings.Encryption.OwnerPassword))
                {
                    document.SecuritySettings.OwnerPassword = settings.Encryption.OwnerPassword;
                }
                if (!string.IsNullOrEmpty(settings.Encryption.UserPassword))
                {
                    document.SecuritySettings.UserPassword = settings.Encryption.UserPassword;
                }
                document.SecuritySettings.PermitAccessibilityExtractContent = settings.Encryption.AllowContentCopyingForAccessibility;
                document.SecuritySettings.PermitAnnotations      = settings.Encryption.AllowAnnotations;
                document.SecuritySettings.PermitAssembleDocument = settings.Encryption.AllowDocumentAssembly;
                document.SecuritySettings.PermitExtractContent   = settings.Encryption.AllowContentCopying;
                document.SecuritySettings.PermitFormsFill        = settings.Encryption.AllowFormFilling;
                document.SecuritySettings.PermitFullQualityPrint = settings.Encryption.AllowFullQualityPrinting;
                document.SecuritySettings.PermitModifyDocument   = settings.Encryption.AllowDocumentModification;
                document.SecuritySettings.PermitPrint            = settings.Encryption.AllowPrinting;
            }

            int i = 0;

            foreach (ScannedImage scannedImage in images)
            {
                using (Stream stream = scannedImage.GetImageStream())
                    using (var img = new Bitmap(stream))
                    {
                        if (!progressCallback(i))
                        {
                            return(false);
                        }

                        OcrResult ocrResult = null;
                        if (ocrLanguageCode != null)
                        {
                            if (ocrEngine.CanProcess(ocrLanguageCode))
                            {
                                ocrResult = ocrEngine.ProcessImage(img, ocrLanguageCode);
                            }
                            else
                            {
                                Log.Error("OCR files not available for '{0}'.", ocrLanguageCode);
                            }
                        }

                        float   hAdjust    = 72 / img.HorizontalResolution;
                        float   vAdjust    = 72 / img.VerticalResolution;
                        double  realWidth  = img.Width * hAdjust;
                        double  realHeight = img.Height * vAdjust;
                        PdfPage newPage    = document.AddPage();
                        newPage.Width  = (int)realWidth;
                        newPage.Height = (int)realHeight;
                        using (XGraphics gfx = XGraphics.FromPdfPage(newPage))
                        {
                            if (ocrResult != null)
                            {
                                var tf = new XTextFormatter(gfx);
                                foreach (var element in ocrResult.Elements)
                                {
                                    var adjustedBounds   = AdjustBounds(element.Bounds, hAdjust, vAdjust);
                                    var adjustedFontSize = CalculateFontSize(element.Text, adjustedBounds, gfx);
                                    var font             = new XFont("Times New Roman", adjustedFontSize, XFontStyle.Regular,
                                                                     new XPdfFontOptions(PdfFontEncoding.Unicode));
                                    tf.DrawString(element.Text, font, XBrushes.Transparent, adjustedBounds);
                                }
                            }
                            gfx.DrawImage(img, 0, 0, (int)realWidth, (int)realHeight);
                        }
                        i++;
                    }
            }
            PathHelper.EnsureParentDirExists(path);
            document.Save(path);
            return(true);
        }
Пример #16
0
        private void btnOK_Click(object sender, EventArgs e)
        {
            var pdfSettings = new PdfSettings
            {
                DefaultFileName = txtDefaultFileName.Text,
                IASAFileValidation = cbIASAFileValidation.Checked,
                Metadata =
                {
                    Title = txtTitle.Text,
                    Author = txtAuthor.Text,
                    Subject = txtSubject.Text,
                    Keywords = txtKeywords.Text
                },
                Encryption =
                {
                    EncryptPdf = cbEncryptPdf.Checked,
                    OwnerPassword = txtOwnerPassword.Text,
                    UserPassword = txtUserPassword.Text,
                    AllowContentCopyingForAccessibility = cbAllowContentCopyingForAccessibility.Checked,
                    AllowAnnotations = cbAllowAnnotations.Checked,
                    AllowDocumentAssembly = cbAllowDocumentAssembly.Checked,
                    AllowContentCopying = cbAllowContentCopying.Checked,
                    AllowFormFilling = cbAllowFormFilling.Checked,
                    AllowFullQualityPrinting = cbAllowFullQualityPrinting.Checked,
                    AllowDocumentModification = cbAllowDocumentModification.Checked,
                    AllowPrinting = cbAllowPrinting.Checked
                }
            };

            pdfSettingsContainer.PdfSettings = pdfSettings;
            userConfigManager.Config.PdfSettings = cbRememberSettings.Checked ? pdfSettings : null;
            userConfigManager.Save();

            Close();
        }
Пример #17
0
        public bool Export(string path, IEnumerable<ScannedImage> images, PdfSettings settings, string ocrLanguageCode, Func<int, bool> progressCallback)
        {
            var document = new PdfDocument();
            document.Info.Author = settings.Metadata.Author;
            document.Info.Creator = settings.Metadata.Creator;
            document.Info.Keywords = settings.Metadata.Keywords;
            document.Info.Subject = settings.Metadata.Subject;
            document.Info.Title = settings.Metadata.Title;

            if (settings.Encryption.EncryptPdf
                && (!string.IsNullOrEmpty(settings.Encryption.OwnerPassword) || !string.IsNullOrEmpty(settings.Encryption.UserPassword)))
            {
                document.SecuritySettings.DocumentSecurityLevel = PdfDocumentSecurityLevel.Encrypted128Bit;
                if (!string.IsNullOrEmpty(settings.Encryption.OwnerPassword))
                {
                    document.SecuritySettings.OwnerPassword = settings.Encryption.OwnerPassword;
                }
                if (!string.IsNullOrEmpty(settings.Encryption.UserPassword))
                {
                    document.SecuritySettings.UserPassword = settings.Encryption.UserPassword;
                }
                document.SecuritySettings.PermitAccessibilityExtractContent = settings.Encryption.AllowContentCopyingForAccessibility;
                document.SecuritySettings.PermitAnnotations = settings.Encryption.AllowAnnotations;
                document.SecuritySettings.PermitAssembleDocument = settings.Encryption.AllowDocumentAssembly;
                document.SecuritySettings.PermitExtractContent = settings.Encryption.AllowContentCopying;
                document.SecuritySettings.PermitFormsFill = settings.Encryption.AllowFormFilling;
                document.SecuritySettings.PermitFullQualityPrint = settings.Encryption.AllowFullQualityPrinting;
                document.SecuritySettings.PermitModifyDocument = settings.Encryption.AllowDocumentModification;
                document.SecuritySettings.PermitPrint = settings.Encryption.AllowPrinting;
            }

            int i = 0;
            foreach (ScannedImage scannedImage in images)
            {
                using (Stream stream = scannedImage.GetImageStream())
                using (var img = new Bitmap(stream))
                {
                    if (!progressCallback(i))
                    {
                        return false;
                    }

                    OcrResult ocrResult = null;
                    if (ocrLanguageCode != null && ocrEngine.CanProcess(ocrLanguageCode))
                    {
                        ocrResult = ocrEngine.ProcessImage(img, ocrLanguageCode);
                    }

                    float hAdjust = 72 / img.HorizontalResolution;
                    float vAdjust = 72 / img.VerticalResolution;
                    double realWidth = img.Width * hAdjust;
                    double realHeight = img.Height * vAdjust;
                    PdfPage newPage = document.AddPage();
                    newPage.Width = (int)realWidth;
                    newPage.Height = (int)realHeight;
                    using (XGraphics gfx = XGraphics.FromPdfPage(newPage))
                    {
                        if (ocrResult != null)
                        {
                            var tf = new XTextFormatter(gfx);
                            foreach (var element in ocrResult.Elements)
                            {
                                var adjustedBounds = AdjustBounds(element.Bounds, hAdjust, vAdjust);
                                var adjustedFontSize = CalculateFontSize(element.Text, adjustedBounds, gfx);
                                var font = new XFont("Times New Roman", adjustedFontSize, XFontStyle.Regular,
                                    new XPdfFontOptions(PdfFontEncoding.Unicode));
                                tf.DrawString(element.Text, font, XBrushes.Transparent, adjustedBounds);
                            }
                        }
                        gfx.DrawImage(img, 0, 0, (int)realWidth, (int)realHeight);
                    }
                    i++;
                }
            }
            document.Save(path);
            return true;
        }
Пример #18
0
        private bool DoExportToPdf(string path)
        {
            var metadata = options.UseSavedMetadata ? pdfSettingsContainer.PdfSettings.Metadata : new PdfMetadata();
            metadata.Creator = ConsoleResources.NAPS2;
            if (options.PdfTitle != null)
            {
                metadata.Title = options.PdfTitle;
            }
            if (options.PdfAuthor != null)
            {
                metadata.Author = options.PdfAuthor;
            }
            if (options.PdfSubject != null)
            {
                metadata.Subject = options.PdfSubject;
            }
            if (options.PdfKeywords != null)
            {
                metadata.Keywords = options.PdfKeywords;
            }

            var encryption = options.UseSavedEncryptConfig ? pdfSettingsContainer.PdfSettings.Encryption : new PdfEncryption();
            if (options.EncryptConfig != null)
            {
                try
                {
                    using (Stream configFileStream = File.OpenRead(options.EncryptConfig))
                    {
                        var serializer = new XmlSerializer(typeof(PdfEncryption));
                        encryption = (PdfEncryption)serializer.Deserialize(configFileStream);
                    }
                }
                catch (Exception ex)
                {
                    Log.ErrorException(ConsoleResources.CouldntLoadEncryptionConfig, ex);
                    errorOutput.DisplayError(ConsoleResources.CouldntLoadEncryptionConfig);
                }
            }

            var pdfSettings = new PdfSettings { Metadata = metadata, Encryption = encryption };

            bool useOcr = !options.DisableOcr && (options.EnableOcr || options.OcrLang != null || userConfigManager.Config.EnableOcr);
            string ocrLanguageCode = useOcr ? (options.OcrLang ?? userConfigManager.Config.OcrLanguageCode) : null;

            return pdfSaver.SavePdf(path, startTime, scannedImages, pdfSettings, ocrLanguageCode, i =>
            {
                OutputVerbose(ConsoleResources.ExportingPage, i, scannedImages.Count);
                return true;
            });
        }