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

Ghostscript でPDFを圧縮する(後日)

    前回の記事

    その後追加で要望が出たので追加でAI-Studioに教えてもらい、対応した

    • 矩形選択した範囲だけ荒くしたい

    • PDF編集機能の制限をもう少し細かく

    • パスワード制限つけてほしい

    • クローズド環境でUIが残念な感じになったので対応

    最終的なもの

    ディレクトリ構成

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

    staticディレクトリ直下

    # Tailwind CSS (v2.2.19) のダウンロード
    # ※v3以降はビルドが必要なため、オフライン配布に適した単一ファイルのv2を使用します。
    wget https://cdnjs.cloudflare.com/ajax/libs/tailwindcss/2.2.19/tailwind.min.css
    
    # PDF.js (v3.11.174) 本体とワーカーのダウンロード
    wget https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.min.js
    wget https://cdnjs.cloudflare.com/ajax/libs/pdf.js/3.11.174/pdf.worker.min.js

    app/main.py

    import os, subprocess, glob, uuid, img2pdf, traceback, 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 PIL import Image
    
    app = Flask(__name__)
    UPLOAD_FOLDER = '/tmp/pdf_uploads'
    os.makedirs(UPLOAD_FOLDER, exist_ok=True)
    
    @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")
    
        try:
            file = request.files['file']
            dpi = request.form.get('dpi', '72')
            quality = request.form.get('quality', '30')
            overall = request.form.get('overall') == 'true'
            page_idx = int(request.form.get('page_idx', 0))
            user_pass = request.form.get('user_password', '')
            owner_pass = request.form.get('owner_password', '')
            perm_level = request.form.get('perm_level', '0')
    
            # 比率 (0.0 ~ 1.0)
            rx, ry, rw, rh = float(request.form.get('x', 0)), float(request.form.get('y', 0)), float(request.form.get('w', 0)), float(request.form.get('h', 0))
    
            file.save(input_path)
            reader = PdfReader(input_path)
    
            # 権限フラグ設定
            p_flag = -3904
            if perm_level == "1": p_flag = -3904 + 4 + 8 + 32 + 256 + 1024 + 2048
            elif perm_level == "2": p_flag = -3904 + 256
            elif perm_level == "3": p_flag = -3904 + 32 + 256
            elif perm_level == "4": p_flag = -3904 + 1024
    
            if overall:
                img_pattern = os.path.join(UPLOAD_FOLDER, f"pg_{session_id}_%03d.jpg")
                subprocess.run(["gs", "-dNOPAUSE", "-dBATCH", "-sDEVICE=jpeg", f"-dJPEGQ={quality}", f"-r{dpi}", 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))
                for f in img_list: os.remove(f)
                reader = PdfReader(temp_path)
    
            writer = PdfWriter()
            for i, page in enumerate(reader.pages):
                mb = page.mediabox
                p_w, p_h = float(mb.width), float(mb.height)
                off_x, off_y = float(mb.left), float(mb.bottom)
    
                if not overall and i == page_idx and rw > 0 and rh > 0:
                    page_img = os.path.join(UPLOAD_FOLDER, f"p_{session_id}_{i}.jpg")
                    subprocess.run(["gs", "-dNOPAUSE", "-dBATCH", "-sDEVICE=jpeg", f"-dJPEGQ={quality}", f"-r{dpi}", f"-dFirstPage={i+1}", f"-dLastPage={i+1}", f"-sOutputFile={page_img}", input_path], check=True)
    
                    with Image.open(page_img) as img:
                        left, top = rx * img.width, ry * img.height
                        right, bottom = (rx + rw) * img.width, (ry + rh) * img.height
                        crop_path = os.path.join(UPLOAD_FOLDER, f"c_{session_id}_{i}.jpg")
                        img.crop((left, top, right, bottom)).save(crop_path, quality=int(quality))
    
                        rect_pdf = os.path.join(UPLOAD_FOLDER, f"re_{session_id}_{i}.pdf")
                        c = canvas.Canvas(rect_pdf, pagesize=(p_w, p_h))
                        # PDF座標変換(下から上)
                        draw_x = off_x + (rx * p_w)
                        draw_y = off_y + (p_h - (ry + rh) * p_h)
                        c.setFillColorRGB(1, 1, 1)
                        c.rect(draw_x, draw_y, rw * p_w, rh * p_h, fill=1, stroke=0)
                        c.drawImage(crop_path, draw_x, draw_y, width=rw * p_w, height=rh * p_h)
                        c.save()
                        page.merge_page(PdfReader(rect_pdf).pages[0])
                        os.remove(page_img); os.remove(crop_path); os.remove(rect_pdf)
                writer.add_page(page)
    
            writer.encrypt(user_password=user_pass, owner_password=owner_pass, permissions_flag=p_flag, algorithm="AES-256")
            with open(output_path, "wb") as f: writer.write(f)
    
            @after_this_request
            def cleanup(response):
                for p in [input_path, temp_path, output_path]:
                    if p and os.path.exists(p): os.remove(p)
                return response
            return send_file(output_path, as_attachment=True, download_name="secure_processed.pdf")
        except Exception: return traceback.format_exc(), 500
    
    if __name__ == '__main__':
        app.run(host='0.0.0.0', port=5000)

    app/requirements.txt

    flask
    pypdf
    reportlab
    img2pdf
    cryptography
    Pillow

    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">
        <title>PDFセキュリティ & 文字荒らしツール</title>
        <link rel="stylesheet" href="/static/tailwind.min.css">
        <script src="/static/pdf.min.js"></script>
        <style>
            #previewContainer { position: relative; display: inline-block; user-select: none; }
            #selectionBox { position: absolute; border: 2px dashed red; background: rgba(255,0,0,0.3); display: none; pointer-events: none; z-index: 50; }
            #pdfCanvas { border: 1px solid #444; cursor: crosshair; background: white; max-width: 100%; height: auto !important; }
            .scroll-area { max-height: 85vh; overflow: auto; scrollbar-width: thin; }
            .explanation { font-size: 0.7rem; color: #9ca3af; line-height: 1.1; }
        </style>
    </head>
    <body class="bg-gray-900 text-gray-200 p-2">
        <div class="max-w-full mx-auto bg-gray-800 rounded-xl shadow-2xl overflow-hidden flex flex-col md:flex-row border border-gray-700">
    
            <!-- 左サイド:設定パネル -->
            <div class="w-full md:w-72 p-4 space-y-3 border-r border-gray-700 bg-gray-850 flex-shrink-0">
    
                <div class="bg-gray-900 p-3 rounded-lg space-y-3">
                    <div>
                        <label class="block text-[10px] text-blue-400 font-bold uppercase">文字のガビガビ度 (DPI)</label>
                        <input type="number" id="dpi" value="72" class="w-full bg-gray-800 p-1 rounded text-sm border border-gray-600">
                        <p class="explanation mt-1">数値が小さいほど文字がドット状に荒れ、コピーや再利用を強力に防げます。</p>
                    </div>
                    <div>
                        <label class="block text-[10px] text-green-400 font-bold uppercase">ファイル軽量化 (品質)</label>
                        <input type="number" id="quality" value="30" class="w-full bg-gray-800 p-1 rounded text-sm border border-gray-600">
                        <p class="explanation mt-1">数値を下げると文字の周りがザラつきますが、ファイルが非常に軽くなります。</p>
                    </div>
                </div>
    
                <div class="bg-gray-900 p-3 rounded-lg space-y-2">
                    <label class="block text-[10px] text-red-400 font-bold uppercase">パスワード & 権限</label>
                    <input type="text" id="userPass" placeholder="閲覧パスワード" class="w-full bg-gray-800 p-1.5 rounded text-xs border border-gray-600">
                    <div class="flex items-center">
                        <input type="checkbox" id="syncPass" checked class="w-3 h-3"><label class="ml-2 text-[9px]">閲覧と編集を同じパスワードにする</label>
                    </div>
                    <input type="text" id="ownerPass" placeholder="編集・制限解除用パスワード" class="w-full bg-gray-800 p-1.5 rounded text-xs border border-gray-600 hidden text-yellow-400">
    
                    <label class="block text-[10px] text-gray-500 mt-2 italic">許可する操作</label>
                    <select id="permLevel" class="w-full bg-gray-800 p-1 rounded text-[10px] border border-gray-600 outline-none">
                        <option value="0">すべて禁止 (印刷・コピー不可)</option>
                        <option value="1">ページ抽出以外すべて許可</option>
                        <option value="2">フォーム入力・署名のみ許可</option>
                        <option value="3">注釈・フォーム・署名を許可</option>
                        <option value="4">ページの挿入・削除・回転のみ許可</option>
                    </select>
                </div>
    
                <div class="flex items-center p-2 bg-gray-700 rounded-lg">
                    <input type="checkbox" id="overall" class="w-4 h-4"><label class="ml-2 text-xs font-bold uppercase tracking-tighter">ファイル全体を荒くする</label>
                </div>
    
                <button id="convertBtn" class="w-full bg-green-600 hover:bg-green-700 p-4 rounded-lg font-black shadow-xl active:scale-95 disabled:bg-gray-600" disabled>変換して保存</button>
            </div>
    
            <!-- 右メイン:表示エリア -->
            <div id="dropZone" class="flex-1 p-2 bg-gray-950 flex flex-col items-center justify-center relative min-h-[400px]">
                <div id="dropMessage" class="absolute inset-0 flex flex-col items-center justify-center pointer-events-none text-gray-600 font-bold border-4 border-dashed border-gray-800 m-4 rounded-xl">
                    PDFをドロップ、またはクリックで選択
                </div>
    
                <div id="toolbar" class="hidden w-full flex flex-wrap justify-center items-center gap-4 mb-2 bg-gray-800 p-1.5 rounded-lg z-20 border border-gray-700">
                    <div class="flex items-center space-x-2">
                        <button id="prevPage" class="hover:text-blue-400 font-bold px-2">前へ</button>
                        <span id="pageInfo" class="text-xs font-mono bg-gray-900 px-2 py-1 rounded">PG 1/1</span>
                        <button id="nextPage" class="hover:text-blue-400 font-bold px-2">次へ</button>
                    </div>
                    <div class="h-4 w-px bg-gray-600"></div>
                    <div class="flex items-center space-x-2">
                        <button id="zoomOut" class="px-2 hover:text-blue-400 font-bold">-</button>
                        <span id="zoomPercent" class="text-[10px] w-8 text-center">100%</span>
                        <button id="zoomIn" class="px-2 hover:text-blue-400 font-bold">+</button>
                        <button id="zoomFit" class="text-[9px] bg-blue-900 px-3 py-1 rounded font-bold ml-2">FIT</button>
                    </div>
                </div>
    
                <div id="canvasWrapper" class="w-full scroll-area flex justify-center p-1">
                    <div id="previewContainer">
                        <canvas id="pdfCanvas"></canvas>
                        <div id="selectionBox"></div>
                    </div>
                </div>
                <input type="file" id="fileInput" accept="application/pdf" class="hidden">
            </div>
        </div>
    
        <script>
            const { pdfjsLib } = globalThis;
            pdfjsLib.GlobalWorkerOptions.workerSrc = window.location.origin + '/static/pdf.worker.min.js';
            let pdfDoc = null, pageNum = 1, currentScale = 1.0, pdfFile = null, isDrawing = false;
            let startX, startY, rect = { x: 0, y: 0, w: 0, h: 0, page: 1 };
    
            const canvas = document.getElementById('pdfCanvas'), ctx = canvas.getContext('2d'), dropZone = document.getElementById('dropZone');
            const selectionBox = document.getElementById('selectionBox'), fileInput = document.getElementById('fileInput'), canvasWrapper = document.getElementById('canvasWrapper');
    
            document.getElementById('syncPass').onchange = (e) => {
                document.getElementById('ownerPass').classList.toggle('hidden', e.target.checked);
            };
    
            // ファイル選択
            dropZone.onclick = (e) => {
                if (e.target === dropZone || e.target === document.getElementById('dropMessage')) fileInput.click();
            };
            dropZone.ondragover = (e) => { e.preventDefault(); dropZone.classList.add('bg-gray-900'); };
            dropZone.ondragleave = () => dropZone.classList.remove('bg-gray-900');
            dropZone.ondrop = (e) => {
                e.preventDefault();
                dropZone.classList.remove('bg-gray-900');
                if (e.dataTransfer.files[0]) loadPdf(e.dataTransfer.files[0]);
            };
            fileInput.onchange = (e) => { if (e.target.files[0]) loadPdf(e.target.files[0]); };
    
            async function loadPdf(file) {
                if (file.type !== "application/pdf") return;
                pdfFile = file;
                const reader = new FileReader();
                reader.onload = async function() {
                    const loadingTask = pdfjsLib.getDocument({data: new Uint8Array(this.result)});
                    pdfDoc = await loadingTask.promise;
                    pageNum = 1;
                    document.getElementById('dropMessage').classList.add('hidden');
                    document.getElementById('toolbar').classList.remove('hidden');
                    document.getElementById('convertBtn').disabled = false;
                    autoFit(); // 読み込み直後にフィットさせる
                };
                reader.readAsArrayBuffer(file);
            }
    
            async function renderPage() {
                if (!pdfDoc) return;
                const page = await pdfDoc.getPage(pageNum);
                const viewport = page.getViewport({scale: currentScale});
                canvas.width = viewport.width; canvas.height = viewport.height;
                await page.render({canvasContext: ctx, viewport: viewport}).promise;
                document.getElementById('pageInfo').innerText = `PG ${pageNum}/${pdfDoc.numPages}`;
                document.getElementById('zoomPercent').innerText = `${Math.round(currentScale * 100)}%`;
                if (rect.page !== pageNum) selectionBox.style.display = 'none';
            }
    
            function autoFit() {
                if (!pdfDoc) return;
                pdfDoc.getPage(pageNum).then(page => {
                    const vp = page.getViewport({scale: 1.0});
                    currentScale = (canvasWrapper.clientWidth - 40) / vp.width;
                    if (currentScale > 2.0) currentScale = 2.0;
                    renderPage();
                });
            }
    
            document.getElementById('zoomFit').onclick = (e) => { e.stopPropagation(); autoFit(); };
            document.getElementById('zoomIn').onclick = (e) => { e.stopPropagation(); currentScale += 0.1; renderPage(); };
            document.getElementById('zoomOut').onclick = (e) => { e.stopPropagation(); if(currentScale > 0.2) currentScale -= 0.1; renderPage(); };
            document.getElementById('prevPage').onclick = (e) => { e.stopPropagation(); if (pageNum > 1) { pageNum--; renderPage(); } };
            document.getElementById('nextPage').onclick = (e) => { e.stopPropagation(); if (pageNum < pdfDoc.numPages) { pageNum++; renderPage(); } };
    
            canvas.onmousedown = (e) => {
                e.stopPropagation();
                isDrawing = true;
                const cRect = canvas.getBoundingClientRect();
                startX = e.clientX - cRect.left;
                startY = e.clientY - cRect.top;
                rect.page = pageNum;
                selectionBox.style.display = 'block';
                selectionBox.style.width = '0px'; selectionBox.style.height = '0px';
            };
    
            window.onmousemove = (e) => {
                if (!isDrawing) return;
                const cRect = canvas.getBoundingClientRect();
                const curX = e.clientX - cRect.left, curY = e.clientY - cRect.top;
                rect.w = Math.abs(curX - startX); rect.h = Math.abs(curY - startY);
                rect.x = Math.min(curX, startX); rect.y = Math.min(curY, startY);
                selectionBox.style.left = rect.x + 'px'; selectionBox.style.top = rect.y + 'px';
                selectionBox.style.width = rect.w + 'px'; selectionBox.style.height = rect.h + 'px';
            };
            window.onmouseup = () => { isDrawing = false; };
    
            document.getElementById('convertBtn').onclick = async (e) => {
                e.stopPropagation();
                const btn = document.getElementById('convertBtn');
                btn.disabled = true; btn.innerText = "処理中...";
                const formData = new FormData();
                formData.append('file', pdfFile);
                formData.append('dpi', document.getElementById('dpi').value);
                formData.append('quality', document.getElementById('quality').value);
                formData.append('overall', document.getElementById('overall').checked);
                formData.append('user_password', document.getElementById('userPass').value);
                const sync = document.getElementById('syncPass').checked;
                formData.append('owner_password', sync ? document.getElementById('userPass').value : document.getElementById('ownerPass').value);
                formData.append('perm_level', document.getElementById('permLevel').value);
                formData.append('page_idx', rect.page - 1);
                formData.append('x', rect.x / canvas.width); formData.append('y', rect.y / canvas.height);
                formData.append('w', rect.w / canvas.width); formData.append('h', rect.h / canvas.height);
    
                try {
                    const res = await fetch('/convert', { method: 'POST', body: formData });
                    const blob = await res.blob();
                    const a = document.createElement('a'); a.href = URL.createObjectURL(blob);
                    a.download = "processed_" + pdfFile.name; a.click();
                } catch (err) { alert("エラーが発生しました"); }
                finally { btn.disabled = false; btn.innerText = "変換して保存"; }
            };
        </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

    できた画面(index.html)

    画像
    赤枠は矩形選択した箇所

    変換後のPDF

    AIが教えてくれたこのツールの仕組みは以下

    1. 抽出(Ghostscript): 指定されたページ全体を、あえて低いDPI(解像度)で1枚のJPEG画像として書き出します。この時点で文字は「綺麗なデータ」から「荒い点(ドット)」に変わります。

    2. 切り抜き(Pillow): ブラウザから送られた座標を元に、その「荒い画像」の指定範囲だけをハサミで切るように切り抜きます。

    3. 消去と上書き(ReportLab):

      1. まず、元のPDFの指定箇所に「真っ白な塗りつぶしの四角形」を置きます。これで元の綺麗な文字を物理的に見えなく(消去)します。

      2. その白い四角形の上に、先ほど切り抜いた「荒い画像」をピッタリ重ねます。

    4. 合成(pypdf): この「白塗り+荒い画像」を1枚の透明なシート(パッチ)として、元のPDFページの上に重ね合わせ(マージ)ます。

    画像

    感想

    これが良い例かわからないが、ニッチな現場のお困りごとを対応できる内製部署つくってくれないかな・・・といつも思ってます。
    が、継続性も含めて今の状況では難しいかな・・・ただ、あきらめないで訴えていきたいとは考えています。

     
     

    のり

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

    あなたへのおすすめ