private void ClearFilesCommand_Execute()
        {
            var files = PdfFiles.Where(
                file => SelectedPdfFiles.All(f => f != file));

            PdfFiles = new ObservableCollection <string>(files);
        }
        private bool ViewIsValid()
        {
            bool   isValid  = false;
            string errorMsg = string.Empty;

            ClearViewErrors();
            if (PdfFiles.Count < 2)
            {
                ProgressStatus = "Please make sure you select at least two PDF files to merge using the + button or [ Ins ].";
            }
            else if (PdfFiles.Where(file => file.IsLocked == true).Any())
            {
                ProgressStatus = "Please unlock any locked PDF file by clicking the lock button in the list or [ Ctrl+U ].";
            }
            else
            {
                if (FileHelpers.FileNameIsValid(BaseFileName, out errorMsg) != Define.Success)
                {
                    SetErrors("BaseFileName", new List <ValidationResult>()
                    {
                        new ValidationResult(false, errorMsg)
                    });
                }

                if (FileHelpers.FolderIsValid(DestinationFolder, out errorMsg) != Define.Success)
                {
                    SetErrors("DestinationFolder", new List <ValidationResult>()
                    {
                        new ValidationResult(false, errorMsg)
                    });
                }
                isValid = !HasErrors;
            }
            return(isValid);
        }
Example #3
0
        private void GenerateXlsxCommand_Execute()
        {
            try
            {
                SetBusy(true);
                var saveFileDialog = new SaveFileDialog
                {
                    Filter = "XLSX Files (*.xlsx) | *.xlsx"
                };
                if (saveFileDialog.ShowDialog() == true)
                {
                    var fileName  = saveFileDialog.FileName;
                    var documents = PdfFiles.Select(FordParser.Parser.FordParser.GetFordDocument).ToArray();

                    var writer = new PoExcelWriter(fileName, documents);
                    writer.Write();

                    System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo()
                    {
                        FileName        = Path.GetDirectoryName(saveFileDialog.FileName),
                        UseShellExecute = true,
                        Verb            = "open"
                    });
                }
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message);
                Console.WriteLine(exception);
            }
            finally
            {
                SetBusy(false);
            }
        }
        internal static void Reinit()
        {
            PdfFiles.Clear();
            ZipFiles.Clear();

            var pdfMimeTypes = MimeTypeId.Pdf.GetMimeTypes();

            for (var i = 0; i < InitialPdfCount; i++)
            {
                PdfFiles.Add(new UploadedFileInfo
                {
                    Content  = null,
                    Name     = string.Format("PdfFile{0}", i),
                    MimeType = pdfMimeTypes[0],
                    Size     = 1024
                });
            }

            var zipMimeTypes = MimeTypeId.Zip.GetMimeTypes();

            for (var i = 0; i < InitialZipCount; i++)
            {
                ZipFiles.Add(new UploadedFileInfo
                {
                    Name     = string.Format("ZipFile{0}", i),
                    Content  = null,
                    MimeType = zipMimeTypes[0],
                    Size     = 1024
                });
            }
        }
        private void ExtractImagesCommand_Execute()
        {
            try
            {
                SetBusy(true);
                var dialog = new FolderBrowserDialog();
                var result = dialog.ShowDialog();

                if (result == DialogResult.OK)
                {
                    var pdfFilePaths   = PdfFiles.ToArray();
                    var imageExtractor = new ImageExtractor(pdfFilePaths, dialog.SelectedPath);

                    imageExtractor.Extract();

                    System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo
                    {
                        FileName        = dialog.SelectedPath,
                        UseShellExecute = true,
                        Verb            = "open"
                    });
                }
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.Message);
                Console.WriteLine(exception);
            }
            finally
            {
                SetBusy(false);
            }
        }
Example #6
0
        private void OnSplitPdfCmdExecute()
        {
            string          destinationPath = string.Empty;
            PageRangeParser pageRangeParser = null;

            IsBusy = true;
            bool isValid = ViewIsValid(out pageRangeParser);

            if (isValid)
            {
                if (SaveType == SaveOptions.UseSourceFolder)
                {
                    destinationPath = string.Format("{0}\\{1}",
                                                    PdfFiles.First().Info.DirectoryName, BaseFileName);
                }
                else if (SaveType == SaveOptions.UseCustomFolder)
                {
                    destinationPath = string.Format("{0}\\{1}",
                                                    DestinationFolder, BaseFileName);
                }

                splitBackgroundWorker.RunWorkerAsync(new object[] { PdfFiles.First(),
                                                                    pageRangeParser, destinationPath, OverwriteFile });
            }
            else
            {
                IsBusy = false;
            }
        }
        private void LoadPdfWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            string result = string.Empty;

            if (e.Error != null)
            {
                result = string.Format("An unexpected error occured while loading PDF file: {0}.", e.Error.Message);
            }
            else
            {
                object[] args = (object[])e.Result;
                if (string.IsNullOrEmpty(args[0].ToString()))
                {
                    PdfFiles.Add(args[1] as PdfFile);
                    SelectedFile = PdfFiles.First();
                }
                else
                {
                    result = args[0].ToString();
                }
            }

            Status = result;
            IsBusy = false;
        }
Example #8
0
        public async Task <bool> MergePdfs()
        {
            var fileList = PdfFiles
                           .Select(pf => pf.File)
                           .ToList();

            var byteList = new List <byte[]>();

            foreach (var file in fileList)
            {
                byte[] byteArray;
                using (var fileStream = await file.OpenStreamForReadAsync())
                {
                    using (var memoryStream = new MemoryStream())
                    {
                        fileStream.CopyTo(memoryStream);
                        byteArray = memoryStream.ToArray();
                    }
                }
                byteList.Add(byteArray);
            }

            var mergedPdfBytes = pdfMergeUtility.MergePdfs(byteList);

            var savePicker = new FileSavePicker
            {
                SuggestedStartLocation = PickerLocationId.DocumentsLibrary,
                SuggestedFileName      = "Merged Pdf"
            };

            savePicker.FileTypeChoices.Add("Pdf", new List <string>()
            {
                ".pdf"
            });

            var mergedFile = await savePicker.PickSaveFileAsync();

            if (mergedFile != null)
            {
                // Prevent updates to the remote version of the file until
                // are changes are finished and CompleteUpdatesAsync is called
                CachedFileManager.DeferUpdates(mergedFile);

                await FileIO.WriteBytesAsync(mergedFile, mergedPdfBytes);

                // Let Windows know that changes to the file are finished so
                // that the remote version of the file can be updated.
                var status = await CachedFileManager.CompleteUpdatesAsync(mergedFile);

                if (status == Windows.Storage.Provider.FileUpdateStatus.Complete)
                {
                    LatestMergedFile = mergedFile;
                    return(true);
                }
            }
            return(false);
        }
Example #9
0
        private void OnOpenFileCmdExecute()
        {
            WebBrowserView      webBrowserView      = new WebBrowserView();
            WebBrowserViewModel webBrowserViewModel = new WebBrowserViewModel(PdfFiles.First().Info.FullName);

            webBrowserView.DataContext = webBrowserViewModel;
            webBrowserView.Owner       = App.Current.MainWindow;
            webBrowserView.Show();
        }
Example #10
0
        public PdfFile LoadLatestMerge()
        {
            if (LatestMergedFile == null)
            {
                return(null);
            }

            PdfFiles.Clear();
            return(AddPdf(LatestMergedFile));
        }
Example #11
0
        private PdfFile AddPdf(StorageFile file)
        {
            var pdfFile = new PdfFile
            {
                File = file
            };

            PdfFiles.Add(pdfFile);

            return(pdfFile);
        }
        private bool OnScrollDownCmdCanExecute()
        {
            bool canExecute = false;

            if (PdfFiles.Count > 1 &&
                SelectedFile != null &&
                PdfFiles.IndexOf(SelectedFile) < PdfFiles.Count - 1)
            {
                canExecute = true;
            }
            return(canExecute);
        }
 private bool OnMoveDownCmdCanExecute()
 {
     if (!IsBusy &&
         SelectedFile != null &&
         PdfFiles.IndexOf(SelectedFile) < PdfFiles.Count - 1)
     {
         return(true);
     }
     else
     {
         return(false);
     }
 }
Example #14
0
        public void RemoveSelectedFile()
        {
            if (SelectedFile == null)
            {
                System.Windows.MessageBox.Show("Please select a file to remove.", "No File Selected");
                return;
            }
            var pdf = PdfFiles.First(c => c == SelectedFile.Path);

            PdfFiles.Remove(pdf);
            PdfFilesList.Remove(SelectedFile);
            SelectedFile = null;
        }
        private void MoveUpAndDown(int direction)
        {
            IsBusy = true;
            int index = PdfFiles.IndexOf(SelectedFile);

            App.Current.Dispatcher.Invoke(delegate
            {
                PdfFiles.Move(index, index + direction);
            });

            //Needed to trigger Selection Changed event In datagrid
            SelectedFile = null;
            SelectedFile = PdfFiles[index + direction];
            IsBusy       = false;
        }
        private void OpenFilesCommand_Execute()
        {
            var dialog = new OpenFileDialog
            {
                Multiselect = true,
                Filter      = "PDF files (*.pdf) | *.pdf"
            };

            if (dialog.ShowDialog() == true)
            {
                PdfFiles.AddRange(dialog.FileNames);
            }

            ExtractImagesCommand?.RaiseCanExecuteChanged();
            ClearFilesCommand?.RaiseCanExecuteChanged();
        }
Example #17
0
        private void OnUnlockCmdExecute()
        {
            PdfLoginView pdfLoginView = new PdfLoginView();

            pdfLoginView.DataContext = new PdfLoginViewModel(pdfLoginView, PdfFiles.First());
            pdfLoginView.Owner       = App.Current.MainWindow;
            bool?dialogResult = pdfLoginView.ShowDialog();

            if (dialogResult.HasValue && dialogResult.Value)
            {
                ProgressStatus = "PDF file successfully unlocked.";
            }
            else
            {
                ProgressStatus = "Failed to unlock PDF file.";
            }
        }
        private void OnRemoveFileCmdExecute()
        {
            SelectedFile.Close();
            int index = PdfFiles.IndexOf(SelectedFile);

            App.Current.Dispatcher.Invoke(delegate { PdfFiles.RemoveAt(index); });
            if (PdfFiles.Count > index)
            {
                SelectedFile = PdfFiles[index];
            }
            else if (PdfFiles.Any())
            {
                SelectedFile = PdfFiles[index - 1];
            }
            else
            {
                SelectedFile = null;
            }
        }
        private void FileWorkerRunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            string result = string.Empty;

            SelectedFile = null;

            if (e.Error != null)
            {
                result = "An error was thrown while loading PDF file(s): " + e.Error.ToString();
                if (PdfFiles.Any())
                {
                    SelectedFile = PdfFiles.Last();
                }
            }
            else
            {
                object[] args         = (object[])e.Result;
                int      skippedFiles = int.Parse(args[0].ToString());
                int      insertIndex  = int.Parse(args[1].ToString());

                if (PdfFiles.Any())
                {
                    if (insertIndex == -1)
                    {
                        SelectedFile = PdfFiles.Last();
                    }
                    else if (insertIndex > 0 && insertIndex < PdfFiles.Count)
                    {
                        SelectedFile = PdfFiles[insertIndex - 1];
                    }
                }

                if (skippedFiles > 0)
                {
                    result = string.Format("Due to PDF file errors, {0} PDF files could not be loaded.", skippedFiles);
                }
            }

            ProgressStatus             = result;
            ProgressBarIsIndeterminate = false;
            IsBusy = false;
        }
Example #20
0
        private void FileWorkerDoWork(object sender, DoWorkEventArgs e)
        {
            string fileName = e.Argument.ToString();

            PdfFile pdfFile = new PdfFile(fileName);
            int     status  = pdfFile.Open();

            if (status == Define.Success ||
                status == Define.BadPasswordException)
            {
                App.Current.Dispatcher.Invoke(delegate()
                {
                    PdfFiles.Add(pdfFile);
                    SelectedFile = PdfFiles.First();
                });
            }
            else
            {
                e.Result = pdfFile.ErrorMsg;
            }
        }
Example #21
0
        public void BrowseForFiles()
        {
            PdfFilesList = new List <PdfFileModel>();
            SelectedFile = null;
            var filesDialog = Common.BrowseForFiles(true, "PDF (*.pdf)|*.pdf|Excel (*.xlsx)|*.xlsx|PNG (*.png)|*.png");

            if (filesDialog.ShowDialog() != true)
            {
                return;
            }
            foreach (var o in filesDialog.FileNames)
            {
                PdfFiles.Add(o);
                var info = new FileInfo(o);
                PdfFilesList.Add(new PdfFileModel
                {
                    Name    = info.Name,
                    Path    = info.FullName,
                    Matches = 0
                });
            }
            FilesViewSource = new CollectionView(PdfFilesList);
        }
        private void FileWorkerDoWork(object sender, DoWorkEventArgs e)
        {
            int     insertIndex = -1, skippedFiles = 0;
            PdfFile pdfFile = null;

            object[] args      = (object[])e.Argument;
            string[] fileNames = (string[])args[0];
            if (args.Length == 2)
            {
                insertIndex = int.Parse(args[1].ToString());
            }

            foreach (string fileName in fileNames)
            {
                fileBackgroundWorker.ReportProgress(0, string.Format("Loading PDF file: {0}", fileName));
                pdfFile = new PdfFile(fileName);
                int status = pdfFile.Open();

                if (status == Define.Success || status == Define.BadPasswordException)
                {
                    if (insertIndex == -1)
                    {
                        App.Current.Dispatcher.Invoke(delegate() { PdfFiles.Add(pdfFile); });
                    }
                    else
                    {
                        App.Current.Dispatcher.Invoke(delegate() { PdfFiles.Insert(insertIndex, pdfFile); });
                        insertIndex++;
                    }
                }
                else
                {
                    skippedFiles++;
                }
            }
            e.Result = new object[] { skippedFiles, insertIndex };
        }
Example #23
0
        private bool ViewIsValid(out PageRangeParser pageRangeParser)
        {
            bool   isValid  = false;
            string errorMsg = string.Empty;

            pageRangeParser = null;

            ClearViewErrors();
            if (PdfFiles.Count == 0)
            {
                ProgressStatus = "Please select a PDF file to split using the + button or [ Ins ].";
            }
            else if (PdfFiles.First().IsLocked)
            {
                ProgressStatus = "Please unlock the PDF file by clicking the lock button in the list or [ Ctrl+U ].";
            }
            else
            {
                if (FileHelpers.FileNameIsValid(BaseFileName, out errorMsg) != Define.Success)
                {
                    SetErrors("BaseFileName", new List <ValidationResult>()
                    {
                        new ValidationResult(false, errorMsg)
                    });
                }

                if (SaveType == SaveOptions.UseCustomFolder &&
                    FileHelpers.FolderIsValid(DestinationFolder, out errorMsg) != Define.Success)
                {
                    SetErrors("DestinationFolder", new List <ValidationResult>()
                    {
                        new ValidationResult(false, errorMsg)
                    });
                }

                errorMsg = string.Empty;
                if (SplitMethod == DocSplitMethod.Interval)
                {
                    if (string.IsNullOrEmpty(PageInterval))
                    {
                        errorMsg = "Split page interval is required.";
                    }
                    else
                    {
                        pageRangeParser = new PageRangeParser(PdfFiles.First().Reader.NumberOfPages, int.Parse(PageInterval));
                        if (pageRangeParser.Validate() != Define.Success)
                        {
                            errorMsg = pageRangeParser.ErrorMsg;
                        }
                    }

                    if (errorMsg != string.Empty)
                    {
                        SetErrors("PageInterval", new List <ValidationResult>()
                        {
                            new ValidationResult(false, errorMsg)
                        });
                    }
                }
                else if (SplitMethod == DocSplitMethod.Range)
                {
                    if (string.IsNullOrEmpty(PageRange))
                    {
                        errorMsg = "Split page range is required.";
                    }
                    else
                    {
                        pageRangeParser = new PageRangeParser(PdfFiles.First().Reader.NumberOfPages, PageRange);
                        if (pageRangeParser.Validate() != Define.Success)
                        {
                            errorMsg = pageRangeParser.ErrorMsg;
                        }
                    }

                    if (errorMsg != string.Empty)
                    {
                        SetErrors("PageRange", new List <ValidationResult>()
                        {
                            new ValidationResult(false, errorMsg)
                        });
                    }
                }

                isValid = !HasErrors;
            }
            return(isValid);
        }
        private void OnScrollDownCmdExecute()
        {
            int index = PdfFiles.IndexOf(SelectedFile);

            SelectedFile = PdfFiles.ElementAt(++index);
        }
Example #25
0
        public Task ProcessSelectedDocumentsAsync(IProgress <TaskProgress> prog, CancellationToken token, List <DocumentTypes> types, EtaCalculator pc, List <FileInfo> files)
        {
            var currentFile = 0.0;
            var fileCount   = Convert.ToDouble(files.Count);

            return(Task.Run(() =>
            {
                foreach (var file in files)
                {
                    var criteriaMatches = types.Select(o => new CriteriaMatchModel {
                        DocumentType = o
                    }).ToList();
                    using (var observedImage = CvInvoke.Imread(file.FullName))
                    {
                        Parallel.ForEach(_criteriaImages, (criteriaImage) =>
                        {
                            var criteriaFile = criteriaImage.Info;
                            var criteriaFileSplit = criteriaFile.Name.Split('-');
                            var type = types.First(c => c.DocumentType == criteriaFileSplit[0]);
                            var score = Classify(criteriaImage, observedImage);
                            var existingModel = criteriaMatches.First(c => c.DocumentType == type);
                            existingModel.Score += score;
                            existingModel.PdfFile = file.FullName;
                        });
                    }
                    if (token.IsCancellationRequested)
                    {
                        return;
                    }
                    var matchedCriteria = criteriaMatches.First(c => c.Score == criteriaMatches.Max(p => p.Score));
                    Console.WriteLine($"Score: {matchedCriteria.Score}");
                    if (matchedCriteria.Score >= matchedCriteria.DocumentType.AverageScore)
                    {
                        DocumentSelectionList.First(c => c.DocumentType == matchedCriteria.DocumentType.DocumentType).Matches += 1;
                        System.Windows.Application.Current.Dispatcher.Invoke(() =>
                        {
                            SelectionViewSource.Refresh();
                        });
                        var matchedFileName = file.Name.Substring(0, file.Name.Length - 4).Split('.')[0];
                        var matchedFile = PdfFiles.First(c => c.Contains(matchedFileName));
                        var matchedFileExtension = matchedFile.Substring(matchedFile.Length - 3);
                        if (matchedFileExtension.Equals("pdf", StringComparison.CurrentCultureIgnoreCase))
                        {
                            ExtractPageFromPdf(file, matchedCriteria.DocumentType.DocumentType, NamingModels);
                        }
                        else
                        {
                            CreatePdfFromImage(file, matchedCriteria.DocumentType.DocumentType, NamingModels);
                        }
                    }
                    currentFile++;
                    var rawProgress = (currentFile / fileCount);
                    var progress = rawProgress * 100;
                    var progressFloat = (float)rawProgress;
                    pc.Update(progressFloat);
                    if (pc.ETAIsAvailable)
                    {
                        var timeRemaining = pc.ETR.ToString(@"dd\.hh\:mm\:ss");
                        prog.Report(new TaskProgress
                        {
                            ProgressText = file.Name,
                            ProgressPercentage = progress,
                            ProgressText2 = timeRemaining
                        });
                    }
                    else
                    {
                        prog.Report(new TaskProgress
                        {
                            ProgressText = file.Name,
                            ProgressPercentage = progress,
                            ProgressText2 = "Calculating..."
                        });
                    }
                }
            }));
        }
Example #26
0
 private void OnRemoveFileCmdExecute()
 {
     SelectedFile.Close();
     App.Current.Dispatcher.Invoke(delegate() { PdfFiles.RemoveAt(0); });
     SelectedFile = null;
 }
 private void OnRemoveFileCmdExecute()
 {
     PdfFiles.Clear();
     SelectedFile            = null;
     ValidationModeRequested = ValidationMode.None;
 }