protected static void PrintToGhostscript(string printer, string outputFilename, PrintDocument printFunc) { String postscriptFile = outputFilename + ".ps"; PrintDialog printDialog = new PrintDialog { AllowPrintToFile = true, PrintToFile = true }; System.Drawing.Printing.PrinterSettings printerSettings = printDialog.PrinterSettings; printerSettings.PrintToFile = true; printerSettings.PrinterName = printer; printerSettings.PrintFileName = postscriptFile; printFunc(postscriptFile, printerSettings.PrinterName); ReleaseCOMObject(printerSettings); ReleaseCOMObject(printDialog); GhostscriptProcessor gsproc = new GhostscriptProcessor(); List <string> gsArgs = new List <string> { "gs", "-dBATCH", "-dNOPAUSE", "-dQUIET", "-dSAFER", "-dNOPROMPT", "-sDEVICE=pdfwrite", String.Format("-sOutputFile=\"{0}\"", string.Join(@"\\", outputFilename.Split(new string[] { @"\" }, StringSplitOptions.None))), @"-f", postscriptFile }; gsproc.Process(gsArgs.ToArray()); File.Delete(postscriptFile); }
public void Start() { string inputFile = @"E:\gss_test\test.pdf"; string outputFile = @"E:\gss_test\output\page-%03d.png"; int pageFrom = 1; int pageTo = 50; using (GhostscriptProcessor ghostscript = new GhostscriptProcessor()) { ghostscript.Processing += new GhostscriptProcessorProcessingEventHandler(ghostscript_Processing); List <string> switches = new List <string>(); switches.Add("-empty"); switches.Add("-dSAFER"); switches.Add("-dBATCH"); switches.Add("-dNOPAUSE"); switches.Add("-dNOPROMPT"); switches.Add("-dFirstPage=" + pageFrom.ToString()); switches.Add("-dLastPage=" + pageTo.ToString()); switches.Add("-sDEVICE=png16m"); switches.Add("-r96"); switches.Add("-dTextAlphaBits=4"); switches.Add("-dGraphicsAlphaBits=4"); switches.Add(@"-sOutputFile=" + outputFile); switches.Add(@"-f"); switches.Add(inputFile); ghostscript.Process(switches.ToArray()); } }
public void Start() { string inputFile = Path.GetFullPath(@"../../../test/test.pdf").Replace("\\", "/"); string outputFile = Path.GetFullPath(@"../../../test/output/test-t2.tiff").Replace("\\", "/"); Directory.CreateDirectory(Path.GetDirectoryName(outputFile)); GhostscriptPipedOutput gsPipedOutput = new GhostscriptPipedOutput(); string h = gsPipedOutput.ClientHandle; string outputPipeHandle = "%handle%" + int.Parse(h).ToString("X2"); using (GhostscriptProcessor processor = new GhostscriptProcessor()) { //"C:\Program Files\gs\gs9.15\bin\gswin64.exe" -sDEVICE=tiff24nc -r300 -dNOPAUSE -dBATCH -sOutputFile="Invoice 1_%03ld.tiff" "Invoice 1.pdf" 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("-dPrinted"); //switches.Add("-sDEVICE=pdfwrite"); switches.Add("-sDEVICE=tiff24nc"); switches.Add("-sOutputFile=" + outputPipeHandle); switches.Add("-f"); switches.Add(inputFile); try { processor.Process(switches.ToArray()); byte[] rawDocumentData = gsPipedOutput.Data; var memStream = new MemoryStream(rawDocumentData); var image = new Bitmap(memStream); image.Save(outputFile); //if (writeToDatabase) //{ // Database.ExecSP("add_document", rawDocumentData); //} //else if (writeToDisk) //{ File.WriteAllBytes(outputFile + "__piped_output.data", rawDocumentData); //} } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { gsPipedOutput.Dispose(); gsPipedOutput = null; } } }
private void Start2() { string inputFile = @"E:\__test_data\i1.pdf"; string outputFile = @"E:\gss_test\output\page-%03d.png"; GhostscriptPipedOutput gsPipedOutput = new GhostscriptPipedOutput(); string outputPipeHandle = "%handle%" + int.Parse(gsPipedOutput.ClientHandle).ToString("X2"); using (GhostscriptProcessor processor = new GhostscriptProcessor()) { //"C:\Program Files\gs\gs9.15\bin\gswin64.exe" -sDEVICE=tiff24nc -r300 -dNOPAUSE -dBATCH -sOutputFile="Invoice 1_%03ld.tiff" "Invoice 1.pdf" 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("-dPrinted"); switches.Add("-sDEVICE=pdfwrite"); //switches.Add("-sDEVICE=tiffsep1"); switches.Add("-sOutputFile=" + outputPipeHandle); //switches.Add("-q"); switches.Add("-f"); switches.Add(inputFile); try { processor.Process(switches.ToArray()); byte[] rawDocumentData = gsPipedOutput.Data; var memStream = new MemoryStream(rawDocumentData); //var image = new Bitmap(memStream); //image.Save(@"Invocie 1.tiff"); //if (writeToDatabase) //{ // Database.ExecSP("add_document", rawDocumentData); //} //else if (writeToDisk) //{ // File.WriteAllBytes(@"E:\gss_test\output\test_piped_output.pdf", rawDocumentData); //} } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { gsPipedOutput.Dispose(); gsPipedOutput = null; } } }
public void Start() { // gs -dSAFER -dBATCH -dNOPAUSE -dNOPROMPT --permit-file-read=W:/Projects/sites/library.visyond.gov/80/lib/CS/Ghostscript.NET/test/ -c '(W:/Projects/sites/library.visyond.gov/80/lib/CS/Ghostscript.NET/test/test.pdf) (r) file runpdfbegin pdfpagecount = quit' string inputFile = @"../../../test/test.pdf"; GhostscriptStdIO stdioCb = new GhostscriptViewerStdIOHandler(); try { using (GhostscriptProcessor ghostscript = new GhostscriptProcessor()) { ghostscript.Processing += new GhostscriptProcessorProcessingEventHandler(ghostscript_Processing); List <string> switches = new List <string>(); //switches.Add("-empty"); switches.Add("-dSAFER"); switches.Add("-dBATCH"); switches.Add("-dNOPAUSE"); switches.Add("-dNOPROMPT"); // report the page count as per https://stackoverflow.com/questions/4826485/ghostscript-pdf-total-pages : // // of course this spells trouble when the `outputFile` path itself contains double quotes :-( // Also you cannot feed this baby *relative* paths as the GhostScript DLL will consider its own location as directory '.': string ap = Path.GetFullPath(inputFile).Replace("\\", "/"); // as per https://stackoverflow.com/questions/50730501/ggt-an-output-file-with-a-count-of-pdf-pages-for-each-file-with-ghostscript#answer-61310660 : // (make sure **all** paths havee forward slashes here, as they must match **exactly**!) #if false // oddly enough --permit-file-read doesn't fly while -I does, but I've seen this same flaky behaviour on the commandline... :-( switches.Add($"--permit-file-read={ Path.GetDirectoryName(ap).Replace("\\", "/") }"); #else switches.Add($"-I{ Path.GetDirectoryName(ap).Replace("\\", "/") }"); #endif switches.Add("-c"); switches.Add($"({ap}) (r) file runpdfbegin pdfpagecount = quit"); if (!File.Exists(ap)) { throw new ApplicationException($"input file does not exist: {inputFile}{ (inputFile != ap ? $" --> {ap}" : "") }"); } Console.WriteLine("CMD: {0}", String.Join(" ", switches.ToArray())); ghostscript.Process(switches.ToArray(), stdioCb); } } catch (Exception ex) { Console.WriteLine($"Error Exception: {ex}"); } finally { Console.WriteLine(stdioCb.ToString()); } }
/// Convert #region Convert /// <summary> /// Converts postscript file to pdf /// </summary> /// <param name="psFileName">postscript file name</param> /// <returns>pdf file name</returns> public static void ConvertPStoPDF(string psFileName, string pdfFileName) { if (string.IsNullOrWhiteSpace(psFileName)) { return; } if (string.IsNullOrWhiteSpace(pdfFileName)) { return; } try { GhostscriptProcessor process = CreateProcessor(); process.Process(ConvertPStoPDFArgs(psFileName, pdfFileName)); process.Dispose(); } catch (Exception ex) { WPFNotifier.DebugError(ex); } }
// Print out a document to a file which we will pass to ghostscript protected static void PrintToGhostscript(string printer, string outputFilename, PrintDocument printFunc) { String postscriptFilePath = ""; String postscriptFile = ""; try { // Create a temporary location to output to postscriptFilePath = Path.GetTempFileName(); File.Delete(postscriptFilePath); Directory.CreateDirectory(postscriptFilePath); postscriptFile = Path.Combine(postscriptFilePath, Guid.NewGuid() + ".ps"); // Set up the printer PrintDialog printDialog = new PrintDialog { AllowPrintToFile = true, PrintToFile = true }; System.Drawing.Printing.PrinterSettings printerSettings = printDialog.PrinterSettings; printerSettings.PrintToFile = true; printerSettings.PrinterName = printer; printerSettings.PrintFileName = postscriptFile; // Call the appropriate printer function (changes based on the office application) printFunc(postscriptFile, printerSettings.PrinterName); ReleaseCOMObject(printerSettings); ReleaseCOMObject(printDialog); // Call ghostscript GhostscriptProcessor gsproc = new GhostscriptProcessor(); List <string> gsArgs = new List <string> { "gs", "-dBATCH", "-dNOPAUSE", "-dQUIET", "-dSAFER", "-dNOPROMPT", "-sDEVICE=pdfwrite", String.Format("-sOutputFile=\"{0}\"", string.Join(@"\\", outputFilename.Split(new string[] { @"\" }, StringSplitOptions.None))), @"-f", postscriptFile }; gsproc.Process(gsArgs.ToArray()); } finally { // Clean up the temporary files if (!String.IsNullOrWhiteSpace(postscriptFilePath) && Directory.Exists(postscriptFilePath)) { if (!String.IsNullOrWhiteSpace(postscriptFile) && File.Exists(postscriptFile)) { // Make sure ghostscript is not holding onto the postscript file for (var i = 0; i < 60; i++) { try { File.Delete(postscriptFile); break; } catch (IOException) { Thread.Sleep(500); } } } Directory.Delete(postscriptFilePath); } } }
public static void ProcessFiles(string storageConnectionString, string destinationContainer, string sourceContainer, string folder, string processedContainer) { if (!folder.Contains(".pdf")) { return; } CloudBlockBlob blob; blob = StorageHelper.GetBlobReference(folder, sourceContainer, storageConnectionString); Stream myBlob = new MemoryStream(); blob.DownloadToStreamAsync(myBlob).Wait(); myBlob.Position = 0; string inputFile = System.IO.Path.GetTempPath() + Path.GetFileName(folder); using (var fileStream = new FileStream(inputFile, FileMode.Create, FileAccess.Write)) { myBlob.CopyTo(fileStream); } string outputFile = Path.GetTempPath() + Path.GetFileNameWithoutExtension(blob.Name) + "_%03d.jpg"; int pageFrom = 1; int pageTo = 999; //log.LogInformation($"Output file:{outputFile}"); GhostscriptVersionInfo gvi = new GhostscriptVersionInfo("D:\\home\\site\\wwwroot\\bin\\gsdll64.dll"); //GhostscriptVersionInfo gvi = new GhostscriptVersionInfo("C:\\Projects\\Repos\\msrpa\\msrpapdf\\bin\\Debug\\netcoreapp2.1\\bin\\gsdll32.dll"); using (GhostscriptProcessor ghostscript = new GhostscriptProcessor(gvi)) { List <string> switches = new List <string> { "-empty", "-dSAFER", "-dBATCH", "-dNOPAUSE", "-dNOPROMPT", "-dFirstPage=" + pageFrom.ToString(), "-dLastPage=" + pageTo.ToString(), "-sDEVICE=jpeg", "-r188", "-dJPEGQ=100", //switches.Add("-dGraphicsAlphaBits=4"); @"-sOutputFile=" + outputFile, @"-f", inputFile }; ghostscript.Process(switches.ToArray()); } UploadFilesToBlob(Path.GetFileNameWithoutExtension(blob.Name), blob.Name, storageConnectionString, destinationContainer); // Delete pdf file File.Delete(inputFile); // Move Blob to Processed Container MoveBlob(storageConnectionString, sourceContainer, folder, processedContainer); }
public void Start() { string inputFile = @"../../../test/test.pdf"; string outputFile = @"../../../test/output\page-%04d.png"; const int pageFrom = 1; const int pageTo = 50; const int dpi = 300; // 96 for screen when you don't want zoom or OCR-viable render output const bool highQualityAntiAliasedOutput = true; using (GhostscriptProcessor ghostscript = new GhostscriptProcessor()) { ghostscript.Processing += new GhostscriptProcessorProcessingEventHandler(ghostscript_Processing); List <string> switches = new List <string>(); //switches.Add("-empty"); switches.Add("-dSAFER"); switches.Add("-dBATCH"); switches.Add("-dNOPAUSE"); switches.Add("-dNOPROMPT"); switches.Add($"-dFirstPage={pageFrom}"); switches.Add($"-dLastPage={pageTo}"); switches.Add($"-sPageList={pageFrom}-"); // overrides FirstPage and LastPage when used... switches.Add("-sDEVICE=png16m"); // PNG 24bit color output: https://ghostscript.com/doc/current/Devices.htm switches.Add($"-r{dpi}"); switches.Add($"-dMaxBitmap={ /* assume A3+50% page size @ 4 bytes per pixel */ (int)(12 * 16 * dpi * dpi * 4 * 1.5) }"); if (highQualityAntiAliasedOutput) { switches.Add("-dTextAlphaBits=4"); // 4 = best quality: https://www.ghostscript.com/doc/9.52/Use.htm#Rendering_parameters switches.Add("-dGraphicsAlphaBits=4"); switches.Add("-dAlignToPixels=0"); } else { switches.Add("-dTextAlphaBits=1"); // 4 = best quality: https://www.ghostscript.com/doc/9.52/Use.htm#Rendering_parameters switches.Add("-dGraphicsAlphaBits=1"); switches.Add("-dAlignToPixels=1"); } switches.Add("-dPrinted=false"); // always treat output device as a screen instead of as a printer for annotations display, etc. switches.Add($"-sOutputFile={outputFile}"); // make sure the target directory exists: Directory.CreateDirectory(Path.GetDirectoryName(outputFile)); #if false // doesn't work :-( // also report the page count as per https://stackoverflow.com/questions/4826485/ghostscript-pdf-total-pages : switches.Add("-q"); switches.Add("-c"); // of course this spells trouble when the `outputFile` path itself contains double quotes :-( // Aalso you cannot feed this baby *relative* paths as the GhostScript DLL will consider its own location as directory '.': string ap = Path.GetFullPath(inputFile).Replace("\\", "/"); switches.Add($"\"({ap}) (r) file runpdfbegin pdfpagecount =\""); #else string ap = Path.GetFullPath(inputFile).Replace("\\", "/"); #endif switches.Add("-c"); switches.Add("30000000 setvmthreshold"); switches.Add("-f"); switches.Add(ap /* inputFile -- just to make sure both parts of the GS command point at exactly the same file */); if (!File.Exists(ap)) { throw new ApplicationException($"input file does not exist: {inputFile}{ (inputFile != ap ? $" --> {ap}" : "") }"); } Console.WriteLine("CMD: {0}", String.Join(" ", switches.ToArray())); ghostscript.Process(switches.ToArray()); } }