Home

Shrinking PDFs on Linux Command Line

Here is a script for shrinking PDFs. It uses gs, Ghostscript, to read in a PDF and to output a new one with a different quality. You can edit the quality by setting the quality variable in the script to any of the dPDFSETTINGS options. In general, gs will butcher images for reduced quality settings.

comppdf.sh

#!/bin/bash

# Recompresses PDFs
# J. Tao 2015


# Tweak "quality" for different compression.

#  -dPDFSETTINGS=configuration
#    Presets the "distiller parameters" to one of four predefined settings:
#
#      /screen selects low-resolution output similar to the Acrobat Distiller
#      "Screen Optimized" setting.
#
#      /ebook selects medium-resolution output similar to the Acrobat Distiller
#      "eBook" setting.
#
#      /printer selects output similar to the Acrobat Distiller "Print Optimized"
#      setting.
#
#      /prepress selects output similar to Acrobat Distiller "Prepress Optimized"
#      setting.
#
#      /default selects output intended to be useful across a wide variety of
#      uses, possibly at the expense of a larger output file. 

quality="/screen"


# Usage: takes an intput PDF and output PDF. When an output PDF is not given,
# the script outputs to STDOUT.
if [ $# -lt 1 -o $# -gt 2 ]; then
  echo "Usage: `basename $0` input.pdf [optional: output.pdf]" 1>&2
  exit 1
fi


# outputs to stdout
if [ $# -eq 1 ]; then
  gs -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dPDFSETTINGS=$quality \
  -dNOPAUSE -dQUIET -dBATCH -sOutputFile=%stdout "$1"
fi

# outputs to output file
if [ $# -eq 2 ]; then
  gs -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dPDFSETTINGS=$quality \
  -dNOPAUSE -dQUIET -dBATCH -sOutputFile="$2" "$1"
fi

Examples

I have named my script comppdf. The usage is as follows:

$ comppdf
Usage: comppdf input.pdf [optional: output.pdf]

The following example demonstrates passing two arguments to the script.

$ comppdf input.pdf output.pdf
$ du -h input.pdf output.pdf 
162M	input.pdf
139M	output.pdf

The following example demonstrates passing a single argument. In this case, the script dumps the new PDF to STDOUT, which can be redirected.

$ comppdf input.pdf > output.pdf
$ du -h input.pdf output.pdf 
162M	input.pdf
139M	output.pdf

Notes

Written on the 23rd of December in 2015.

References

  1. Mailman, "Compress PDF files on Linux," http://tuxdiary.com/2015/04/07/compress-pdf-files-linux/" , Accessed December 23, 2015.