Compress a PDF file on Linux via the CLI

Want to help support this blog? Try out Oh Dear, the best all-in-one monitoring tool for your entire website, co-founded by me (the guy that wrote this blogpost). Start with a 10-day trial, no strings attached.

We offer uptime monitoring, SSL checks, broken links checking, performance & cronjob monitoring, branded status pages & so much more. Try us out today!

Profile image of Mattias Geniar

Mattias Geniar, October 05, 2014

Follow me on Twitter as @mattiasgeniar

If you’re processing large PDF files, you may want to optimize the filesize. Here’s what I found to be working. These tools all require Ghostscript.

$ yum install ghostscript
$ apt-get install ghostscript

Convert the PDF to the “ebook” format. For a few tests, this took 65% of the original filesize (18MB to 6MB).

$ gs -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dPDFSETTINGS=/ebook \
       -dNOPAUSE -dBATCH  -dQUIET -sOutputFile=output.pdf input.pdf

If you want to try, you can also try the “screen” format. This reduced the test PDFs from 18MB to 1.5MB, so a very large reduction, but image quality inside the PDF was no longer up to the standards.

$ gs -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dPDFSETTINGS=/screen \
       -dNOPAUSE -dBATCH  -dQUIET -sOutputFile=output.pdf input.pdf

I’ve read reports that using ghostscript to convert the PDF to GhostScript format and back to PDF can also substantially reduce the filesize. My tests did not confirm this, I ended up with files +15% larger. You’ll need to test this for your own needs.

$ pdf2ps original.pdf original.ps
$ ps2pdf original.ps new.pdf

And when all else fails, just compress the file with zip (zip instead of gzip/tar, to help our Windows friends with opening the files more easily).

$ zip file.zip original.pdf

Should anyone else have more tips, I’d love to hear them!



Want to subscribe to the cron.weekly newsletter?

I write a weekly-ish newsletter on Linux, open source & webdevelopment called cron.weekly.

It features the latest news, guides & tutorials and new open source projects. You can sign up via email below.

No spam. Just some good, practical Linux & open source content.