2026年4月28日 星期二

只要點兩下,就能將input資料夾內所有PDF進行容量壓縮

系列文章:
01.python 不管何時何地,只要點兩下,資料夾內的所有pdf都會合併成一個pdf
https://skjhcreator.blogspot.com/2022/06/pythonpdfpdf.html
02.python 只要點兩下,分別對各資料夾內的pdf合併,合併後的檔名要讓人知道來自哪個資料夾 
https://skjhcreator.blogspot.com/2022/06/python-pdf.html
03. 只要點兩下,就能將一堆的Doc與Docx 轉成 PDF
03.https://skjhcreator.blogspot.com/2023/05/docdocx-pdf.html
04.只要點兩下,就能將一堆的JPG轉成一個PDF,並以JPG所在的資料夾名稱為PDF的檔名
04.https://skjhcreator.blogspot.com/2023/06/jpgpdfjpgpdf.html
05.只要點兩下,就能將放進input的一堆PDF轉成各自的WORD
05.https://skjhcreator.blogspot.com/2023/10/inputpdfword.html
06.只要點兩下,就能將放進input的一堆PDF轉成在ouput資料夾內的各自的WORD 
06.https://skjhcreator.blogspot.com/2023/10/inputpdfouputword.html
07.只要點兩下,就能夠將InputAndOutput資料夾底下的子子孫孫資料夾內所有Word通通轉成PDF
07.https://skjhcreator.blogspot.com/2024/09/word-word-pdf.html
08.只要點兩下,就可以將資料夾input內的所有Word通通轉成一個PDF
08.https://skjhcreator.blogspot.com/2025/07/inputwordpdf.html
09.只要點兩下兩次,就能依照設定拆分指定PDF頁數並合併成設定好的一個PDF
09.https://skjhcreator.blogspot.com/2025/09/pdfpdf.html
10.只要點兩下,就能將input資料夾內所有PDF進行容量壓縮
10.https://skjhcreator.blogspot.com/2026/04/inputpdf.html

Just double-click to compress all PDFs in the input folder.

        最近要上傳一大堆的PDF,常常因為PDF內的照片未經壓縮,導致整體容量過大。上傳時又因容量過大,導致無法上傳。上傳網站要求多少容量內的PDF才能上傳。問題是PDF不是我做的,偏偏又要發回或通知原主,要做PDF壓縮,才能上傳。如此的一來一往,浪費很多時間。能不能有個程式,讓我點個兩下就能將這些PDF進行壓縮,而不用再跟原主溝通?

        Recently, I’ve had to upload a large number of PDFs, but they’re often too big because the images inside them haven’t been compressed. As a result, the files exceed the upload size limit and can’t be uploaded. The website requires PDFs to be under a certain size, but the problem is that I didn’t create these PDFs. I end up having to send them back or notify the original creator to compress them before I can upload them. This back-and-forth wastes a lot of time.

        Is there a program that would let me simply double-click and compress these PDFs myself, without needing to communicate with the original creator?

下載檔案解壓密碼:demo1234
Here is the website where you can download the program and find instructions:
Download。Extraction Password: demo1234
使用教學(Instructional videos):




方法:Python + Ghostscript
一、下載與安裝 Ghostscript
到 https://www.ghostscript.com/download/gsdnld.html 下載後,點兩下進行安裝

二、Python 程式碼
檔案:pyPdfCompress.py
檔案內容:import os
import subprocess
import shutil
import webbrowser
import sys
import argparse
import platform

INPUT_DIR = "input"
OUTPUT_DIR = "output"

quality_settings = {
    "screen": "/screen",
    "ebook": "/ebook",
    "printer": "/printer",
    "prepress": "/prepress"
}


def check_ghostscript():
    gs = shutil.which("gswin64c") or shutil.which("gs")

    if gs is None:
        print("[未安裝Ghostscript]")

        if platform.system() == "Windows":
            print("請下載 Windows 版本 (gswin64)")
        else:
            print("請下載對應系統版本")

        print("即將開啟下載頁面...")

        webbrowser.open("https://www.ghostscript.com/download/gsdnld.html")

        print("若已安裝,請確認 Ghostscript 已加入 PATH")

        sys.exit(1)

    return gs


def compress_pdf(gs_command, input_path, output_path, quality):
    cmd = [
        gs_command,
        "-sDEVICE=pdfwrite",
        "-dCompatibilityLevel=1.4",
        f"-dPDFSETTINGS={quality_settings.get(quality, '/ebook')}",
        "-dNOPAUSE",
        "-dQUIET",
        "-dBATCH",
        f"-sOutputFile={output_path}",
        input_path
    ]

    result = subprocess.run(cmd, capture_output=True, text=True)

    if result.returncode != 0:
        raise RuntimeError(result.stderr)


def process_file(gs_command, file, quality):
    input_path = os.path.join(INPUT_DIR, file)

    name, ext = os.path.splitext(file)
    output_path = os.path.join(OUTPUT_DIR, f"{name}_compressed{ext}")

    compress_pdf(gs_command, input_path, output_path, quality)

    original_size = os.path.getsize(input_path) / 1024
    compressed_size = os.path.getsize(output_path) / 1024

    print(f"✔ {file}")
    print(f"   原始: {original_size:.2f} KB")
    print(f"   壓縮: {compressed_size:.2f} KB")

    if compressed_size >= original_size:
        print(" 壓縮後反而變大,已刪除壓縮檔\n")
        os.remove(output_path)
        return

    reduction = original_size - compressed_size
    ratio = (1 - compressed_size / original_size) * 100

    print(f"   減少: {reduction:.2f} KB")
    print(f"   壓縮率: {ratio:.2f}%\n")


def main():
    parser = argparse.ArgumentParser(description="PDF 批次壓縮工具")
    parser.add_argument(
        "--quality",
        choices=quality_settings.keys(),
        default="ebook",
        help="壓縮品質 (預設: ebook)"
    )
    args = parser.parse_args()

    gs_command = check_ghostscript()

    if not os.path.exists(INPUT_DIR):
        os.makedirs(INPUT_DIR)
        print(f"📁 已建立資料夾: {INPUT_DIR},請放入 PDF 後重新執行")
        return

    if not os.path.exists(OUTPUT_DIR):
        os.makedirs(OUTPUT_DIR)

    files = [f for f in os.listdir(INPUT_DIR) if f.lower().endswith(".pdf")]

    if not files:
        print("📂 input 資料夾內沒有 PDF")
        return

    for file in files:
        try:
            process_file(gs_command, file, args.quality)
        except Exception as e:
            print(f"✖ 失敗: {file}")
            print(e)
            print()


if __name__ == "__main__":
    main()

沒有留言:

張貼留言

只要點兩下,就能將input資料夾內所有m4a 轉檔為 mp3

         最近需要將m4a檔案轉檔為mp3,所以寫python程式來處理。希望將很多的m4a放進input資料夾內,只要點兩下滑鼠就能將這些m4a 通通轉檔為 mp3。          Recently, I needed to convert M4A files in...