Skip to content

Instantly share code, notes, and snippets.

@jmetzz
Created February 21, 2021 12:18
Show Gist options
  • Save jmetzz/0347bdf37c054989d264ddd43d6f44b0 to your computer and use it in GitHub Desktop.
Save jmetzz/0347bdf37c054989d264ddd43d6f44b0 to your computer and use it in GitHub Desktop.

Compress pdf files

I was looking for a good enough solution to compress pdf files, one which I could use to create scripts and automate some tasks.

Buy a Pdf Compressor license for use once per year is not an option for.

Luckly there exists GhostScript.

So, if you have GhostScript installed in your machine it is pretty easy to compress some files without losing too much quality.

Here it is what I've done

Install GhostScript

brew install ghostscript

Run gs to compress the file

gs -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dPDFSETTINGS=/printer -dNOPAUSE -dQUIET -dBATCH  -sOutputFile=output.pdf input.pdf

There are a myriad of options you can fiddle with to compress the file. The most important one is the -dPDFSETTINGS. According to the documentation, a few options you can use are:

  • /screen selects low-resolution output ("Screen Optimized" setting).
  • /ebook selects medium-resolution output ("eBook" setting).
  • /printer selects output print optimized setting.
  • /default.

More detailed options are available in: distillerparams

Have a look at the Official documentation

Note that by default Ghostscript removes hyperlinks from PDFs. To preserve links, include the flag -dPrinted=false.

If you want to run in batch mode for all files in a directory:

find . -name '*.pdf' | while read pdf; do gs -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dPDFSETTINGS=/printer -dNOPAUSE -dQUIET -dBATCH -sOutputFile="${pdf}_new.pdf" "$pdf"; done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment