首页 文章

如何从C#程序执行ghostscript

提问于
浏览
1

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

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

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

This is the string that's being called in the process.start(gs) function

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

This is the message that I get in my console.

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

Then this is the code for my method.

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 回答

  • 1

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

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

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

    你可以在这里找到一个:Ghostscript.NET on GitHub

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

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

相关问题