Skip to content

Instantly share code, notes, and snippets.

@jcl86
Created October 9, 2021 16:37
Show Gist options
  • Save jcl86/2ac2d22126920fc25c543a8141528ae3 to your computer and use it in GitHub Desktop.
Save jcl86/2ac2d22126920fc25c543a8141528ae3 to your computer and use it in GitHub Desktop.
Compress pdf file with ghostscript
public static class CompressionExtensions
{
//The binaries of ghostscript should be included in the application directory to make this work, in this case gswin32c. (Only for windows)
public static void CompressPDF(string inputFile, string outPutFile, CompressionOption compressionOption = CompressionOption.Printer)
{
Process proc = new Process();
ProcessStartInfo psi = new ProcessStartInfo
{
CreateNoWindow = true,
ErrorDialog = false,
UseShellExecute = false,
WindowStyle = ProcessWindowStyle.Hidden
};
string fileName = Path.Combine(Directory.GetCurrentDirectory(), "gswin32c");
psi.FileName = fileName;
string args = $"-sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dPDFSETTINGS=/{compressionOption.ToString().ToLower()}" +
$" -dNOPAUSE -dQUIET -dBATCH -sOutputFile=\"{outPutFile}\" \"{inputFile}\"";
psi.Arguments = args;
//start the execution
proc.StartInfo = psi;
proc.Start();
proc.WaitForExit();
}
}
public enum CompressionOption
{
// - /screen selects low-resolution output similar to the Acrobat Distiller "Screen Optimized" setting.
Screen,
// - /ebook selects medium-resolution output similar to the Acrobat Distiller "eBook" setting.
Ebook,
// - /printer selects output similar to the Acrobat Distiller "Print Optimized" setting.
Printer,
// - /prepress selects output similar to Acrobat Distiller "Prepress Optimized" setting.
Prepress,
// - /default selects output intended to be useful across a wide variety of uses, possibly at the expense of a larger output file.
Default
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment