基于Python實(shí)現(xiàn)簡(jiǎn)單的PDF批量壓縮工具
前言
在日常工作中,我們經(jīng)常會(huì)遇到 PDF 文件太大、不便于傳輸或上傳的問(wèn)題。雖然網(wǎng)上有許多 PDF 壓縮工具,但:
- 有些要付費(fèi)
- 有些限制文件大小
- 有些需要上傳到不可信的網(wǎng)站
因此,使用 Python + Ghostscript 自己寫(xiě)一個(gè)“本地 PDF 壓縮工具”就非常有必要。
本文提供一個(gè) 完整的可運(yùn)行腳本:
- 支持 單文件壓縮
- 支持 批量掃描目錄壓縮(可逐個(gè)確認(rèn))
- 支持選擇不同壓縮等級(jí)
- 自動(dòng)檢測(cè) Ghostscript
- 輸出壓縮結(jié)果總結(jié)
非常適合作為實(shí)用腳本收藏!
功能特點(diǎn)
1. 支持四種壓縮等級(jí)
/screen:最低質(zhì)量,體積最小/ebook:推薦,平衡質(zhì)量/printer:適合打印/prepress:最高質(zhì)量(印刷)
2. 支持兩種輸入模式
- 輸入文件路徑 → 壓縮單個(gè) PDF
- 直接回車(chē) → 自動(dòng)掃描
output_pdfs目錄批量處理
3. 逐個(gè)確認(rèn)壓縮
每個(gè)文件你都可以選擇:
y壓縮n跳過(guò)a剩余全部壓縮q退出
4. 自動(dòng)檢測(cè) Ghostscript
支持 Windows / macOS / Linux。
程序代碼(可直接運(yùn)行)
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import os
import subprocess
import sys
import platform
import shutil
# ===== 配置 =====
BATCH_INPUT_DIR = "output_pdfs" # 批量模式默認(rèn)掃描此文件夾
output_dir = "pdf_output" # 輸出目錄
# 壓縮等級(jí)選項(xiàng)
COMPRESSION_LEVELS = {
"1": ("/screen", "屏幕查看 (72dpi, 最小文件)"),
"2": ("/ebook", "電子書(shū) (150dpi, 平衡質(zhì)量)"),
"3": ("/printer", "打印 (300dpi, 高質(zhì)量)"),
"4": ("/prepress", "印刷 (300dpi+, 最高保真)")
}
DEFAULT_LEVEL = "2"
# ===== 交互式選擇壓縮等級(jí) =====
def select_compression_level():
print("\n請(qǐng)選擇壓縮等級(jí):")
for k, (_, desc) in COMPRESSION_LEVELS.items():
print(f" {k}. {desc}")
print(f"默認(rèn): {COMPRESSION_LEVELS[DEFAULT_LEVEL][1]}")
while True:
choice = input(f"\n請(qǐng)輸入編號(hào) (1-4) [回車(chē)默認(rèn) {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("無(wú)效輸入,請(qǐng)輸入 1-4")
# ===== 自動(dòng)檢測(cè) 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請(qǐng)先安裝:")
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}`")
# ===== 選擇輸入:?jiǎn)挝募?or 批量 =====
print("\n" + "="*60)
print(" PDF 壓縮工具 - 逐個(gè)確認(rèn)壓縮")
print("="*60)
input_path = input(f"\n輸入 PDF 文件路徑(或回車(chē)掃描 `{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}` 中無(wú) PDF 文件")
sys.exit(0)
print(f"批量模式: 共 {len(pdf_files)} 個(gè)文件")
# ===== 選擇壓縮等級(jí) =====
compression_level = select_compression_level()
# ===== 創(chuàng)建輸出目錄 =====
os.makedirs(output_dir, exist_ok=True)
# ===== 逐個(gè)確認(rèn)壓縮 =====
failed = []
skipped = []
compressed = []
print("\n" + "-"*60)
print("開(kāi)始處理(輸入 y=壓縮, n=跳過(guò), 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("請(qǐng)輸入 y, n, a 或 q")
if action == 'q':
print("用戶(hù)退出")
break
if action == 'n':
print(f"跳過(guò): {filename}")
skipped.append(filename)
continue
if action == 'a':
all_yes = True
print(f"全部壓縮(剩余 {len(pdf_files)-idx} 個(gè))")
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" 錯(cuò)誤: {e}")
failed.append(filename)
# ===== 最終總結(jié) =====
total = len(pdf_files)
done = len(compressed) + len(skipped) + len(failed)
print("\n" + "="*60)
print("壓縮總結(jié)")
print(f" 總文件: {total}")
print(f" 已壓縮: {len(compressed)}")
print(f" 已跳過(guò): {len(skipped)}")
print(f" 失敗: {len(failed)}")
if failed:
print(f" 失敗文件: {', '.join(failed)}")
if skipped:
print(f" 跳過(guò)文件: {', '.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
常見(jiàn)問(wèn)題
Q1:壓縮后圖片模糊怎么辦?
使用 /printer 或 /prepress:
- 打印模式(300dpi)
- 印刷模式(最高質(zhì)量)
總結(jié)
這是一個(gè)非常實(shí)用的 Python 工具腳本:
- 零依賴(lài)(只需要 Ghostscript)
- 支持批量、單文件
- 支持交互式選擇
- 安全(完全本地)
以上就是基于Python實(shí)現(xiàn)簡(jiǎn)單的PDF批量壓縮工具的詳細(xì)內(nèi)容,更多關(guān)于Python PDF壓縮的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Python使用多進(jìn)程執(zhí)行同一個(gè)函數(shù)的多種方法
本文介紹了在Python中使用多進(jìn)程執(zhí)行相同函數(shù)的三種方法:Process類(lèi)、Pool進(jìn)程池和apply_async異步執(zhí)行,比較了各種方法的適用場(chǎng)景、優(yōu)缺點(diǎn),并提供了實(shí)用技巧和注意事項(xiàng),推薦使用Pool進(jìn)程池處理大量任務(wù),它簡(jiǎn)單易用且自動(dòng)負(fù)載均衡,需要的朋友可以參考下2026-04-04
python?查看cpu的核數(shù)實(shí)現(xiàn)
這篇文章主要介紹了python?查看cpu的核數(shù)的實(shí)現(xiàn)方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-05-05
Python使用pyttsx3庫(kù)實(shí)現(xiàn)離線文字轉(zhuǎn)語(yǔ)音功能
文章介紹了pyttsx3庫(kù),這是一個(gè)用于Python的離線文本轉(zhuǎn)語(yǔ)音庫(kù),支持跨平臺(tái)使用,它能夠?qū)崿F(xiàn)基礎(chǔ)文本轉(zhuǎn)語(yǔ)音、自定義語(yǔ)速和音量、切換語(yǔ)音類(lèi)型、中斷語(yǔ)音、批量朗讀文件和將語(yǔ)音保存為音頻文件等功能,需要的朋友可以參考下2026-01-01
python實(shí)現(xiàn)自動(dòng)登錄后臺(tái)管理系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了python實(shí)現(xiàn)自動(dòng)登錄后臺(tái)管理系統(tǒng),并進(jìn)行后續(xù)操作,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-10-10
玩轉(zhuǎn)python爬蟲(chóng)之正則表達(dá)式
這篇文章主要介紹了python爬蟲(chóng)的正則表達(dá)式,正則表達(dá)式在Python爬蟲(chóng)是必不可少的神兵利器,本文整理了Python中的正則表達(dá)式的相關(guān)內(nèi)容,感興趣的小伙伴們可以參考一下2016-02-02

