Certainly! Below is a Python script that uses Ghostscript to compress a PDF file while preserving the quality of the document. This script utilizes the subprocess module to call Ghostscript with appropriate parameters to ensure that images within the PDF are compressed efficiently without significant loss of quality.
Before running the script, make sure that Ghostscript is installed on your system and accessible from your PATH. You can download Ghostscript from here.
import subprocess
import sys
import os
def compress_pdf(input_file, output_file):
try:
# Check if Ghostscript is installed
gs_installed = False
try:
subprocess.run(['gs', '--version'], check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
gs_installed = True
except (subprocess.CalledProcessError, FileNotFoundError):
pass
if not gs_installed:
print("Ghostscript is not installed or not found in PATH.")
return
# Ghostscript command with parameters for high-quality compression
gs_command = [
'gs',
'-sDEVICE=pdfwrite',
'-dCompatibilityLevel=1.4',
'-dPDFSETTINGS=/prepress',
'-dColorImageDownsampleType=/Bicubic',
'-dColorImageResolution=300',
'-dGrayImageDownsampleType=/Bicubic',
'-dGrayImageResolution=300',
'-dMonoImageDownsampleType=/Subsample',
'-dMonoImageResolution=1200',
'-dCompressFonts=true',
'-dEmbedAllFonts=true',
'-dSubsetFonts=true',
'-dAutoRotatePages=/None',
'-dNOPAUSE',
'-dQUIET',
'-dBATCH',
'-sOutputFile=' + output_file,
input_file
]
subprocess.run(gs_command, check=True)
print(f"Compressed PDF saved as '{output_file}'.")
except Exception as e:
print(f"Error: {e}")
def main():
if len(sys.argv) < 2:
print("Usage: python compress_pdf.py input.pdf [output.pdf]")
sys.exit(1)
input_file = sys.argv[1]
if len(sys.argv) >= 3:
output_file = sys.argv[2]
else:
base, ext = os.path.splitext(input_file)
output_file = base + '_compressed.pdf'
compress_pdf(input_file, output_file)
if __name__ == '__main__':
main()
Usage:
Save the script as compress_pdf.py and run it from the command line:
python compress_pdf.py input.pdf output.pdf
If you omit output.pdf, the script will create a new file named input_compressed.pdf.
Explanation:
- Ghostscript Command Parameters:
-sDEVICE=pdfwrite: Specifies the output device as PDF.
-dCompatibilityLevel=1.4: Sets the PDF version compatibility.
-dPDFSETTINGS=/prepress: High-quality output suitable for prepress; preserves color and detail.
-dColorImageDownsampleType=/Bicubic: Uses bicubic downsampling for color images.
-dColorImageResolution=300: Sets color image resolution to 300 DPI.
-dGrayImageDownsampleType=/Bicubic: Uses bicubic downsampling for grayscale images.
-dGrayImageResolution=300: Sets grayscale image resolution to 300 DPI.
-dMonoImageDownsampleType=/Subsample: Uses subsampling for monochrome images.
-dMonoImageResolution=1200: Sets monochrome image resolution to 1200 DPI.
-dCompressFonts=true: Enables font compression.
-dEmbedAllFonts=true: Embeds all fonts in the PDF.
-dSubsetFonts=true: Subsets fonts to include only the necessary characters.
-dAutoRotatePages=/None: Disables automatic page rotation.
-dNOPAUSE -dQUIET -dBATCH: Runs Ghostscript without user interaction.
These settings aim to preserve the document's quality by maintaining a reasonable resolution for images and ensuring that fonts are embedded correctly.
Note:
- Adjust the image resolutions (
-dColorImageResolution, -dGrayImageResolution, -dMonoImageResolution) if needed. Higher resolutions result in larger file sizes but better quality.
- The script checks if Ghostscript is installed before attempting to run the compression.
- Ensure that you have the necessary permissions to read the input file and write the output file.
Additional Tips:
- For maximum compression, you can experiment with
-dPDFSETTINGS=/ebook or -dPDFSETTINGS=/screen, but these settings will reduce image quality.
- If you find that the compressed PDF is still too large, consider reducing the image resolutions or adjusting the quality settings.
By using this script, you can batch process PDFs and compress them efficiently without compromising the quality of the documents.