private void selectFolderInScratch(object o)
        {
            // PROBLEM HERE: CRASHES IF SelectedFolderInScratch is null;

            // close overlay
            ModalOverlayIsVisible          = false;
            ScratchFolderSelectorIsVisible = false;

            UpdateLabelPdf = "";

            // clear out existing files
            Files?.Clear(); UpdateLabel = string.Empty;
            if (null == FilesConvertedToPdf)
            {
                FilesConvertedToPdf = new ObservableCollection <CockleFilePdf>();
            }
            else
            {
                FilesConvertedToPdf.Clear(); DestinationFolderConvertedFiles = string.Empty;
            }

            if (null == SelectedFolderInScratch)
            {
                return;
            }

            var files = System.IO.Directory.EnumerateFiles(SelectedFolderInScratch.FolderName).ToList();

            files.ForEach(x =>
            {
                FilesConvertedToPdf.Add(new CockleFilePdf(x, SourceFileTypeEnum.Unrecognized));
            });
            DestinationFolderConvertedFiles =
                System.IO.Path.GetDirectoryName(FilesConvertedToPdf.FirstOrDefault().FullName);
        }
        private async void convertToPdfA(object o)
        {
            UpdateLabelPdf = "";

            try
            {
                var new_cockleFilePdf = await Task.Run(() =>
                {
                    var conversion = new ConvertToPdfa(SelectedPdfFile);
                    return(conversion.PdfaCockleFilePdf);
                });

                FilesConvertedToPdf.Add(new_cockleFilePdf);
                FilesConvertedToPdf.Remove(SelectedPdfFile);
                SelectedPdfFile = new_cockleFilePdf;

                UpdateLabelPdf = "PDF/A file successfully converted.";
            }
            catch (Exception ex)
            {
                UpdateLabelPdf = ex.Message;
                //UpdateLabelPdf = $"File from '{FilesConvertedToPdf.FirstOrDefault().TicketPlusAttorney}' failed PDF/A conversion.";
                System.Diagnostics.Debug.WriteLine(ex.Message);
            }
        }
        private async void imposeCircuitCourtCover_11x19()
        {
            ModalOverlayIsVisible = false;
            SpecialImpositionsOverlayIsVisible = false;
            UpdateLabelPdf = "";
            try
            {
                // get ticket, atty:
                var ticket_atty = FilesConvertedToPdf.Where(x => !string.IsNullOrEmpty(x.TicketPlusAttorney)).Select(x => x.TicketPlusAttorney).FirstOrDefault();


                Models.Imposition.NUpCircuitCourtCoverOn11x19 nupfile = null;
                await System.Threading.Tasks.Task.Run(() =>
                {
                    nupfile = new Models.Imposition.NUpCircuitCourtCoverOn11x19(SelectedPdfFile);
                });

                if (null != nupfile && System.IO.File.Exists(nupfile.NewFileCreated.FullName))
                {
                    if (!FilesConvertedToPdf.Any(x => x.FullName == nupfile.NewFileCreated.FullName))
                    {
                        FilesConvertedToPdf.Add(nupfile.NewFileCreated);
                        UpdateLabelPdf = "Created: " + System.IO.Path.GetFileNameWithoutExtension(nupfile.NewFileCreated.FullName);
                    }
                }
            }
            catch (Exception ex)
            {
                UpdateLabelPdf = ex.Message;
            }
        }
        private void watcherPdfFolderChanged(object sender, System.IO.FileSystemEventArgs e)
        {
            try
            {
                if (!string.IsNullOrEmpty(DestinationFolderConvertedFiles) &&
                    System.IO.Directory.Exists(DestinationFolderConvertedFiles) &&
                    null != FilesConvertedToPdf)
                {
                    if (e.ChangeType == System.IO.WatcherChangeTypes.Deleted)
                    {
                        var file_to_remove = FilesConvertedToPdf.Where(x => x.FullName == e.FullPath).FirstOrDefault();
                        System.Windows.Application.Current.Dispatcher.Invoke(delegate
                        {
                            FilesConvertedToPdf.Remove(file_to_remove);
                        });
                    }
                    else if (e.ChangeType == System.IO.WatcherChangeTypes.Created)
                    {
                        var temp_count = FilesConvertedToPdf.Count();
                        if (!FilesConvertedToPdf.Any(x => x.FullName == e.FullPath))
                        {
                            var file_to_add = new CockleFilePdf(e.FullPath, SourceFileTypeEnum.Unrecognized);

                            System.Windows.Application.Current.Dispatcher.Invoke(delegate
                            {
                                if (temp_count == FilesConvertedToPdf.Count())
                                {
                                    FilesConvertedToPdf.Add(file_to_add);
                                }
                            });
                        }
                    }
                    else if (e.ChangeType == System.IO.WatcherChangeTypes.Renamed)
                    {
                        var file_to_remove = FilesConvertedToPdf.Where(x => x.FullName == e.FullPath).FirstOrDefault();
                        System.Windows.Application.Current.Dispatcher.Invoke(delegate
                        {
                            FilesConvertedToPdf.Remove(file_to_remove);
                        });
                        var file_to_add = new CockleFilePdf(e.FullPath, SourceFileTypeEnum.Unrecognized);
                        System.Windows.Application.Current.Dispatcher.Invoke(delegate
                        {
                            FilesConvertedToPdf.Add(file_to_add);
                        });
                    }
                }
                else
                {
                    //Files?.Clear();
                    //FilesConvertedToPdf?.Clear();
                    //FilesConvertedToPdf_Ordered?.Clear();
                    //DestinationFolderConvertedFiles = string.Empty;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
        private void saveSelectedCameraReadyFilesToScratch(object o)
        {
            try
            {
                if (null == FilesConvertedToPdf)
                {
                    FilesConvertedToPdf = new ObservableCollection <CockleFilePdf>();
                }
                else
                {
                    FilesConvertedToPdf.Clear(); DestinationFolderConvertedFiles = string.Empty;
                }

                // also clear Files & UpdateLabel
                Files?.Clear();
                UpdateLabel    = string.Empty;
                UpdateLabelPdf = string.Empty;

                var selections = FilesFoundInCameraReady.Where(x => x.IsSelected).ToList();
                if (selections.Count() == 0)
                {
                    throw new Exception("No files selected");
                }
                var time_stamp = string.Format("({0} {1}, {2}, {3})", DateTime.Now.ToString("MMM") /*Oct*/,
                                               DateTime.Now.ToString("dd") /*09*/, DateTime.Now.ToString("yyy") /*2015*/,
                                               DateTime.Now.ToString("T").ToLower() /*10:58:44 AM*/ /*, len_text*/)
                                 .Replace(':', ' ');
                var ticket_no  = selections.Where(x => !string.IsNullOrEmpty(x.Ticket)).FirstOrDefault().Ticket;
                var atty       = selections.Where(x => !string.IsNullOrEmpty(x.Attorney)).FirstOrDefault().Attorney;
                var new_folder = $"c:\\scratch\\{ticket_no} {atty} {time_stamp}";
                System.IO.Directory.CreateDirectory(new_folder);

                DestinationFolderConvertedFiles = new_folder;
                // move to scratch and add to FilesConvertedToPdf collection
                selections.ForEach(x =>
                {
                    var new_full_name = System.IO.Path.Combine(new_folder, x.ShortFileName);
                    System.IO.File.Copy(x.FileName, new_full_name, true);
                    if (System.IO.File.Exists(new_full_name))
                    {
                        FilesConvertedToPdf.Add(new CockleFilePdf(new_full_name, SourceFileTypeEnum.Camera_Ready));
                    }
                });
            }
            catch (Exception ex)
            {
                UpdateLabelPdf = ex.Message;
            }
            finally
            {
                ModalOverlayIsVisible            = false;
                CameraReadyFileSelectorIsVisible = false;
            }
        }
        private void combineFilesConvertedToPdf_Ordered()
        {
            ModalOverlayIsVisible      = false;
            SetFileOrderModalIsVisible = false;
            UpdateLabelPdf             = "";

            try
            {
                var combined_file_names = new List <string>();
                var combine_files       = FilesConvertedToPdf_Ordered.ToList();

                var ticket_atty   = FilesConvertedToPdf.Where(x => !string.IsNullOrEmpty(x.TicketPlusAttorney)).Select(x => x.TicketPlusAttorney).FirstOrDefault();
                var new_file_name = PdfUtilities.GenerateFilenameForNewPdf(DestinationFolderConvertedFiles, "CombinedPdf", ticket_atty);

                if (StaticSystemTests.IsAdobePdfPrinterAvailable())
                {
                    // create combined pdf
                    Models.MergePdf.SimpleMergedPdf simpleMergedPdf;
                    if (!string.IsNullOrEmpty(new_file_name))
                    {
                        simpleMergedPdf = new Models.MergePdf.SimpleMergedPdf(combine_files, "Acrobat", true, new_file_name);
                    }
                    else
                    {
                        simpleMergedPdf = new Models.MergePdf.SimpleMergedPdf(combine_files, "Acrobat", true);
                    }

                    // add new file to FilesConvertedToPdf collection
                    if (System.IO.File.Exists(simpleMergedPdf?.NewCombinedFile))
                    {
                        if (!FilesConvertedToPdf.Any(x => x.FullName == simpleMergedPdf.NewCombinedFile))
                        {
                            FilesConvertedToPdf.Add(new CockleFilePdf(simpleMergedPdf.NewCombinedFile, SourceFileTypeEnum.Combined_Pdf));
                            UpdateLabelPdf = "Created: " + simpleMergedPdf.NewCombinedFile;
                        }
                    }
                }
                else // using PdfSharp or iTextSharp ???
                {
                    //combined_file_name = new SimpleMergedPdf(SelectedPdfFiles, "PdfSharp").NewCombinedFile;
                    //var combined_file = new SimpleMergedPdf(SelectedPdfFiles, "iTextSharp").NewFileName;
                }
            }
            catch (Exception ex)
            {
                Console.Write(ex.Message);
                UpdateLabelPdf = ex.Message;
            }
        }
 private void cancelSearchOrConvert()
 {
     try
     {
         searchCancelTokenSource?.Cancel();
     }
     catch (ObjectDisposedException ex)
     {
         System.Diagnostics.Debug.WriteLine(ex);
     }
     try
     {
         convertCancelTokenSource?.Cancel();
     }
     catch (ObjectDisposedException ex)
     {
         System.Diagnostics.Debug.WriteLine(ex);
     }
     try
     {
         UpdateLabel = UpdateLabel.Equals("Operation cancelled") ? "" : "Operation cancelled";
         if (null == Files)
         {
             Files = new ObservableCollection <CockleFile>();
         }
         else
         {
             Files.Clear();
         }
         if (null == FilesConvertedToPdf)
         {
             FilesConvertedToPdf = new ObservableCollection <CockleFilePdf>();
         }
         else
         {
             FilesConvertedToPdf.Clear();
         }
         DestinationFolderConvertedFiles = string.Empty;
         SearchText = string.Empty;
     }
     catch (ObjectDisposedException ex)
     {
         System.Diagnostics.Debug.WriteLine(ex);
     }
 }
        private void clearPdfFiles()
        {
            try
            {
                if (null == FilesConvertedToPdf)
                {
                    FilesConvertedToPdf = new ObservableCollection <CockleFilePdf>();
                }
                else
                {
                    FilesConvertedToPdf.Clear();
                }

                if (null == FilesConvertedToPdf_Ordered)
                {
                    FilesConvertedToPdf_Ordered = new ObservableCollection <CockleFilePdf>();
                }
                else
                {
                    FilesConvertedToPdf_Ordered.Clear();
                }

                if (null == Files)
                {
                    Files = new ObservableCollection <CockleFile>();
                }
                else
                {
                    Files.Clear();
                }

                DestinationFolderConvertedFiles = string.Empty;
                UpdateLabelPdf = "";
            }
            catch (Exception ex)
            {
                UpdateLabelPdf = ex.Message;
            }
        }
        private void getFilesFromCameraReadyFolder()
        {
            // clear out existing files
            Files?.Clear();
            FilesConvertedToPdf?.Clear();
            FilesFoundInCameraReady?.Clear();
            CameraReadyFileSelectorIsVisible = true;
            ModalOverlayIsVisible            = true;

            if (null == FilesFoundInCameraReady)
            {
                FilesFoundInCameraReady = new ObservableCollection <CockleFileInCameraReady>();
            }

            string CAMERA_READY_FOLDER = System.IO.Directory.Exists(@"L:\Camera Ready")
                ? @"L:\Camera Ready" : @"\\CLBDC02\Printing\Camera Ready";

            var filesFoundInCameraReady = System.IO.Directory.EnumerateFiles(CAMERA_READY_FOLDER);

            filesFoundInCameraReady.ToList().ForEach(x =>
            {
                FilesFoundInCameraReady.Add(new CockleFileInCameraReady(x));
            });
        }
        private async void executeCenterPdf()
        {
            ModalOverlayIsVisible        = false;
            CoverLengthSelectorIsVisible = false;
            UpdateLabelPdf = "";
            try
            {
                // get new file name
                var cv_type = CenteredCoverType.NotSet;
                var custom_filename_text = string.Empty;
                if (BookletSelected_CenterPdf)
                {
                    cv_type = CenteredCoverType.Booklet;
                    custom_filename_text = "CenteredOnBookletSizedPage";
                }
                else if (LetterSelected_CenterPdf)
                {
                    cv_type = CenteredCoverType.Letter;
                    custom_filename_text = "CenteredOnLetterSizedPage";
                }
                var ticket_atty   = FilesConvertedToPdf.Where(x => !string.IsNullOrEmpty(x.TicketPlusAttorney)).Select(x => x.TicketPlusAttorney).FirstOrDefault();
                var new_file_name = PdfUtilities.GenerateFilenameForNewPdf(DestinationFolderConvertedFiles, custom_filename_text, ticket_atty);

                // typeset -- upper left
                if (UpperLeftPosition_CenterPdf)
                {
                    // this is a simple typeset centering, done with the one step process
                    int?cv_len = null;
                    if (HasCover_CenterPdf)
                    {
                        // two ways to get cover length: 1) check other files in directory, 2) iText method
                        if (FilesConvertedToPdf.Any(x => null != x.CoverLength))
                        {
                            cv_len = FilesConvertedToPdf.Where(x => null != x.CoverLength).FirstOrDefault().CoverLength;
                        }
                        else
                        {
                            cv_len = PdfCropAndNUp.StaticUtils.GetCoverLength_FirstPageTypesetPdf(SelectedPdfFile.FullName);
                        }
                    }
                    var c = await System.Threading.Tasks.Task.Run(() =>
                                                                  new Models.CenterPdfText.CenterTypesetPdf(SelectedPdfFile, cv_len, new_file_name, cv_type));

                    if (null != c && null != c.NewFileCreated &&
                        System.IO.File.Exists(c.NewFileCreated.FullName))
                    {
                        if (!FilesConvertedToPdf.Any(x => x.FullName == c.NewFileCreated.FullName))
                        {
                            FilesConvertedToPdf.Add(c.NewFileCreated);
                        }
                        UpdateLabelPdf = "Created: " + System.IO.Path.GetFileNameWithoutExtension(c.NewFileCreated.FullName);
                    }
                }
                // already centered
                else if (CenterPosition_CenterPdf)
                {
                    // if already centered, no need to separate out cover
                    Models.CenterPdfText.CenterCameraReadyBrief ctr = null;
                    if (BookletSelected_CenterPdf)
                    {
                        ctr = await System.Threading.Tasks.Task.Run(() =>
                                                                    new Models.CenterPdfText.CenterCameraReadyBrief(SelectedPdfFile, new_file_name, CenteredCoverType.Booklet));
                    }
                    else if (LetterSelected_CenterPdf)
                    {
                        ctr = await System.Threading.Tasks.Task.Run(() =>
                                                                    new Models.CenterPdfText.CenterCameraReadyBrief(SelectedPdfFile, new_file_name, CenteredCoverType.Letter));
                    }
                    if (null != ctr && null != ctr.NewFileCreated &&
                        System.IO.File.Exists(ctr.NewFileCreated.FullName))
                    {
                        if (!FilesConvertedToPdf.Any(x => x.FullName == ctr.NewFileCreated.FullName))
                        {
                            FilesConvertedToPdf.Add(ctr.NewFileCreated);
                            UpdateLabelPdf = "Created: " + System.IO.Path.GetFileNameWithoutExtension(ctr.NewFileCreated.FullName);
                        }
                    }
                }
                // need to develop this: method to crop (find text boundaries) and center
                else if (NotCentered_CenterPdf)
                {
                }
            }
            catch (Exception ex)
            {
                Console.Write(ex.Message);
                UpdateLabelPdf = ex.Message;
            }
        }
Beispiel #11
0
        private async void searchAndSaveToScratch()
        {
            #region step 1: search for files
            var error_issue = string.Empty;
            IsExecutingSearch = true;
            Files.Clear();
            FilesConvertedToPdf?.Clear(); // added 12/1/2017
            UpdateLabel = "";
            var searchProgress = new Progress <string>(reportProgress);
            searchCancelTokenSource = new CancellationTokenSource();
            var latestFiles = new List <CockleFile>();
            List <CockleFile> cockleFilesFound = null;
            try
            {
                addItemToRecentSearchTerms();
                cockleFilesFound =
                    await Models.Search.SearchModel.SearchCurrentAndBackupT(
                        SearchText,
                        SearchEverywhere,
                        IsSingleTicket,
                        searchProgress,
                        searchCancelTokenSource.Token,
                        error_issue);

                latestFiles          = MarkLatestFiles(cockleFilesFound);
                TicketsFoundInSearch = new HashSet <int>();
                cockleFilesFound?.ForEach(f =>
                {
                    if (null != f.TicketNumber)
                    {
                        TicketsFoundInSearch.Add((int)f.TicketNumber);
                    }
                    Files.Add(f);
                });
                UpdateLabel  = $"{TicketsFoundInSearch.Count} ticket{(TicketsFoundInSearch.Count == 1 ? "" : "s")} found in search";
                UpdateLabel += $"\n{cockleFilesFound.Count} file{(cockleFilesFound.Count == 1 ? "" : "s")} found";
            }
            catch (OperationCanceledException ex)
            {
                System.Diagnostics.Debug.WriteLine(ex);
                var iSearchProgress = searchProgress as IProgress <string>;
                iSearchProgress.Report("Search cancelled");
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex);
                var iSearchProgress = searchProgress as IProgress <string>;
                iSearchProgress.Report("Error in search for files");
            }
            finally
            {
                searchCancelTokenSource.Dispose();
                IsExecutingSearch = false;
                CollapseTickets   = false;
                ShowLatestFiles   = true;
            }
            #endregion
            #region Save files to scratch folder
            if (null != cockleFilesFound)
            {
                var scratchLocation = @"c:\scratch";
                cockleFilesFound
                .Where(x => x.IsLatestFile)
                .ToList()
                .ForEach(x =>
                {
                    System.IO.File.Copy(x.FullName, System.IO.Path.Combine(scratchLocation, x.Filename));
                });
                UpdateLabel += '\n' + "Latest files saved to scratch";
            }
            #endregion
        }
Beispiel #12
0
        private async void searchAndConvertToPdf()
        {
            #region step 1: search for files
            var error_issue = string.Empty;
            IsExecutingSearch = true;
            Files.Clear();
            FilesConvertedToPdf?.Clear(); // added 12/1/2017
            UpdateLabel = "";
            var searchProgress = new Progress <string>(reportProgress);
            searchCancelTokenSource = new CancellationTokenSource();
            var latestFiles = new List <CockleFile>();
            try
            {
                addItemToRecentSearchTerms();
                var cockleFilesFound =
                    await Models.Search.SearchModel.SearchCurrentAndBackupT(
                        SearchText,
                        SearchEverywhere,
                        IsSingleTicket,
                        searchProgress,
                        searchCancelTokenSource.Token,
                        error_issue);

                latestFiles          = MarkLatestFiles(cockleFilesFound);
                TicketsFoundInSearch = new HashSet <int>();
                cockleFilesFound?.ForEach(f =>
                {
                    if (null != f.TicketNumber)
                    {
                        TicketsFoundInSearch.Add((int)f.TicketNumber);
                    }
                    Files.Add(f);
                });
                UpdateLabel  = $"{TicketsFoundInSearch.Count} ticket{(TicketsFoundInSearch.Count == 1 ? "" : "s")} found in search";
                UpdateLabel += $"\n{cockleFilesFound.Count} file{(cockleFilesFound.Count == 1 ? "" : "s")} found";
            }
            catch (OperationCanceledException ex)
            {
                System.Diagnostics.Debug.WriteLine(ex);
                var iSearchProgress = searchProgress as IProgress <string>;
                iSearchProgress.Report("Search cancelled");
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex);
                var iSearchProgress = searchProgress as IProgress <string>;
                iSearchProgress.Report("Error in search for files");
            }
            finally
            {
                searchCancelTokenSource.Dispose();
                IsExecutingSearch = false;
                CollapseTickets   = false;
                ShowLatestFiles   = true;
            }
            #endregion
            #region step 2: convert collected files to pdf
            if (null == latestFiles || latestFiles?.Count == 0)
            {
                UpdateLabel = "No files found";
                return;
            }


            // step 4: convert latest files to pdf
            // Files will land in c:\scratch, so capture them
            IsConvertingToPdf = true;
            var convertProgress = new Progress <string>(reportProgress);
            convertCancelTokenSource = new CancellationTokenSource();
            try
            {
                // HERE EXCEPTION !!!
                var _filesConverting =
                    await executePdfConversion(
                        convertProgress,
                        convertCancelTokenSource.Token,
                        latestFiles.ToList());

                FilesConvertedToPdf = new ObservableCollection <CockleFilePdf>(_filesConverting);
                UpdateLabel        += $"\n{FilesConvertedToPdf.Count} file{(FilesConvertedToPdf.Count == 1 ? "" : "s")} created";
            }
            catch (OperationCanceledException ex)
            {
                System.Diagnostics.Debug.WriteLine(ex);
                var iConvertProgress = convertProgress as IProgress <string>;
                iConvertProgress.Report("Conversion cancelled");
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex);
                var iConvertProgress = convertProgress as IProgress <string>;
                iConvertProgress.Report("Error trying to convert files");
            }
            finally
            {
                convertCancelTokenSource.Dispose();
                IsConvertingToPdf = false;
            }
            #endregion
        }
        private void refreshLoadedPdfFolder()
        {
            try
            {
                // Command:RunRefreshLoadedPdfFolder
                if (!System.IO.Directory.Exists(DestinationFolderConvertedFiles))
                {
                    FilesConvertedToPdf.Clear();
                    DestinationFolderConvertedFiles = string.Empty;
                    return;
                }
                else
                {
                    var files = System.IO.Directory.EnumerateFiles(DestinationFolderConvertedFiles).ToList();

                    var files_to_add = files.Where(x => !FilesConvertedToPdf.Any(y => x == y.FullName));
                    if (files_to_add.Count() > 0)
                    {
                        files_to_add.ToList().ForEach(x =>
                        {
                            FilesConvertedToPdf.Add(new CockleFilePdf(x, Models.Utilities.SourceFileTypeEnum.Unrecognized));
                        });
                    }

                    var files_to_remove = FilesConvertedToPdf.Where(x => !System.IO.File.Exists(x.FullName));
                    if (files_to_remove?.Count() > 0)
                    {
                        foreach (var x in files_to_remove)
                        {
                            FilesConvertedToPdf.Remove(x);
                        }
                    }

                    var files_dup = FilesConvertedToPdf.GroupBy(x => x.FullName)
                                    .Where(g => g.Count() > 1).Select(y => y.Key).ToList();
                    foreach (var y in files_dup)
                    {
                        var options_to_remove = FilesConvertedToPdf.Where(x => x.FullName == y);
                        var unrec_option      = options_to_remove.Where(x => x.FileType == SourceFileTypeEnum.Unrecognized || x.FileType == SourceFileTypeEnum.UnrecognizedCentered);
                        if (unrec_option.Count() == 1)
                        {
                            FilesConvertedToPdf.Remove(unrec_option.FirstOrDefault());
                        }
                        else
                        {
                            var other_option = FilesConvertedToPdf.Where(x => x.FullName == y);
                            FilesConvertedToPdf.Remove(other_option.FirstOrDefault());
                        }
                    }

                    foreach (var x in FilesConvertedToPdf)
                    {
                        foreach (var y in files_dup)
                        {
                            if (x.FullName == y)
                            {
                                if (x.FileType == SourceFileTypeEnum.Unrecognized)
                                {
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Console.Write(ex.Message);
            }
        }
 private bool canExtractPagesFromPdfDocument()
 {
     return(null != FilesConvertedToPdf &&
            FilesConvertedToPdf.Count() > 0 &&
            SelectedPdfFile != null);
 }
        /// <summary>
        /// imposePdf() function:
        /// The only source is the modal SelectImpositionDetails.xaml,
        /// and the RunImposePdf Command.
        /// The imposition process is controlled by a group of
        /// boolean properties:
        /// 1) IsTypeset: Upper Left Corner Document Only
        ///               All Centered Briefs are considered Camera Ready
        /// 2) IsSaddleStitchPdf: True or False (if false: IsPerfectBindPdf)
        /// 3) HasCover: self explanatory
        /// 4) BlankPagesAdded: Works as a Gatekeeper: User cannot run function
        ///                     without clicking Yes
        ///
        /// Function uses PDFCropAndNUp:
        ///     How many functions in the SVM others here use this?
        ///
        /// Problem: When creating imposed files -- only CR? --
        ///          user may click NoCover, but program creates a cover anyway
        ///          (one that won't open)
        ///          Solved: Solved this issue by simply doing a null test on the result.
        ///
        ///
        ///
        /// </summary>
        private void imposePdf()
        {
            ModalOverlayIsVisible            = false;
            SelectImpositionDetailsIsVisible = false;
            UpdateLabelPdf = "";
            var new_files_created = new List <CockleFilePdf>();

            try
            {
                if (IsTypesetPdf)
                {
                    string[] new_file_name = null;
                    var      num_pages     = new iTextSharp.text.pdf.PdfReader(SelectedPdfFile.FullName).NumberOfPages;
                    new_file_name = generateImposedTypesetPdfFilename(num_pages);

                    ImposeSingleTypesetPdf imposed_doc = null;
                    if (HasCoverPdf && IsPerfectBindPdf && num_pages > 1)
                    {
                        // two docs
                        // cover first: extract page 1

                        using (var file_stream = PdfUtilities.ConvertPdfFileToStream(SelectedPdfFile.FullName))
                        {
                            // problem here: cv_stream is dying !!!
                            using (var cv_stream = extractPagesFromPerfectBindStream(file_stream, 1, 1))
                            {
                                imposed_doc = new ImposeSingleTypesetPdf(cv_stream,
                                                                         IsSaddleStitchPdf ? TypeOfBindEnum.SaddleStitch : TypeOfBindEnum.PerfectBind, hasCover: true);
                                using (var fs = new System.IO.FileStream(new_file_name[0], System.IO.FileMode.Create, System.IO.FileAccess.Write))
                                {
                                    fs.Write(imposed_doc.NewDocMemStream.ToArray(), 0, imposed_doc.NewDocMemStream.ToArray().Length);
                                }
                            }
                            using (var br_stream = PdfUtilities.ExtractPdfPagesToStream(file_stream, 2, num_pages))
                            {
                                imposed_doc = new ImposeSingleTypesetPdf(br_stream,
                                                                         IsSaddleStitchPdf ? TypeOfBindEnum.SaddleStitch : TypeOfBindEnum.PerfectBind, hasCover: false);
                                using (var fs = new System.IO.FileStream(new_file_name[1], System.IO.FileMode.Create, System.IO.FileAccess.Write))
                                {
                                    fs.Write(imposed_doc.NewDocMemStream.ToArray(), 0, imposed_doc.NewDocMemStream.ToArray().Length);
                                }
                            }
                        }
                        //new_files_created.Add(new CockleFilePdf( new_file_name[0]);
                    }
                    else
                    {
                        imposed_doc = new ImposeSingleTypesetPdf(SelectedPdfFile,
                                                                 IsSaddleStitchPdf ? TypeOfBindEnum.SaddleStitch : TypeOfBindEnum.PerfectBind, HasCoverPdf);
                        using (var fs = new System.IO.FileStream(new_file_name[0], System.IO.FileMode.Create, System.IO.FileAccess.Write))
                        {
                            fs.Write(imposed_doc.NewDocMemStream.ToArray(), 0, imposed_doc.NewDocMemStream.ToArray().Length);
                        }
                    }
                }
                else if (IsCameraReadyCenteredPdf)
                {
                    var new_files = PdfCropAndNUp.PdfCookbook.CreatePrintReadyFile(
                        SelectedPdfFile.FullName,
                        HasCoverPdf,
                        IsSaddleStitchPdf
                            ? PdfCropAndNUp.PdfBindTypeEnum.SaddleStitch
                            : PdfCropAndNUp.PdfBindTypeEnum.PerfectBind,
                        null,
                        IsCameraReadyCenteredPdf,
                        IsCameraReadyOffsetPdf
                        );
                    if (new_files.All(x => System.IO.File.Exists(x.FullName)))
                    {
                        UpdateLabelPdf = "Created:";
                        foreach (var x in new_files)
                        {
                            if (!FilesConvertedToPdf.Any(y => x.FullName == y.FullName))
                            {
                                FilesConvertedToPdf.Add(new CockleFilePdf(x.FullName, SourceFileTypeEnum.Imposed_Pdf));
                            }
                            UpdateLabelPdf += " " + System.IO.Path.GetFileNameWithoutExtension(x.FullName);
                        }
                    }
                }
                else if (IsCameraReadyOffsetPdf)
                {
                    var new_files = PdfCropAndNUp.PdfCookbook.CreatePrintReadyFile(
                        SelectedPdfFile.FullName,
                        HasCoverPdf,
                        IsSaddleStitchPdf
                            ? PdfCropAndNUp.PdfBindTypeEnum.SaddleStitch
                            : PdfCropAndNUp.PdfBindTypeEnum.PerfectBind,
                        null,
                        IsCameraReadyCenteredPdf,
                        IsCameraReadyOffsetPdf
                        );
                    if (new_files.All(x => System.IO.File.Exists(x.FullName)))
                    {
                        UpdateLabelPdf = "Created:";
                        new_files.ForEach(x =>
                        {
                            FilesConvertedToPdf.Add(new CockleFilePdf(x.FullName, SourceFileTypeEnum.Imposed_Pdf));
                            UpdateLabelPdf += " " + System.IO.Path.GetFileNameWithoutExtension(x.FullName);
                        });
                    }
                }
            }
            catch (Exception ex)
            {
                UpdateLabelPdf = ex.Message;
            }
        }
        private string[] generateImposedTypesetPdfFilename(int num_pages)
        {
            var new_file_name = new string[] { string.Empty, string.Empty };

            // get custom name
            var custom_name_a = string.Empty;
            var custom_name_b = string.Empty;

            if (IsSaddleStitchPdf)
            {
                if (HasCoverPdf && num_pages == 1)
                {
                    custom_name_a = "Cover_SaddleStitch";
                }
                else if (HasCoverPdf && num_pages > 1)
                {
                    custom_name_a = "Cover_&_Brief_SaddleStitch";
                }
                else if (!HasCoverPdf)
                {
                    custom_name_a = "Brief_SaddleStitch";
                }
            }
            else // Perfect Bind
            {
                if (HasCoverPdf && num_pages == 1)
                {
                    custom_name_a = "Cover_PerfectBind";
                }
                else if (HasCoverPdf && num_pages > 1)
                {
                    // need two names here
                    custom_name_a = "Cover_PerfectBind";
                    custom_name_b = "Brief_PerfectBind";
                }
                else if (!HasCoverPdf)
                {
                    custom_name_a = "Brief_PerfectBind";
                }
            }

            // get ticket + atty
            var ticket_atty = FilesConvertedToPdf.Where(x => x.TicketNumber != null && !(string.IsNullOrEmpty(x.Attorney))).Select(x => x.TicketPlusAttorney).FirstOrDefault().Trim();

            if (string.IsNullOrEmpty(ticket_atty))
            {
                ticket_atty = FilesConvertedToPdf.Where(x => x.TicketNumber != null).Select(x => x.TicketNumber).FirstOrDefault().ToString().Trim();
            }
            custom_name_a = ticket_atty + " " + custom_name_a;
            if (!string.IsNullOrEmpty(custom_name_b))
            {
                custom_name_b = (ticket_atty + " " + custom_name_b).Trim();
            }

            new_file_name[0] = System.IO.Path.Combine(DestinationFolderConvertedFiles, custom_name_a + ".pdf");
            var i = 0;

            while (System.IO.File.Exists(new_file_name[0]))
            {
                new_file_name[0] = new_file_name[0].Substring(0, new_file_name[0].Length - 4);
                new_file_name[0] = System.IO.Path.Combine(DestinationFolderConvertedFiles, new_file_name[0] + "_" + i + ".pdf");
                i++;
            }
            if (!string.IsNullOrEmpty(custom_name_b))
            {
                new_file_name[1] = System.IO.Path.Combine(DestinationFolderConvertedFiles, custom_name_b + ".pdf");
                i = 0;
                while (System.IO.File.Exists(new_file_name[1]))
                {
                    new_file_name[1] = new_file_name[1].Substring(0, new_file_name[1].Length - 4);
                    new_file_name[1] = System.IO.Path.Combine(DestinationFolderConvertedFiles, new_file_name[1] + "_" + i + ".pdf");
                    i++;
                }
            }
            return(new_file_name);
        }
        private void centerPdfOptions()
        {
            try
            {
                // preset booleans
                // preset cover length
                var cv_len = FilesConvertedToPdf.Where(x => x.CoverLength != null).Select(x => x.CoverLength).FirstOrDefault();
                switch (cv_len)
                {
                case 48:
                    Cover48PicaPdf = true;
                    break;

                case 49:
                    Cover49PicaPdf = true;
                    break;

                case 50:
                    Cover50PicaPdf = true;
                    break;

                case 51:
                    Cover51PicaPdf = true;
                    break;

                default:
                    Cover48PicaPdf = false;
                    Cover49PicaPdf = false;
                    Cover50PicaPdf = false;
                    Cover51PicaPdf = false;
                    break;
                }

                // preset "has cover"
                var file_type = SelectedPdfFile.FileType;
                switch (file_type)
                {
                case SourceFileTypeEnum.Cover:
                    NoCover_CenterPdf  = false;
                    HasCover_CenterPdf = true;
                    break;

                default:
                    NoCover_CenterPdf  = true;
                    HasCover_CenterPdf = false;
                    break;
                }

                // preset page size
                LetterSelected_CenterPdf  = true;
                BookletSelected_CenterPdf = false;

                // preset position of original
                UpperLeftPosition_CenterPdf = false;
                CenterPosition_CenterPdf    = true;
                NotCentered_CenterPdf       = false;

                // call modal overlay
                ModalOverlayIsVisible        = true;
                CoverLengthSelectorIsVisible = true;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }