Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Reduce PDF Size
#1
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()
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Reduce file size - simplify code Bloody_geek 3 3,297 Dec-10-2019, 06:36 AM
Last Post: joe_momma

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020