2

I am trying to call ghost script from my C# program, passing it some args to crop the footer of a PDF file, then overwrite the temp file with the new modified version.

I think I'm calling the gs.exe incorrectly. Does anyone see a reason that the string I'm passing to start(gs) doesn't work?

When trace the script, it triggers the catch when it gets to System.Diagnostics.Process.Start(gs);

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();
        }
    }
Frantumn
  • 1,545
  • 6
  • 32
  • 57

2 Answers2

2

System.Diagnostics.Process.Start(gs); takes 2 parms. a file, and then args. I had to change the code to

System.Diagnostics.Process.Start(gsPath, gsArgs);
Frantumn
  • 1,545
  • 6
  • 32
  • 57
1

I would suggest you to use Ghostscript wrapper for .NET.

You can find one here: Ghostscript.NET on GitHub

Usage example can be found here: Ghostscript Processor C# Sample

There is also an example on how to add the watermark with a -c switch which postscript you can simply replace with your cropbox postscript: Ghostscript.NET - Passing Postscript commands (take a look at the bottom function)

HABJAN
  • 8,803
  • 3
  • 32
  • 54