Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

pnrt/PDF-Compression

Open more actions menu

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

5 Commits
5 Commits
 
 
 
 
 
 

Repository files navigation

PDF Compression with Ghostscript & Python🗜️📄

Ghostscript
Python
License

A lightweight and efficient way to compress PDFs using Ghostscript (gs) and Python. Easily compress PDFs without losing quality using either the command line or a simple GUI.


🔧 Installation

1️⃣ Install Ghostscript

📌 macOS (Homebrew)

brew install ghostscript

📌 Windows

  1. Download Ghostscript from official site.
  2. Install and add it to your system PATH.

📌 Linux (Debian/Ubuntu)

sudo apt install ghostscript

2️⃣ Install Python Dependencies

pip install tkinter

tkinter is built into Python, but this ensures it's available.

🚀 Usage

🔹 Command Line

Run the following command to compress a PDF:

gs -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dPDFSETTINGS=/screen -dNOPAUSE -dBATCH -sOutputFile=output.pdf input.pdf

🔹 Compression Levels

Option Best For Compression Strength
/screen Smallest size (low-quality images) 🔥🔥🔥🔥
/ebook Good balance for reading 🔥🔥🔥
/printer Higher quality for printing 🔥🔥
/prepress Best for publishing (large files) 🔥

📌 Example Usage:

gs -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dPDFSETTINGS=/ebook -dNOPAUSE -dBATCH -sOutputFile=compressed.pdf original.pdf

📝 Python GUI for Easy PDF Compression

If you prefer a graphical interface, we have a simple Python Tkinter-based GUI for non-technical users.

📌 Run the Python GUI

python pdf_compressor_gui.py

🔹 Features

  • ✔ Select PDF file easily
  • ✔ Choose compression level (screen, ebook, printer, prepress)
  • ✔ One-click compression
  • ✔ User-friendly interface

📝 Python SGUI Code

If you want to automate compression using Python, you can use this script:

import subprocess
import os
import tkinter as tk
from tkinter import filedialog, messagebox, ttk

def compress_pdf(input_pdf, output_pdf, quality="screen"):
    """Compress PDF using Ghostscript without losing much quality."""
    gs_command = [
        "gs", "-sDEVICE=pdfwrite",
        "-dCompatibilityLevel=1.4",
        f"-dPDFSETTINGS=/{quality}",
        "-dNOPAUSE", "-dBATCH",
        f"-sOutputFile={output_pdf}",
        input_pdf
    ]

    try:
        subprocess.run(gs_command, check=True)
        original_size = os.path.getsize(input_pdf) / 1024
        compressed_size = os.path.getsize(output_pdf) / 1024
        reduction = 100 - ((compressed_size / original_size) * 100)

        messagebox.showinfo("Success", f"Compressed PDF saved at:\n{output_pdf}\n"
                                       f"Original: {original_size:.2f} KB\n"
                                       f"Compressed: {compressed_size:.2f} KB\n"
                                       f"Size Reduced: {reduction:.2f}%")

    except subprocess.CalledProcessError as e:
        messagebox.showerror("Error", f"Compression failed: {e}")

def browse_pdf():
    """Select a PDF file."""
    file_path = filedialog.askopenfilename(filetypes=[("PDF Files", "*.pdf")])
    if file_path:
        input_entry.delete(0, tk.END)
        input_entry.insert(0, file_path)

def save_pdf():
    """Select save location for the compressed PDF."""
    output_path = filedialog.asksaveasfilename(defaultextension=".pdf",
                                               filetypes=[("PDF Files", "*.pdf")])
    if output_path:
        output_entry.delete(0, tk.END)
        output_entry.insert(0, output_path)

def start_compression():
    """Start the compression process."""
    input_pdf = input_entry.get()
    output_pdf = output_entry.get()
    quality = quality_var.get()

    if not input_pdf or not output_pdf:
        messagebox.showwarning("Warning", "Please select input and output files.")
        return

    compress_pdf(input_pdf, output_pdf, quality)

# UI
root = tk.Tk()
root.title("PDF Compressor")
root.geometry("400x300")

ttk.Label(root, text="Select PDF File:").pack(pady=2)
input_entry = ttk.Entry(root, width=40)
input_entry.pack(pady=2)
ttk.Button(root, text="Browse", command=browse_pdf).pack(pady=2)

ttk.Label(root, text="Save Compressed PDF As:").pack(pady=2)
output_entry = ttk.Entry(root, width=40)
output_entry.pack(pady=2)
ttk.Button(root, text="Save As", command=save_pdf).pack(pady=2)

ttk.Label(root, text="Compression Quality:").pack(pady=2)
quality_var = tk.StringVar(value="screen")
quality_options = ["screen", "ebook", "printer", "prepress"]
quality_menu = ttk.Combobox(root, textvariable=quality_var, values=quality_options, state="readonly")
quality_menu.pack(pady=2)

ttk.Button(root, text="Compress PDF", command=start_compression).pack(pady=10)

root.mainloop()

💡 Why Use This Tool?

FCommand Line & GUI Available
No Quality Loss with Smart Compression
Works on Windows, macOS, & Linux
Easy for Both Developers & Non-Tech Users


📜 License

This project is licensed under the MIT License. Feel free to use and modify it!


⭐ Star this repo if you find it useful!

GitHub Repo stars


About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors

Languages

Morty Proxy This is a proxified and sanitized view of the page, visit original site.