如何从C#程序执行ghostscript

时间:2014-05-30 14:57:21

标签: c# ghostscript pdf-manipulation

我试图从我的C#程序调用ghost脚本,传递一些args来裁剪PDF文件的页脚,然后使用新的修改版本覆盖临时文件。

我认为我正在错误地调用gs.exe。有没有人看到我传递给开始的字符串(gs)不起作用的原因?

跟踪脚本时,它会在到达System.Diagnostics.Process.Start(gs);

时触发捕获

这是在process.start(gs)函数中调用的字符串

C:\gs\gs9.14\bin\gswin64c.exe -o C:\Users\myname\Desktop\assignment1\assignment1\data\temp\test.pdf -sDEVICE=pdfwrite -c "[/CropBox [24 72 559 794] /PAGES pdf mark" -f C:\Users\myname\Desktop\assignment1\assignment1\data\temp\test.pdf

这是我在控制台中收到的消息。

System.ComponentModel.Win32Exception (0x80004005): The system cannot find the file specified
       at System.Diagnostics.Process.StartWithShellExecuteEx(ProcessStartInfo startInfo)
       at System.Diagnostics.Process.Start()
       at System.Diagnostics.Process.Start(ProcessStartInfo startInfo)
       at System.Diagnostics.Process.Start(String fileName)
       at assignment1.Program.cropPDFFooter(String tempPDF) in C:\Users\tessierd\Desktop\assignment1\assignment1\Program.cs:line 78

然后这是我方法的代码。

public static void cropPDFFooter(string tempPDF)
    {
        try
        {
            byte[] croppedPDF = File.ReadAllBytes(tempPDF);
            string gsPath = @"C:\gs\gs9.14\bin\gswin64c.exe";

            List<string> gsArgsList = new List<string>();
            gsArgsList.Add(" -o " + tempPDF);
            gsArgsList.Add(" -sDEVICE=pdfwrite");
            gsArgsList.Add(" -c \"[/CropBox [24 72 559 794] /PAGES pdfmark\"");
            gsArgsList.Add(" -f " + tempPDF);
            var gsArgs = String.Join(null, gsArgsList);

            string gs = gsPath + gsArgs; // not needed anymore (see solution)
            // * wrong code here. 
            // System.Diagnostics.Process.Start(gs);
            // * Correct code below.
            System.Diagnostics.Process.Start(gsPath, gsArgs);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
            Console.ReadLine();
        }
    }

2 个答案:

答案 0 :(得分:1)

System.Diagnostics.Process.Start(gs);需要2个参与者。一个文件,然后是args。 我不得不将代码更改为

System.Diagnostics.Process.Start(gsPath, gsArgs);

答案 1 :(得分:1)

我建议您使用Ghostscript包装器 .NET

您可以在此处找到:Ghostscript.NET on GitHub

用法示例可在此处找到:Ghostscript Processor C# Sample

还有一个关于如何使用 -c 开关添加水印的示例,其中postscript可以简单地替换为cropbox postscript:Ghostscript.NET - Passing Postscript commands(看看底部函数)