Bash script to compress pdf files

Since I work as a freelance, I have to deal with a lot of pdf files I receive from clients. Some of them contain uncompressed images that make the files bigger than they need to be.

On this stackexchange question, a user named Marco gives us a nice way to use ghostscript to compress any pdf file.

There is a loss of quality in the compression, but most of the time it is acceptable.

Here is the script:



# save metadata
pdftk "$INPUTPDF" dump_data_utf8 > "$METADATA"

# compress
gs                       \
  -q                     \
  -sOutputFile="$TMPPDF" \
  -sDEVICE=pdfwrite      \
  -dNOPAUSE              \
  -dBATCH                \
  -dPDFSETTINGS=/ebook   \

# restore metadata
pdftk "$TMPPDF" update_info_utf8 "$METADATA" output "$OUTPUTPDF"

# clean up

If you liked this, you can follow me on twitter: @guillaumecherea