Apr-16-2024, 05:21 PM
This code prompts the user for an input & output path/filename, and compresses the original PDF. This is a huge asset when working with PDF images that are a large size by default. Must have Ghostscript(GS) installed, and hardcode the path to the GS installation in line eight (ghostscript_path =). For use with Python 3.
import subprocess import os from pathlib import Path def compress_pdf_file(input_path, output_path): try: # Specify the path to Ghostscript executable (gswin32c or gswin64c) ghostscript_path = "C:\\Program Files\\gs\\gs10.03.0\\bin\\gswin64c" # Adjust this path as needed subprocess.call([ ghostscript_path, "-q", "-sDEVICE=pdfwrite", "-dCompatibilityLevel=1.3", # Set PDF version to 1.3 "-dPDFSETTINGS=/prepress", # Optimize for prepress quality "-dNOPAUSE", "-dBATCH", "-sOutputFile=" + output_path, input_path, ]) return output_path except FileNotFoundError: print("Error: Ghostscript (gs) not found. Please install Ghostscript.") return None def main(): input_pdf_path = input("Enter the path to the input PDF file: ") output_pdf_path = input("Enter the path to save the optimized PDF file: ") compressed_path = compress_pdf_file(input_pdf_path, output_pdf_path) if compressed_path: print(f"PDF successfully optimized and saved as {compressed_path}") if __name__ == "__main__": main()