メインコンテンツへスキップ
見出し画像

Ghostscript でPDFを圧縮する

    とある課から「Ghostscript使ったことある?」と尋ねられた。
    過去にプリンタードライバー的に使ったことがあったような気がしたので、
    「あったような気がしますが、何に使いたいんですか?」と返したところ
    「あるPDFを、圧縮して文字を読み取りにくくしたいんだけど・・・プラスダウンロードもさせたくない」で、GhostScriptにたどり着いたようでした。
    ということで、試しにAIに聞いてツール化した時の設定(最終結果)を残します。

    ダウンロードをさせないのはPDFの設定で出来るんだろうか・・・できない気がするのでとりあえずできる設定を入れてみたところです。

    Googleで検索した時の結果

    ライセンスはデュアルライセンスとのことで、社内利用やソースコードの公開が可能な場合はAGPLを、自社製品への組み込みやソースコードの非公開を希望する場合は商用ライセンスの取得が必要のようです。

    画像

    最初にAIに質問した内容(Google AI Studio)

    Docker インストール済み
    server.key,server.crt作成済み
    Docker で以下の要件を満たす環境を構築してほしい
    サーバーのipアドレスは 192.168.3.25/24
    
    #Ghostscriptインストール
    #WebサーバーにUIを用意すること
    
    ##WebUI
    #PDFの圧縮を行うパラメーターを選択または入力
    #PDFをドラッグ&ドロップするエリア
    #PDF変換ボタン
    
    ##PDF変換ボタンの挙動
    #PDFの圧縮・軽量化をパラメーターに合わせて実施する
    #複写禁止の透かし文字を入れる
    #Webのダウンロードで変換したPDFをダウンロードする
    
    #他に足りないものがあれば随時追加してほしい

    途中で直したりしたところ

    • 文字が圧縮されなかったので一度画像に変換してから圧縮してもらうようにした

    • エラーがで出たので何度かやり直し(定義不足等々)

    • 「複写禁止」の文字の出方を直してもらった

    • PDFを印刷できないようにした

    • gsの引数「-dJPEGQ」を設定すると荒くなりすぎたので消した(app.py)

    最終的なもの

    ディレクトリ構成

    pdf-tool/
    ├── app/
    │   ├── main.py
    │   ├── requirements.txt
    │   ├── Dockerfile
    │   └── templates/
    │       └── index.html
    ├── nginx/
    │   ├── conf.d/
    │   │   └── default.conf
    │   └── ssl/
    │       ├── server.crt
    │       └── server.key
    └── docker-compose.yml

    app/main.py

    import os
    import subprocess
    import glob
    import uuid
    import img2pdf
    import traceback
    import logging
    from flask import Flask, render_template, request, send_file, after_this_request
    from pypdf import PdfReader, PdfWriter
    from reportlab.pdfgen import canvas
    from reportlab.lib.pagesizes import A4
    from reportlab.pdfbase import pdfmetrics
    from reportlab.pdfbase.ttfonts import TTFont
    
    # ログ設定
    logging.basicConfig(level=logging.INFO)
    logger = logging.getLogger(__name__)
    
    app = Flask(__name__)
    UPLOAD_FOLDER = '/tmp/pdf_uploads'
    os.makedirs(UPLOAD_FOLDER, exist_ok=True)
    
    FONT_PATH = "/usr/share/fonts/opentype/ipafont-gothic/ipag.ttf"
    
    def create_tiled_watermark(text):
        wm_path = f"/tmp/wm_{uuid.uuid4()}.pdf"
        c = canvas.Canvas(wm_path, pagesize=A4)
        try:
            if os.path.exists(FONT_PATH):
                pdfmetrics.registerFont(TTFont('IPAGothic', FONT_PATH))
                c.setFont('IPAGothic', 35)
            else:
                c.setFont('Helvetica', 35)
        except Exception as e:
            logger.warning(f"Font Load Warning: {e}")
            c.setFont('Helvetica', 35)
    
        c.setFillColorRGB(0.7, 0.7, 0.7)
        c.setStrokeColorRGB(0.7, 0.7, 0.7)
        c.setFillAlpha(0.3)
    
        for x in range(-50, 650, 150):
            for y in range(-50, 900, 120):
                c.saveState()
                c.translate(x, y)
                c.rotate(35)
                c.drawCentredString(0, 0, text)
                c.restoreState()
        c.save()
        return wm_path
    
    @app.route('/')
    def index():
        return render_template('index.html')
    
    @app.route('/convert', methods=['POST'])
    def convert():
        session_id = str(uuid.uuid4())
        input_path = os.path.join(UPLOAD_FOLDER, f"in_{session_id}.pdf")
        temp_path = os.path.join(UPLOAD_FOLDER, f"temp_{session_id}.pdf")
        output_path = os.path.join(UPLOAD_FOLDER, f"out_{session_id}.pdf")
        wm_path = None
        img_list = []
    
        try:
            file = request.files['file']
            quality_mode = request.form.get('quality', 'ebook')
            do_grayscale = request.form.get('grayscale') == 'true'
            do_rasterize = request.form.get('rasterize') == 'true'
    
            file.save(input_path)
    
            # 1. 圧縮・ラスタライズ
            # -dJPEGQ=数値" を追加 (デフォルトは75くらい)
            if do_rasterize:
                # --- 調整ポイント ---
                # dpi = "150" : 読みやすさと軽さのバランスが良い(標準的なPDF品質)
                # dpi = "100" : 少しぼやけるが、ファイルサイズはかなり小さくなる
                dpi = "150" 
                
                img_pattern = os.path.join(UPLOAD_FOLDER, f"pg_{session_id}_%03d.jpg")
                
                subprocess.run([
                    "gs", "-dNOPAUSE", "-dBATCH", "-sDEVICE=jpeg",
                    "-dJPEGQ=75",      # 画質(75くらいあればノイズはほぼ気になりません)
                    f"-r{dpi}",        # ここを消すとデフォルト(72)になるので、明示的に指定します
                    f"-sOutputFile={img_pattern}", 
                    input_path
                ], check=True)
                img_list = sorted(glob.glob(os.path.join(UPLOAD_FOLDER, f"pg_{session_id}_*.jpg")))
                with open(temp_path, "wb") as f:
                    f.write(img2pdf.convert(img_list))
            else:
                gs_cmd = [
                    "gs", "-sDEVICE=pdfwrite", "-dCompatibilityLevel=1.4",
                    "-dNOPAUSE", "-dQUIET", "-dBATCH", "-dJPEGQ=50", f"-sOutputFile={temp_path}"
                ]
                if quality_mode == "super_low":
                    gs_cmd += ["-dPDFSETTINGS=/screen", "-dColorImageResolution=40", "-dGrayImageResolution=40"]
                else:
                    gs_cmd.append(f"-dPDFSETTINGS=/{quality_mode}")
                if do_grayscale:
                    gs_cmd += ["-sColorConversionStrategy=Gray", "-dProcessColorModel=/DeviceGray"]
                gs_cmd.append(input_path)
                subprocess.run(gs_cmd, check=True)
    
            # 2. 透かしの合成
            wm_path = create_tiled_watermark("複写禁止")
            reader = PdfReader(temp_path)
            writer = PdfWriter()
            watermark_page = PdfReader(wm_path).pages[0]
    
            for page in reader.pages:
                page.merge_page(watermark_page)
                writer.add_page(page)
    
            # --- セキュリティ設定の強化 ---
            # permissions_flag の値について:
            # -3904 は「印刷禁止」「コピー禁止」「編集禁止」をすべて盛り込んだ非常に厳しい制限値です。
            # algorithm="AES-256" を指定することで、より強固な暗号化を施します。
            writer.encrypt(
                user_password="",
                owner_password=str(uuid.uuid4()),
                permissions_flag=-3904,
                algorithm="AES-256"
            )
    
            with open(output_path, "wb") as f:
                writer.write(f)
    
            @after_this_request
            def cleanup(response):
                files_to_del = [input_path, temp_path, output_path, wm_path] + img_list
                for p in files_to_del:
                    if p and os.path.exists(p):
                        try: os.remove(p)
                        except: pass
                return response
    
            return send_file(output_path, as_attachment=True, download_name="secure_processed.pdf")
    
        except Exception as e:
            err_msg = traceback.format_exc()
            logger.error(f"Error: {err_msg}")
            return f"SERVER ERROR:\n{err_msg}", 500
    
    if __name__ == '__main__':
        app.run(host='0.0.0.0', port=5000)

    app/requirements.txt

    flask
    pypdf
    reportlab
    img2pdf
    cryptography

    app/Dockerfile

    FROM python:3.11-slim
    
    RUN apt-get update && apt-get install -y \
        ghostscript \
        fonts-ipafont-gothic \
        && rm -rf /var/lib/apt/lists/*
    
    WORKDIR /app
    COPY requirements.txt .
    RUN pip install --no-cache-dir -r requirements.txt
    
    COPY . .
    
    CMD ["python", "main.py"]

    app/templates/index.html

    <!DOCTYPE html>
    <html lang="ja">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>PDF超圧縮 & 荒らしツール</title>
        <script src="https://cdn.tailwindcss.com"></script>
        <style>
            .drag-over {
                border-color: #2563eb !important;
                background-color: #eff6ff !important;
            }
            /* ローディングアニメーションの微調整 */
            @keyframes spin { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }
            .animate-spin { animation: spin 1s linear infinite; }
        </style>
    </head>
    <body class="bg-gray-100 min-h-screen flex items-center justify-center p-4">
    
        <div class="bg-white p-8 rounded-2xl shadow-xl w-full max-w-xl">
            <h1 class="text-2xl font-black mb-2 text-center text-gray-800">PDF 変換プロセッサ</h1>
            <p class="text-center text-gray-500 text-sm mb-8">圧縮・文字の画像化・透かしの一括処理</p>
    
            <form id="uploadForm" class="space-y-5">
                <!-- 1. 圧縮設定 -->
                <div>
                    <label class="block mb-2 font-bold text-gray-700 flex items-center">
                        <span class="bg-blue-600 text-white text-xs px-2 py-1 rounded mr-2">必須</span>
                        圧縮解像度を選択
                    </label>
                    <select id="quality" class="w-full border-2 border-gray-200 p-3 rounded-xl focus:border-blue-500 outline-none transition-all">
                        <option value="super_low">極限圧縮 (50dpi - 画質を最小化)</option>
                        <option value="screen" selected>高圧縮 (72dpi - 標準的な軽量化)</option>
                        <option value="ebook">中圧縮 (150dpi - 画質維持)</option>
                    </select>
                </div>
    
                <!-- 2. 特殊オプション -->
                <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                    <!-- グレースケール -->
                    <div class="bg-blue-50 p-4 rounded-xl border border-blue-100">
                        <div class="flex items-center">
                            <input type="checkbox" id="grayscale" class="w-5 h-5 text-blue-600 rounded">
                            <label for="grayscale" class="ml-2 font-bold text-gray-700">白黒化</label>
                        </div>
                        <p class="mt-1 text-[10px] text-blue-600">カラー情報を削除して軽量化します</p>
                    </div>
    
                    <!-- ラスタライズ -->
                    <div class="bg-amber-50 p-4 rounded-xl border border-amber-100">
                        <div class="flex items-center">
                            <input type="checkbox" id="rasterize" class="w-5 h-5 text-amber-600 rounded">
                            <label for="rasterize" class="ml-2 font-bold text-gray-700">文字を荒くする</label>
                        </div>
                        <p class="mt-1 text-[10px] text-amber-600">文字を画像化し、コピー不可&ガビガビにします</p>
                    </div>
                </div>
    
                <!-- 3. ファイル選択エリア -->
                <div id="dropZone" class="border-4 border-dashed border-gray-200 p-10 text-center rounded-2xl cursor-pointer hover:bg-gray-50 transition-all relative">
                    <div id="dropMessage">
                        <div class="bg-gray-100 w-16 h-16 rounded-full flex items-center justify-center mx-auto mb-4">
                            <svg class="h-8 w-8 text-gray-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12" />
                            </svg>
                        </div>
                        <p class="text-sm font-bold text-gray-600">PDFをドラッグ&ドロップ</p>
                        <p class="text-xs text-gray-400 mt-1">またはここをクリックして選択</p>
                    </div>
                    <input type="file" id="fileInput" class="hidden" accept="application/pdf">
                    <div id="fileInfo" class="hidden">
                        <p class="text-blue-600 font-bold text-lg">✓ ファイル準備完了</p>
                        <p id="fileName" class="text-gray-500 text-sm mt-1 truncate px-4"></p>
                    </div>
                </div>
    
                <!-- 4. 実行ボタン -->
                <button type="submit" id="submitBtn" class="w-full bg-slate-800 text-white py-4 rounded-xl font-bold text-lg hover:bg-black active:scale-95 transition-all shadow-lg disabled:bg-gray-400">
                    変換を開始する
                </button>
            </form>
    
            <!-- 処理中の表示 -->
            <div id="loading" class="hidden mt-6 text-center animate-fade-in">
                <div class="flex justify-center mb-2">
                    <div class="w-8 h-8 border-4 border-blue-600 border-t-transparent rounded-full animate-spin"></div>
                </div>
                <p class="text-sm text-blue-600 font-bold">サーバーで変換処理を行っています...</p>
                <p class="text-[10px] text-gray-400 mt-1">※文字の画像化を選択した場合、時間がかかることがあります</p>
            </div>
        </div>
    
        <script>
            const dropZone = document.getElementById('dropZone');
            const fileInput = document.getElementById('fileInput');
            const fileInfo = document.getElementById('fileInfo');
            const fileName = document.getElementById('fileName');
            const dropMessage = document.getElementById('dropMessage');
            const form = document.getElementById('uploadForm');
            const btn = document.getElementById('submitBtn');
            const loading = document.getElementById('loading');
    
            // ファイル選択ダイアログ起動
            dropZone.onclick = () => fileInput.click();
    
            // ドラッグ&ドロップ制御
            ['dragenter', 'dragover'].forEach(n => {
                dropZone.addEventListener(n, (e) => { e.preventDefault(); dropZone.classList.add('drag-over'); });
            });
            ['dragleave', 'drop'].forEach(n => {
                dropZone.addEventListener(n, (e) => { e.preventDefault(); dropZone.classList.remove('drag-over'); });
            });
    
            dropZone.ondrop = (e) => {
                const files = e.dataTransfer.files;
                if(files.length > 0 && files[0].type === "application/pdf") {
                    fileInput.files = files;
                    showFile(files[0].name);
                } else {
                    alert("PDFファイルのみ対応しています。");
                }
            };
    
            fileInput.onchange = () => {
                if(fileInput.files[0]) showFile(fileInput.files[0].name);
            };
    
            function showFile(name) {
                fileName.innerText = name;
                fileInfo.classList.remove('hidden');
                dropMessage.classList.add('hidden');
            }
    
            // 送信処理
            form.onsubmit = async (e) => {
                e.preventDefault();
                if(!fileInput.files[0]) return alert("PDFを選択してください");
    
                btn.disabled = true;
                loading.classList.remove('hidden');
    
                const formData = new FormData();
                formData.append('file', fileInput.files[0]);
                formData.append('quality', document.getElementById('quality').value);
                formData.append('grayscale', document.getElementById('grayscale').checked);
                formData.append('rasterize', document.getElementById('rasterize').checked);
    
                try {
                    const response = await fetch('/convert', { method: 'POST', body: formData });
                    if (!response.ok) throw new Error('サーバーエラーが発生しました');
    
                    const blob = await response.blob();
                    const url = window.URL.createObjectURL(blob);
                    const a = document.createElement('a');
                    a.href = url;
                    a.download = "processed_" + fileInput.files[0].name;
                    document.body.appendChild(a);
                    a.click();
                    a.remove();
                    window.URL.revokeObjectURL(url);
                } catch (err) {
                    alert(err.message);
                } finally {
                    btn.disabled = false;
                    loading.classList.add('hidden');
                }
            };
        </script>
    </body>
    </html>

    nginx/conf.d/default.conf

    server_ipは適宜変更

    server {
        listen 443 ssl;
        server_name server_ip;
    
        ssl_certificate /etc/nginx/ssl/server.crt;
        ssl_certificate_key /etc/nginx/ssl/server.key;
    
        location / {
            proxy_pass http://app:5000;
            proxy_set_header Host $host;
            proxy_set_header X-Real-IP $remote_addr;
            client_max_body_size 50M; # 大きなPDFを許可
        }
    }

    docker-compose.yml

    services:
      app:
        build: ./app
        container_name: pdf-app
        restart: always
        environment:
          - PYTHONUNBUFFERED=1  # これを追加
        # ↓ここを追加
        volumes:
          - ./app:/app
        # ↑ここまで
      nginx:
        image: nginx:latest
        container_name: pdf-nginx
        ports:
          - "443:443"
        volumes:
          - ./nginx/conf.d:/etc/nginx/conf.d
          - ./nginx/ssl:/etc/nginx/ssl
        depends_on:
          - app
        restart: always

    できた画面

    圧縮解像度は

    • 極限圧縮 (50dpi - 画質を最小化)

    • 高圧縮 (72dpi - 標準的な軽量化)

    • 中圧縮 (150dpi - 画質維持)

    画像

    結果

    • 元PDF

    画像
    • 圧縮したPDF

    画像
    あんまり変わらないな
    • 文字を荒くして圧縮したPDF

    結構荒くなった

    画像

    印刷ボタンは押せない状態になった

    画像

    他の修正ポイントを聞いた

    試してないけど修正する場合のコードを教えてもらった

    app/main.py の中の create_tiled_watermark という関数を書き換えることで、見た目を自由に変更できます。

    文字色の変更 (c.setFillColorRGB)

    RGB(赤・緑・青)を 0.0 〜 1.0 の範囲で指定します。もっと濃いグレー: c.setFillColorRGB(0.4, 0.4, 0.4)
    赤色にする: c.setFillColorRGB(1.0, 0.0, 0.0)
    薄い青色にする: c.setFillColorRGB(0.8, 0.8, 1.0)


    文字サイズの変更 (c.setFont)

    2番目の引数がフォントサイズ(単位はポイント)です。大きくする: c.setFont('IPAGothic', 60)
    小さくする: c.setFont('IPAGothic', 20)


    実装例:

    もし「赤色で、もっと大きく、さらに薄く」したい場合は、以下のように書き換えます。


    Tips: 微調整のコツ目立ちすぎる場合: c.setFillAlpha(0.1) 程度まで下げると、背景に溶け込みつつ、コピーした時にはうっすら映る絶妙な濃さになります。
    もっと邪魔にしたい場合: range の第3引数(150 や 120)を小さくすると、画面が「複写禁止」の文字で埋め尽くされます。
    文字内容の変更: writer.encrypt の前の create_tiled_watermark("複写禁止") の文字を変えれば、社名や日付を入れることも可能です。

    def create_tiled_watermark(text):
        wm_path = f"/tmp/wm_{uuid.uuid4()}.pdf"
        c = canvas.Canvas(wm_path, pagesize=A4)
        
        # フォントとサイズ(35 → 60に変更)
        try:
            pdfmetrics.registerFont(TTFont('IPAGothic', FONT_PATH))
            c.setFont('IPAGothic', 60)
        except:
            c.setFont('Helvetica', 60)
    
        # 色を赤(1, 0, 0)にして、透明度をさらに薄く(0.3 → 0.15)
        c.setFillColorRGB(1.0, 0.0, 0.0)
        c.setStrokeColorRGB(1.0, 0.0, 0.0)
        c.setFillAlpha(0.15) 
    
        # 格子の間隔(150, 120を大きくするとまばらに、小さくすると密集します)
        for x in range(-50, 650, 150):
            for y in range(-50, 900, 120):
                c.saveState()
                c.translate(x, y)
                c.rotate(35) # 角度(35度)
                c.drawCentredString(0, 0, text)
                c.restoreState()
        c.save()
        return wm_path

    文字のあらさの変更点(AIから)

    画像

    感想

    思ったよりすんなり動いてくれた。果たして要望に沿っているかは来週聞いてみよう・・・こういうあまり予想していないような要望は他にも眠っているのだろうか??

     
     

    のり

     
     
    北海道江別市の職員です。 LGWAN内で業務を効率化できるようにサーバーの構築等を自分メモ的ではありますが残していきたいと思います。 よろしくお願いいたします。 更新していきたいもの Pleasanter NextCloud RPA(SikuliX) その他OSSが興味あります。

    あなたへのおすすめ