Compress PDF files using GhostScript

This post describes method how to automate process of compressing PDF files in Mac or Linux environments using GhostScript library.

First of all you need to install GhostScript library on your computer. On mac os you can do it with brew:

brew install ghostscript
Install GhostScript on Mac OS with Brew

Or using apt on Linux systems

sudo apt update
sudo apt install ghostscript
Install GhostScipt on Linux using apt

Now you can do converting using gs command in terminal. There are a lot of options, but here I would give you my solution.

gs -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dPDFSETTINGS=/default \
   -dNOPAUSE -dQUIET -dBATCH -dDetectDuplicateImages \
   -dCompressFonts=true -r150 -sOutputFile=output.pdf input.pdf

If you would like to make shortcut in your terminal to start this commands quicker, you can add this code to your ~/.zshrc file.

nano ~/.zshrc
pdfcompress ()
{
   mkdir -p compressed
        gs -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dPDFSETTINGS=/default \
                -dNOPAUSE -dQUIET -dBATCH -dDetectDuplicateImages \
                -dCompressFonts=true -r150 -sOutputFile=compressed/$1 $1
}
pdfcompressall (){
   for i in $(ls | grep .pdf); do pdfcompress "$i"; done
}

This will allow you call GhostScript command as pdfcompress name_of_pdf.pdf to compress one pdf file, or using pdfcompressall to compress all pdf files in current folder.