基于Python實現(xiàn)簡單的PDF批量壓縮工具
更新時間:2025年12月01日 09:34:35 作者:weixin_46244623
在日常工作中,我們經(jīng)常會遇到 PDF 文件太大、不便于傳輸或上傳的問題,下面我們就來看看如何使用Python實現(xiàn)PDF批量壓縮,支持逐個確認,批量處理,多級壓縮
前言
在日常工作中,我們經(jīng)常會遇到 PDF 文件太大、不便于傳輸或上傳的問題。雖然網(wǎng)上有許多 PDF 壓縮工具,但:
- 有些要付費
- 有些限制文件大小
- 有些需要上傳到不可信的網(wǎng)站
因此,使用 Python + Ghostscript 自己寫一個“本地 PDF 壓縮工具”就非常有必要。
本文提供一個 完整的可運行腳本:
- 支持 單文件壓縮
- 支持 批量掃描目錄壓縮(可逐個確認)
- 支持選擇不同壓縮等級
- 自動檢測 Ghostscript
- 輸出壓縮結果總結
非常適合作為實用腳本收藏!
功能特點
1. 支持四種壓縮等級
/screen:最低質量,體積最小/ebook:推薦,平衡質量/printer:適合打印/prepress:最高質量(印刷)
2. 支持兩種輸入模式
- 輸入文件路徑 → 壓縮單個 PDF
- 直接回車 → 自動掃描
output_pdfs目錄批量處理
3. 逐個確認壓縮
每個文件你都可以選擇:
y壓縮n跳過a剩余全部壓縮q退出
4. 自動檢測 Ghostscript
支持 Windows / macOS / Linux。
程序代碼(可直接運行)
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import subprocess
import sys
import platform
import shutil
# ===== 配置 =====
BATCH_INPUT_DIR = "output_pdfs" # 批量模式默認掃描此文件夾
output_dir = "pdf_output" # 輸出目錄
# 壓縮等級選項
COMPRESSION_LEVELS = {
"1": ("/screen", "屏幕查看 (72dpi, 最小文件)"),
"2": ("/ebook", "電子書 (150dpi, 平衡質量)"),
"3": ("/printer", "打印 (300dpi, 高質量)"),
"4": ("/prepress", "印刷 (300dpi+, 最高保真)")
}
DEFAULT_LEVEL = "2"
# ===== 交互式選擇壓縮等級 =====
def select_compression_level():
print("\n請選擇壓縮等級:")
for k, (_, desc) in COMPRESSION_LEVELS.items():
print(f" {k}. {desc}")
print(f"默認: {COMPRESSION_LEVELS[DEFAULT_LEVEL][1]}")
while True:
choice = input(f"\n請輸入編號 (1-4) [回車默認 {DEFAULT_LEVEL}]: ").strip()
if not choice:
choice = DEFAULT_LEVEL
if choice in COMPRESSION_LEVELS:
level, desc = COMPRESSION_LEVELS[choice]
print(f"\n已選擇: {desc}")
return level
print("無效輸入,請輸入 1-4")
# ===== 自動檢測 Ghostscript =====
def find_gs_command():
system = platform.system()
candidates = ["gs"] if system != "Windows" else ["gswin64c", "gswin32c", "gs"]
for cmd in candidates:
if shutil.which(cmd):
return cmd
return None
gs_cmd = find_gs_command()
if not gs_cmd:
print("未找到 Ghostscript!")
print("\n請先安裝:")
if platform.system() == "Windows":
print(" 下載:https://www.ghostscript.com/download/gsdnld.html")
elif platform.system() == "Darwin":
print(" brew install ghostscript")
else:
print(" sudo apt install ghostscript")
sys.exit(1)
print(f"使用 Ghostscript: `{gs_cmd}`")
# ===== 選擇輸入:單文件 or 批量 =====
print("\n" + "="*60)
print(" PDF 壓縮工具 - 逐個確認壓縮")
print("="*60)
input_path = input(f"\n輸入 PDF 文件路徑(或回車掃描 `{BATCH_INPUT_DIR}`): ").strip()
# 收集待處理文件
if input_path:
if not os.path.exists(input_path):
print("文件不存在")
sys.exit(1)
if not input_path.lower().endswith(".pdf"):
print("僅支持 .pdf")
sys.exit(1)
pdf_files = [(os.path.basename(input_path), input_path)]
print(f"單文件模式: {input_path}")
else:
if not os.path.isdir(BATCH_INPUT_DIR):
print(f"目錄不存在: {BATCH_INPUT_DIR}")
sys.exit(1)
pdf_files = [
(f, os.path.join(BATCH_INPUT_DIR, f))
for f in os.listdir(BATCH_INPUT_DIR)
if f.lower().endswith(".pdf") and os.path.isfile(os.path.join(BATCH_INPUT_DIR, f))
]
if not pdf_files:
print(f"`{BATCH_INPUT_DIR}` 中無 PDF 文件")
sys.exit(0)
print(f"批量模式: 共 {len(pdf_files)} 個文件")
# ===== 選擇壓縮等級 =====
compression_level = select_compression_level()
# ===== 創(chuàng)建輸出目錄 =====
os.makedirs(output_dir, exist_ok=True)
# ===== 逐個確認壓縮 =====
failed = []
skipped = []
compressed = []
print("\n" + "-"*60)
print("開始處理(輸入 y=壓縮, n=跳過, a=全部壓縮, q=退出)")
print("-"*60)
all_yes = False
for idx, (filename, input_path) in enumerate(pdf_files, 1):
if all_yes:
action = 'y'
else:
while True:
prompt = f"\n[{idx}/{len(pdf_files)}] 壓縮 '{filename}'? (y/n/a/q): "
action = input(prompt).strip().lower()
if action in {'y', 'n', 'a', 'q'}:
break
print("請輸入 y, n, a 或 q")
if action == 'q':
print("用戶退出")
break
if action == 'n':
print(f"跳過: {filename}")
skipped.append(filename)
continue
if action == 'a':
all_yes = True
print(f"全部壓縮(剩余 {len(pdf_files)-idx} 個)")
output_path = os.path.join(output_dir, filename)
cmd = [
gs_cmd,
"-sDEVICE=pdfwrite",
"-dCompatibilityLevel=1.4",
f"-dPDFSETTINGS={compression_level}",
"-dNOPAUSE",
"-dQUIET",
"-dBATCH",
f"-sOutputFile={output_path}",
input_path
]
try:
print(f"壓縮中: {filename} ...", end="")
subprocess.run(cmd, check=True, capture_output=True, text=True)
print(" 完成")
compressed.append(filename)
except subprocess.CalledProcessError as e:
print(f" 失敗")
failed.append(filename)
except Exception as e:
print(f" 錯誤: {e}")
failed.append(filename)
# ===== 最終總結 =====
total = len(pdf_files)
done = len(compressed) + len(skipped) + len(failed)
print("\n" + "="*60)
print("壓縮總結")
print(f" 總文件: {total}")
print(f" 已壓縮: {len(compressed)}")
print(f" 已跳過: {len(skipped)}")
print(f" 失敗: {len(failed)}")
if failed:
print(f" 失敗文件: {', '.join(failed)}")
if skipped:
print(f" 跳過文件: {', '.join(skipped[:10])}{'...' if len(skipped)>10 else ''}")
print(f" 輸出目錄: {os.path.abspath(output_dir)}")
print("="*60)
安裝 Ghostscript(必須)
Windows:下載地址
macOS
brew install ghostscript
Linux
sudo apt install ghostscript
常見問題
Q1:壓縮后圖片模糊怎么辦?
使用 /printer 或 /prepress:
- 打印模式(300dpi)
- 印刷模式(最高質量)
總結
這是一個非常實用的 Python 工具腳本:
- 零依賴(只需要 Ghostscript)
- 支持批量、單文件
- 支持交互式選擇
- 安全(完全本地)
以上就是基于Python實現(xiàn)簡單的PDF批量壓縮工具的詳細內(nèi)容,更多關于Python PDF壓縮的資料請關注腳本之家其它相關文章!
相關文章
Python結合JSON實現(xiàn)動態(tài)按鈕管理程序
這篇文章主要為大家詳細介紹了如何使用Python的wxPython庫結合JSON配置文件,開發(fā)一個支持動態(tài)按鈕創(chuàng)建,文件執(zhí)行和配置管理的桌面應用程序,感興趣的可以了解下2025-04-04

