How to reduce the size of a PDF file with a Python 3 script
It is common to find upload forms that require PDF documents under a strict size limit. In those situations a local compression workflow is often the simplest solution.
Instead of uploading the file to a random website, this article shows how to compress PDFs locally with Python and Ghostscript. Repository: https://github.com/al118345/pdfconpython3
Video: https://www.youtube.com/watch?v=Qc6WG2k5tFk
File compression in Python
The following script contains the required methods to execute PDF compression with Python 3:
compress method
The compress function receives the input path, the output path and the compression level. A value of 4 applies stronger compression, while 1 preserves more quality.
The method relies on Ghostscript with these flags:
- -sDEVICE=pdfwrite
- -dCompatibilityLevel=1.4
- -dPDFSETTINGS=[0-4]
- dNOPAUSE
- -dQUIET
- -dBATCH
Important: use a different output path and do not overwrite the original file directly.
get_ghostscript_path method
This helper returns the path to the Ghostscript executable available in the system.
Main method
A basic batch usage example looks like this:
The script loops through all files in a folder and stores the compressed PDFs in a different destination folder.