To efficiently compress your PDF, especially when a large portion of its size is due to a single high-resolution image, leveraging Ghostscript is a highly effective approach. Ghostscript is a powerful tool for processing PDF files and can significantly reduce the file size by optimizing image compression without compromising the quality.
Below is a Python script that utilizes Ghostscript to compress your PDF. This script sets parameters to ensure minimal quality loss while achieving maximum compression. It checks for Ghostscript installation and processes the PDF accordingly.
Prerequisites
-
Install Ghostscript
-
Windows: Download the installer from Ghostscript Downloads and follow the installation instructions.
-
macOS: You can install Ghostscript using Homebrew:
brew install ghostscript
-
Linux: Install via your distribution's package manager. For example, on Ubuntu:
sudo apt-get install ghostscript
-
Install Required Python Packages
Ensure you have Python installed (preferably Python 3.6 or higher). This script uses the subprocess module, which is part of the Python Standard Library, so no additional Python packages are required.
Python Script
import subprocess
import shutil
import sys
import os
def check_ghostscript():
"""Check if Ghostscript is installed."""
gs_path = shutil.which("gs")
if gs_path is None:
# On Windows, Ghostscript might be installed as 'gswin64c.exe' or 'gswin32c.exe'
gs_win = shutil.which("gswin64c") or shutil.which("gswin32c")
if gs_win is None:
print("Ghostscript is not installed or not added to PATH.")
print("Please install Ghostscript from https://www.ghostscript.com/download.html and ensure it's added to your system PATH.")
sys.exit(1)
else:
return gs_win
return gs_path
def compress_pdf(input_pdf, output_pdf):
"""Compress PDF using Ghostscript without compromising quality."""
gs_executable = check_ghostscript()
# Ghostscript command for optimal compression without significant quality loss
# Adjust the 'screen', 'ebook', 'printer', or 'prepress' settings based on your needs
# Here we use /prepress for minimal quality loss
gs_command = [
gs_executable,
"-sDEVICE=pdfwrite",
"-dCompatibilityLevel=1.5",
"-dPDFSETTINGS=/prepress", # Options: /screen, /ebook, /printer, /prepress, /default
"-dNOPAUSE",
"-dQUIET",
"-dBATCH",
f"-sOutputFile={output_pdf}",
input_pdf
]
try:
print("Compressing PDF...")
subprocess.run(gs_command, check=True)
print(f"Compression successful. Saved as '{output_pdf}'")
except subprocess.CalledProcessError as e:
print("An error occurred during PDF compression:", e)
sys.exit(1)
def main():
if len(sys.argv) != 3:
print("Usage: python compress_pdf.py input.pdf output.pdf")
sys.exit(1)
input_pdf = sys.argv[1]
output_pdf = sys.argv[2]
if not os.path.isfile(input_pdf):
print(f"Input file '{input_pdf}' does not exist.")
sys.exit(1)
compress_pdf(input_pdf, output_pdf)
if __name__ == "__main__":
main()
How to Use the Script
-
Save the Script
Save the above script to a file named compress_pdf.py.
-
Run the Script
Open your terminal or command prompt, navigate to the directory containing compress_pdf.py, and execute the following command:
python compress_pdf.py input.pdf output_compressed.pdf
- Replace
input.pdf with the path to your original PDF file.
- Replace
output_compressed.pdf with the desired path for the compressed PDF.
Understanding the Ghostscript Parameters
-
-sDEVICE=pdfwrite: Specifies the output device (PDF writer in this case).
-
-dCompatibilityLevel=1.5: Sets the compatibility level of the output PDF. You can adjust this based on your requirements.
-
-dPDFSETTINGS=/prepress: Determines the quality and compression level. Available options:
/screen: Lowest quality and smallest size.
/ebook: Medium quality and size.
/printer: High quality and larger size.
/prepress: Highest quality, suitable for printing.
/default: Default settings.
For your requirement of minimal quality loss, /prepress is recommended. If you find that the file size is still too large, you can experiment with /printer or /ebook.
-
-dNOPAUSE -dQUIET -dBATCH: These options run Ghostscript without pausing after each page, suppress non-essential output, and exit after processing, respectively.
-
-sOutputFile=output.pdf: Specifies the output file path.
Example
Suppose you have a PDF named large_document.pdf and you want to compress it to large_document_compressed.pdf. Run:
python compress_pdf.py large_document.pdf large_document_compressed.pdf
Additional Tips
-
Fine-Tuning Compression
If you need more control over the compression (e.g., specifically targeting image compression), you can modify the Ghostscript parameters. For instance, to control downsampling of images:
-dDownsampleColorImages=true
-dColorImageResolution=150
Add these parameters to the gs_command list as needed.
-
Handling Multiple PDFs
You can modify the script to handle multiple PDFs in a directory by iterating over files with a .pdf extension.
-
Error Handling
The script includes basic error handling. Ensure that the input PDF exists and that Ghostscript is properly installed and accessible via the command line.
Conclusion
This Python script provides a straightforward way to compress PDFs using Ghostscript while maintaining high-quality output. By adjusting the -dPDFSETTINGS parameter, you can balance between file size and quality based on your specific needs.
Feel free to enhance the script further, such as adding logging, handling batches of files, or integrating a graphical user interface for ease of use.