Compressing PDFs With Ghostscript

Previously, I was using Photoshop to processed scanned documents, convert them to PDFs and compress the PDF. The resulting PDFs were usually less than 800KB and that was OK for me. Lately I started using GIMP instead of Photoshop for this task and the PDFs that GIMP produced were a few megabytes in size. I looked for a way to compress them and found a nice utility called Ghostscript that processes PDFs and PostScript files. Here’s a script I found to compress PDFs using Ghostscript:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#!/bin/sh
set -e

if [ "$#" -ne 1 ]; then
  echo "Usage: $0 pdf-file" >&2
  echo "Compresses a PDF file using ghostscript" >&2
  exit 1
fi

TMP_FILE=/tmp/$(basename "$1")
mv "$1" "$TMP_FILE"
gs    -q -dNOPAUSE -dBATCH -dSAFER \
    -sDEVICE=pdfwrite \
    -dCompatibilityLevel=1.3 \
    -dEmbedAllFonts=true \
    -dSubsetFonts=true \
    -dColorImageDownsampleType=/Bicubic \
    -dColorImageResolution=72 \
    -dGrayImageDownsampleType=/Bicubic \
    -dGrayImageResolution=72 \
    -dMonoImageDownsampleType=/Bicubic \
    -dMonoImageResolution=72 \
    -sOutputFile="$1" \
    "$TMP_FILE"
# rm "$TMP_FILE"

The last line that removes the temporary file is optional because I would like to have a copy of the original file if the compression ends up looking too bad.