Skip to content

Compress PDF Files from the Command Line Using a Bash Function

Updated: at 02:05 PM

As someone who often needs to send PDF files via email, I wanted a solution that would allow me to reduce file sizes quickly without compromising security. Many online services can shrink PDFs, but they require you to upload your files to a third-party server, which might not be secure. To address this, I created a simple tool that works right from the command line, ensuring your files stay on your computer and remain private.

The tool I created is a bash function called smallpdf. It uses a program called Ghostscript, which needs to be installed on your computer but is usually just a quick download away. This function is great for anyone familiar with basic command line operations and is particularly handy.

Here’s how the script looks:

smallpdf() {
    if [ "$#" -lt 1 ]; then
        echo "Usage: smallpdf [input file] [screen*|ebook|printer|prepress]"
        return 1
    fi

    local output_file="${1%.pdf}.compressed.pdf"
    gs -sDEVICE=pdfwrite -dNOPAUSE -dQUIET -dBATCH -dPDFSETTINGS=/${2:-"screen"} -dCompatibilityLevel=1.4 -sOutputFile="$output_file" "$1"
}

Using smallpdf is very straightforward. First, ensure Ghostscript is installed on your system. Once you’re set up, you can start compressing PDFs with this simple command by adding it to your ~/.zshrc configuration if you are on macOS.

Here’s the basic format:

smallpdf [input file] [screen*|ebook|printer|prepress]

The name of the compressed file will be similar to your original file but will end in .compressed.pdf.

For instance, if you want to shrink a PDF for emailing, you might type:

smallpdf mydocument.pdf

For a PDF that’s going to have some detailed graphics, you could use:

smallpdf mydocument.pdf printer