private void Process(string input, string output, int startPage, int endPage)
        {
            GhostscriptVersionInfo _gs_verssion_info = GhostscriptVersionInfo.GetLastInstalledVersion();

            Ghostscript.NET.Processor.GhostscriptProcessor processor = new Ghostscript.NET.Processor.GhostscriptProcessor(_gs_verssion_info, true);
            processor.StartProcessing(CreateTestArgs(input, output, startPage, endPage), new ConsoleStdIO(true, true, true));
        }
Esempio n. 2
0
        private async Task <List <CockleFilePdf> > executePdfConversionForProof(
            IProgress <string> progress, CancellationToken cancellationToken, List <CockleFile> latestFiles)
        {
            bool exceptionThrownInAwait = false; // tracks excptn in await

            List <CockleFile> filesSelectedForConversion;
            bool convertAll = false;

            // get files from grid if null
            if (null == latestFiles)
            {
                filesSelectedForConversion = SelectedFiles;
            }
            else
            {
                convertAll = true; filesSelectedForConversion = latestFiles;
            }

            if (filesSelectedForConversion.Count < 1)
            {
                throw new Exception();
            }

            // begin AWAIT
            var filesToReturnFromTask = await Task.Run(() =>
            {
                //instantiate Word Application & Document
                Word.Application app = new Word.Application();
                app.Visible          = false; //true; // changed 9-7-17
                Word.Document doc    = null;

                //get original printer & prepare to create PDF
                var current_printer        = app.ActivePrinter;
                var konica_554_prn_printer = "554 Print to File";
                app.ActivePrinter          = konica_554_prn_printer;

                // collection of special class to track files
                var filesPrintedToPrnSuccessfully = new List <FilesPrintedToPrnSuccessfully>();
                // the Word file saved to scratch
                try
                {
                    // counter to track files printed
                    int i = 0;
                    // Q. copy all files to scratch?  A. cannot, because need tagline to read server drive



                    // loop through files
                    foreach (CockleFile fileSelected in filesSelectedForConversion)
                    {
                        // cancel if requested
                        try { cancellationToken.ThrowIfCancellationRequested(); }
                        catch (OperationCanceledException) { exceptionThrownInAwait = true; throw new OperationCanceledException(); }

                        // Open docx files in Word, clean up, and convert
                        try
                        {
                            doc = app.Documents.Open(FileName: fileSelected.LocalFullFilename, ReadOnly: true);
                        }
                        catch
                        {
                            System.Diagnostics.Debug.WriteLine($"{fileSelected.FullName} failed to open");
                        }

                        // cancel if requested
                        try { cancellationToken.ThrowIfCancellationRequested(); }
                        catch (OperationCanceledException) { exceptionThrownInAwait = true; throw new OperationCanceledException(); }

                        // print to pdf, reporting progress
                        var newPrnConvertedFromWord = string.Empty;
                        newPrnConvertedFromWord     = MicrosoftWordStaticClass.PrintToFileForProof(app, doc.FullName);

                        // halt process here: wait for COM background status to end
                        while (app.BackgroundPrintingStatus > 0 && app.BackgroundSavingStatus > 0)
                        {
                            try { cancellationToken.ThrowIfCancellationRequested(); }
                            catch (OperationCanceledException) { exceptionThrownInAwait = true; throw new OperationCanceledException(); }
                        }

                        // add to files_printed list
                        filesPrintedToPrnSuccessfully.Add(
                            new FilesPrintedToPrnSuccessfully
                        {
                            CockleFile  = fileSelected,
                            PrnFilename = newPrnConvertedFromWord,
                            Filetype    = fileSelected.FileType
                        });

                        // make sure file exists before closing
                        while (!System.IO.File.Exists(newPrnConvertedFromWord))
                        {
                            System.Diagnostics.Debug.WriteLine($"Waiting to print to pdf: {newPrnConvertedFromWord}");
                            // cancel if requested
                            try { cancellationToken.ThrowIfCancellationRequested(); }
                            catch (OperationCanceledException) { exceptionThrownInAwait = true; throw new OperationCanceledException(); }
                        }
                        // close document & delete temp file
                        doc.Close(SaveChanges: Word.WdSaveOptions.wdDoNotSaveChanges);
                        // increment counter
                        i++;
                    }// end for loop to convert each files
                }
                //catch (OperationCanceledException ex) { }
                catch { }
                finally
                {
                    app.ActivePrinter = current_printer;
                    app?.Quit();
                }
                if (exceptionThrownInAwait)
                {
                    // close app
                    app.ActivePrinter = current_printer;
                    app?.Quit();
                    // try to clean folder
                    filesPrintedToPrnSuccessfully.ForEach(f =>
                    {
                        if (System.IO.File.Exists(f.PrnFilename))
                        {
                            System.IO.File.Delete(f.PrnFilename);
                        }
                    });
                    return(null);
                }

                // block until all files exist
                while (filesPrintedToPrnSuccessfully?.Count != filesSelectedForConversion.Count)
                {
                    ;
                }

                // NOW, CHANGE NAMES OF FILES TO PS, AND USE GHOSTSCRIPT TO CONVERT TO PDF

                var filesPrintedSuccessfully = new List <FilePrintedSuccessfully>();

                foreach (var f in filesPrintedToPrnSuccessfully)
                {
                    var psFileName  = f.PrnFilename.Replace(".prn", ".ps");
                    var pdfFileName = f.PrnFilename.Replace(".prn", ".pdf");

                    System.IO.File.Move(f.PrnFilename, psFileName);
                    // block until successful
                    while (!System.IO.File.Exists(psFileName)) /*waiting for IO*/ } {
                    using (var processor = new Ghostscript.NET.Processor.GhostscriptProcessor())
                    {
                        List <string> switches = new List <string>();
                        switches.Add("-empty");
                        switches.Add("-dQUIET");
                        switches.Add("-dSAFER");
                        switches.Add("-dBATCH");
                        switches.Add("-dNOPAUSE");
                        switches.Add("-dNOPROMPT");
                        switches.Add("-sDEVICE=pdfwrite");
                        switches.Add("-o" + pdfFileName);
                        switches.Add("-q");
                        switches.Add("-f");
                        switches.Add(psFileName);

                        processor.StartProcessing(switches.ToArray(), null);
                    }

                    // make sure successful
                    while (!System.IO.File.Exists(pdfFileName)) /*waiting for IO*/ } {
                    filesPrintedSuccessfully.Add(
                        new FilePrintedSuccessfully
                    {
                        CockleFile    = f.CockleFile,
                        TempWordFile  = string.Empty,
                        PdfFilename   = pdfFileName,
                        Filetype      = SourceFileTypeEnum.Unrecognized, // may have to adjust type here
                        LengthOfCover = null
                    });

                    System.IO.File.Delete(psFileName);
            }

                                                       #region POINT OF NO RETURN IN CONVERSION
                                                       // convert files to CockleFilePdf
                                                       var cockleFilePdfsPrintedSuccessfully = new List <CockleFilePdf>();
                                                       foreach (var _f in filesPrintedSuccessfully)
                {
                    if (_f.LengthOfCover == null && _f.CockleFile == null)
                    {
                        cockleFilePdfsPrintedSuccessfully.Add(new CockleFilePdf(_f.PdfFilename, _f.Filetype));
                    }
                    else
                    {
                        cockleFilePdfsPrintedSuccessfully.Add(
                            new CockleFilePdf(_f.CockleFile, _f.PdfFilename, _f.LengthOfCover));
                    }
                }

                                                       // test whether all converted files have same ticket
                                                       bool allConvertedFilesSameTicket = cockleFilePdfsPrintedSuccessfully
                                                                                          .TrueForAll(f => f.TicketNumber ==
                                                                                                      cockleFilePdfsPrintedSuccessfully.First().TicketNumber);

                                                                                                                                                             // move files to unique folder
                                                       if ((allConvertedFilesSameTicket || IsSingleTicket) && cockleFilePdfsPrintedSuccessfully.Count() > 0) // PROBLEM HERE !!!
                {
                    var firstFile    = cockleFilePdfsPrintedSuccessfully.First();
                    string timeStamp = 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 folderName      = $"{firstFile.TicketNumber} {firstFile.Attorney} {timeStamp}";
                    var scratchLocation = @"c:\scratch";

                    var newFolder = System.IO.Directory.CreateDirectory(System.IO.Path.Combine(scratchLocation, folderName));

                    foreach (var f in cockleFilePdfsPrintedSuccessfully)
                    {
                        try
                        {
                            var new_filename = System.IO.Path.Combine(newFolder.FullName, f.Filename);
                            System.IO.File.Move(f.FullName, new_filename);

                            // associate new location with CockleFilePdf
                            f.FullName = new_filename;
                        }
                        catch (Exception ex)
                        {
                            System.Diagnostics.Debug.WriteLine(ex);
                        }
                    }
                }

                                                       // set destination property
                                                       DestinationFolderConvertedFiles = System.IO.Path.GetDirectoryName(cockleFilePdfsPrintedSuccessfully.First().FullName);

                                                       // set ranks of pdfs before returning
                                                       setCockleFilePdfRanks(cockleFilePdfsPrintedSuccessfully);


                                                       if (convertAll)
                {
                    // 1. create imposed pdf files
                    Models.Imposition.ImposeFullConvertedTicket createImposedPdfiTextSharp = null;
                    try
                    {
                        var len_of_cover = cockleFilePdfsPrintedSuccessfully
                                           .Where(f => f.FileType == SourceFileTypeEnum.Cover).First().CoverLength ?? -1;

                        // prepare files for imposition
                        //var cockleFilePdfsPrintedSuccessfullyToCombine = cockleFilePdfsPrintedSuccessfully.ToList();
                        //cockleFilePdfsPrintedSuccessfullyToCombine.Remove(mergedCockleFile);

                        createImposedPdfiTextSharp =
                            new Models.Imposition.ImposeFullConvertedTicket(
                                DestinationFolderConvertedFiles,
                                cockleFilePdfsPrintedSuccessfully.ToList(),
                                len_of_cover,
                                TypeOfBindEnum.ProgramDecidesByPageCount);

                        // add imposed files to list of cocklefilepdf files
                        if (createImposedPdfiTextSharp.ImposedFilesCreated.All(f => System.IO.File.Exists(f.FullName)))
                        {
                            createImposedPdfiTextSharp.ImposedFilesCreated.ForEach(f =>
                            {
                                cockleFilePdfsPrintedSuccessfully.Add(
                                    new CockleFilePdf(
                                        f.FullName,
                                        filesSelectedForConversion.First().Attorney,
                                        filesSelectedForConversion.First().TicketNumber,
                                        SourceFileTypeEnum.Imposed_Cover_and_Brief,
                                        "pdf",
                                        null));
                            });
                        }
                    }
                    catch (Exception ex)
                    {
                        if (null != createImposedPdfiTextSharp.ImposedFilesCreated &&
                            createImposedPdfiTextSharp.ImposedFilesCreated.Count > 0)
                        {
                            createImposedPdfiTextSharp.ImposedFilesCreated.ForEach(x => System.IO.File.Delete(x.FullName));

                            foreach (var imposed_file in createImposedPdfiTextSharp.ImposedFilesCreated)
                            {
                                if (cockleFilePdfsPrintedSuccessfully.Contains(imposed_file))
                                {
                                    cockleFilePdfsPrintedSuccessfully.Remove(imposed_file);
                                }
                            }
                        }
                        System.Diagnostics.Debug.WriteLine(ex.Message);
                    }

                    // 2. combine files into single pdf
                    Models.MergePdf.CreateMergedPDFAcrobat createMergedPdfAcrobat = null;
                    CockleFilePdf mergedCockleFile = null;
                    try
                    {
                        createMergedPdfAcrobat = new Models.MergePdf.CreateMergedPDFAcrobat(
                            cockleFilePdfsPrintedSuccessfully, Models.MergePdf.TypeOfCombinedPdf.All, centerPdf: true);

                        // add combined file to list of cocklefilepdf files
                        if (System.IO.File.Exists(createMergedPdfAcrobat.CombinedPdfFilename))
                        {
                            mergedCockleFile =
                                new CockleFilePdf(
                                    createMergedPdfAcrobat.CombinedPdfFilename,
                                    filesSelectedForConversion.First().Attorney,
                                    filesSelectedForConversion.First().TicketNumber,
                                    SourceFileTypeEnum.Combined_Pdf,
                                    "pdf",
                                    null);
                            cockleFilePdfsPrintedSuccessfully.Add(mergedCockleFile);
                        }
                    }
                    catch (Exception ex)
                    {
                        if (null != createMergedPdfAcrobat.CombinedPdfFilename &&
                            System.IO.File.Exists(createMergedPdfAcrobat.CombinedPdfFilename))
                        {
                            System.IO.File.Delete(createMergedPdfAcrobat.CombinedPdfFilename);
                        }
                        if (null != mergedCockleFile &&
                            cockleFilePdfsPrintedSuccessfully.Contains(mergedCockleFile))
                        {
                            cockleFilePdfsPrintedSuccessfully.Remove(mergedCockleFile);
                        }
                        System.Diagnostics.Debug.WriteLine(ex.Message);
                    }
                }
                                                       #endregion


                                                       return(cockleFilePdfsPrintedSuccessfully);
});

            if (exceptionThrownInAwait)
            {
                throw new OperationCanceledException();
            }
            return(filesToReturnFromTask);
        }