"""PDF 壓縮:Ghostscript pdfwrite 的圖片降採樣、嚴格字型子集化與目標檔案大小自動降級。 設計原則(與 app.py 的 CMYK 轉換刻意分開,兩者互不影響) - 只做壓縮、不做色彩轉換:使用 LeaveColorUnchanged,避免 CMYK 檔被改色。 - 不使用 -dPDFSETTINGS:/prepress 會覆寫 CompatibilityLevel(app.py 已註記此坑), 因此所有參數一律明寫。 - 目標大小以「原檔百分比」表示;未達標時先降 DPI、最後才降 JPEG 品質, 仍無法達成時保留最小可讀版本並在報告中說明。 - 掃描/影像型 PDF 的不隱藏文字層由 Ghostscript 原樣保留(本工具不做 OCR、 也不會移除既有文字)。 """ import json import os import shutil import subprocess from pathlib import Path # 輸出逾時;與 app.py 的 PDF_TIMEOUT_SECONDS 保持一致 COMPRESS_TIMEOUT_SECONDS = 300 INSPECTION_TIMEOUT_SECONDS = 90 # 降級階梯:DPI 由大而小,JPEG 品質在最後一階才降 DPI_STEPS = (300, 200, 150, 120, 96, 72) FLOOR_DPI = 96 FLOOR_JPEG = 65 DEFAULT_START_DPI = 150 DEFAULT_START_JPEG = 85 # 目標大小選項(原檔百分比) TARGET_RATIO_CHOICES = ("不指定", "10%", "20%", "30%", "50%", "自訂") COMPATIBILITY_CHOICES = ("1.7(建議)", "1.4(最大相容)") # ============================================================ # 外部工具 # ============================================================ def find_ghostscript(): """找可用的 Ghostscript 執行檔,找不到回傳 None。""" for candidate in ("gs", "gsc"): path = shutil.which(candidate) if path: return path return None def _tool(name): return shutil.which(name) def ghostscript_version(gs_path): try: result = subprocess.run( [gs_path, "--version"], capture_output=True, text=True, timeout=10, check=True, ) return result.stdout.strip() except Exception: return None # ============================================================ # 文件類型判斷(決定預設策略與提示) # ============================================================ KIND_LABELS = { "text": "向量/文字型", "image": "影像型(掃描,無文字層)", "image_text": "影像為主(每頁含圖,且有文字層)", "mixed": "混合型(部分文字、部分影像)", "unknown": "無法判斷", } def _count_pdf_fonts(pdf_path): fonts_path = _tool("pdffonts") if fonts_path is None: return None try: result = subprocess.run( [fonts_path, str(pdf_path)], capture_output=True, text=True, timeout=INSPECTION_TIMEOUT_SECONDS, check=True, ) except Exception: return None count = 0 for line in result.stdout.splitlines(): stripped = line.strip() if not stripped or stripped.startswith("name") or set(stripped) <= {"-", " "}: continue if len(stripped.split()) >= 6: count += 1 return count def _image_stats(pdf_path): """回傳 (圖片張數, 出現圖片的頁數集合);工具缺失時回傳 (None, set())。""" images_path = _tool("pdfimages") if images_path is None: return None, set() try: result = subprocess.run( [images_path, "-list", str(pdf_path)], capture_output=True, text=True, timeout=INSPECTION_TIMEOUT_SECONDS, check=True, ) except Exception: return None, set() count = 0 pages = set() for line in result.stdout.splitlines(): columns = line.split() if len(columns) < 14 or not columns[0].isdigit(): continue count += 1 pages.add(int(columns[0])) return count, pages def _pdf_page_count(pdf_path): info_path = _tool("pdfinfo") if info_path is None: return None try: result = subprocess.run( [info_path, str(pdf_path)], capture_output=True, text=True, timeout=INSPECTION_TIMEOUT_SECONDS, check=True, ) except Exception: return None for line in result.stdout.splitlines(): if line.startswith("Pages:"): try: return int(line.split(":", 1)[1].strip()) except ValueError: return None return None def classify_pdf(pdf_path): """判斷 PDF 類型;用來決定預設壓縮策略與介面提示。""" fonts = _count_pdf_fonts(pdf_path) images, image_pages = _image_stats(pdf_path) pages = _pdf_page_count(pdf_path) if fonts is None and images is None: kind = "unknown" elif not fonts and images: kind = "image" elif fonts and images: kind = "image_text" if (pages and len(image_pages) >= pages) else "mixed" elif fonts: kind = "text" else: kind = "unknown" if kind == "image": advice = "偵測不到字型:這是純影像掃描檔,壓縮後仍然無法搜尋文字。若要可搜尋,請先做 OCR。" elif kind == "image_text": advice = "每頁都有影像且偵測到字型:掃描檔或滿版圖片型(型錄、簡報)。可用較強的壓縮,既有文字層會保留。" elif kind == "text": advice = "以文字與向量圖形為主:頁面不會被點陣化,壓縮來自字型子集化與內嵌影像降採樣。" elif kind == "mixed": advice = "文字與影像混合:影像會被降採樣,文字保持向量與可搜尋。" else: advice = "缺少 pdffonts/pdfimages 或檔案無法解析,無法判斷類型。" return { "kind": kind, "label": KIND_LABELS[kind], "advice": advice, "font_count": fonts, "image_count": images, "pages": pages, } # ============================================================ # Ghostscript 指令 # ============================================================ def mono_resolution(dpi): """單色圖片的解析度:維持彩色解析度的 4 倍,並限制在 300–1200 ppi。""" return max(300, min(1200, int(dpi) * 4)) def build_compress_command( gs_path, input_path, output_path, dpi, jpeg_quality, compatibility="1.7", permit_dirs=(), ): """組出 pdfwrite 壓縮指令;所有會影響輸出的參數都明寫,不依賴 -dPDFSETTINGS。""" input_path = Path(input_path).resolve() output_path = Path(output_path).resolve() mono_dpi = mono_resolution(dpi) command = [ gs_path, "-dSAFER", "-dBATCH", "-dNOPAUSE", "-dQUIET", "-sDEVICE=pdfwrite", f"-dCompatibilityLevel={compatibility}", # 字型:一律嵌入並子集化,且允許 100% 子集(strict subsetting) "-dEmbedAllFonts=true", "-dSubsetFonts=true", "-dMaxSubsetPct=100", "-dCompressFonts=true", "-dCompressPages=true", "-dDetectDuplicateImages=true", # 壓縮不應該改動頁面方向,否則掃描檔的文字層會與影像錯位 "-dAutoRotatePages=/None", # 只壓縮、不轉色(CMYK 維持 CMYK、RGB 維持 RGB) "-sColorConversionStrategy=LeaveColorUnchanged", # 彩色/灰階圖片降採樣 "-dDownsampleColorImages=true", f"-dColorImageResolution={int(dpi)}", "-dColorImageDownsampleType=/Bicubic", "-dColorImageDownsampleThreshold=1.5", "-dDownsampleGrayImages=true", f"-dGrayImageResolution={int(dpi)}", "-dGrayImageDownsampleType=/Bicubic", "-dGrayImageDownsampleThreshold=1.5", # 單色(線稿)圖片 "-dDownsampleMonoImages=true", f"-dMonoImageResolution={mono_dpi}", "-dMonoImageDownsampleType=/Subsample", "-dMonoImageDownsampleThreshold=1.5", # 重新編碼:彩色/灰階走 JPEG(可調品質),單色走 CCITT G4 "-dAutoFilterColorImages=false", "-dColorImageFilter=/DCTEncode", f"-dJPEGQ={int(jpeg_quality)}", "-dAutoFilterGrayImages=false", "-dGrayImageFilter=/DCTEncode", "-dAutoFilterMonoImages=false", "-dMonoImageFilter=/CCITTFaxEncode", ] for directory in permit_dirs: if not directory: continue prefix = str(Path(directory).resolve()) + os.sep command.extend([f"--permit-file-read={prefix}", f"--permit-file-write={prefix}"]) command.extend([f"-sOutputFile={output_path}", str(input_path)]) return command def compression_ladder(start_dpi=DEFAULT_START_DPI, start_jpeg=DEFAULT_START_JPEG, max_steps=5): """降級候選:先降 DPI(對掃描檔效果最大),最後一階才降 JPEG 品質。""" dpi_chain = [dpi for dpi in DPI_STEPS if FLOOR_DPI <= dpi <= int(start_dpi)] if not dpi_chain: dpi_chain = [FLOOR_DPI] ladder = [(dpi, int(start_jpeg)) for dpi in dpi_chain] if int(start_jpeg) > FLOOR_JPEG: ladder.append((FLOOR_DPI, FLOOR_JPEG)) return ladder[:max_steps] # ============================================================ # 壓縮主流程 # ============================================================ def compress_pdf( pdf_path, work_dir, target_ratio=None, start_dpi=DEFAULT_START_DPI, start_jpeg=DEFAULT_START_JPEG, compatibility="1.7", gs_path=None, timeout=COMPRESS_TIMEOUT_SECONDS, ): """壓縮 PDF。 target_ratio: 目標大小(原檔比例,例如 0.1 表示 10%);None 表示只跑一輪不追目標。 回傳 dict;失敗時 ok=False 並帶 message。 """ gs_path = gs_path or find_ghostscript() if gs_path is None: return {"ok": False, "message": "❌ 系統未安裝 Ghostscript;請在 packages.txt 加入 ghostscript。"} input_path = Path(pdf_path).resolve() if not input_path.exists(): return {"ok": False, "message": f"❌ 找不到輸入檔:{input_path}"} work_dir = Path(work_dir).resolve() work_dir.mkdir(parents=True, exist_ok=True) input_bytes = input_path.stat().st_size if input_bytes <= 0: return {"ok": False, "message": "❌ 輸入檔為空。"} target_bytes = int(input_bytes * float(target_ratio)) if target_ratio else None permission_dirs = {str(input_path.parent), str(work_dir)} attempts = [] best = None errors = [] for dpi, jpeg_quality in compression_ladder(start_dpi, start_jpeg): mono_dpi = mono_resolution(dpi) output_path = work_dir / f"{input_path.stem}_compressed_{dpi}dpi_q{jpeg_quality}.pdf" command = build_compress_command( gs_path, input_path, output_path, dpi, jpeg_quality, compatibility=compatibility, permit_dirs=permission_dirs, ) try: subprocess.run( command, check=True, capture_output=True, text=True, timeout=timeout, ) except subprocess.TimeoutExpired: errors.append(f"{dpi} dpi / Q{jpeg_quality}:逾時({timeout} 秒)") continue except subprocess.CalledProcessError as error: detail = (error.stderr or error.stdout or "").strip().splitlines() errors.append(f"{dpi} dpi / Q{jpeg_quality}:{detail[-1] if detail else 'Ghostscript 執行失敗'}") continue if not output_path.exists() or output_path.stat().st_size == 0: errors.append(f"{dpi} dpi / Q{jpeg_quality}:未產生有效輸出") continue output_bytes = output_path.stat().st_size attempt = { "dpi": dpi, "jpeg_quality": jpeg_quality, "mono_dpi": mono_dpi, "output": str(output_path), "output_bytes": output_bytes, "ratio": output_bytes / input_bytes, } attempts.append(attempt) if best is None or output_bytes < best["output_bytes"]: best = attempt # 沒指定目標:只跑第一階,不浪費時間反覆壓 if target_bytes is None: break if output_bytes <= target_bytes: break if best is None: return { "ok": False, "message": "❌ 壓縮失敗:Ghostscript 沒有產生有效輸出。\n" + "\n".join(errors[-3:]), "attempts": attempts, "errors": errors, } # pdfwrite 會重寫整個檔案結構;純向量或本來就很小的 PDF 可能反而變大(實測 5 KB → 16 KB), # 這種情況不應該把更大的檔案當成「壓縮結果」交出去。 if best["output_bytes"] >= input_bytes: for attempt in attempts: try: Path(attempt["output"]).unlink() except OSError: pass return { "ok": False, "message": ( f"❌ 壓縮後反而變大({human_bytes(input_bytes)} → {human_bytes(best['output_bytes'])})。\n" "這個檔案可能已經是純向量/文字、或本來就很小,重新編碼沒有收益。\n" "建議:改用「列印成 PDF」以外的原生壓縮工具,或直接使用原檔。" ), "attempts": attempts, "errors": errors, } # 清掉沒有採用的中間輸出,暫存目錄才不會越積越大 for attempt in attempts: if attempt["output"] != best["output"]: try: Path(attempt["output"]).unlink() except OSError: pass met_target = bool(target_bytes and best["output_bytes"] <= target_bytes) if target_bytes and not met_target: note = ( f"⚠️ 已降到最低可讀設定({best['dpi']} dpi / JPEG {best['jpeg_quality']})仍未達 " f"{target_ratio * 100:.0f}% 目標,已保留目前最小版本。" ) elif target_bytes: note = f"✅ 已達成目標:{target_ratio * 100:.0f}% 以內。" else: note = "ℹ️ 未指定目標大小,僅套用一組壓縮設定。" return { "ok": True, "message": "", "input_path": str(input_path), "input_bytes": input_bytes, "output_path": best["output"], "output_bytes": best["output_bytes"], "ratio": best["output_bytes"] / input_bytes, "met_target": met_target, "target_ratio": target_ratio, "target_bytes": target_bytes, "used": {"dpi": best["dpi"], "jpeg_quality": best["jpeg_quality"], "mono_dpi": best["mono_dpi"]}, "compatibility": compatibility, "attempts": attempts, "errors": errors, "note": note, } def pdf_summary(pdf_path): """輸出檔驗證用摘要:頁數、字型數、影像數與影像解析度範圍。""" fonts = _count_pdf_fonts(pdf_path) images, pages_with_images = _image_stats(pdf_path) pages = _pdf_page_count(pdf_path) ppi_values = [] images_path = _tool("pdfimages") if images_path is not None: try: result = subprocess.run( [images_path, "-list", str(pdf_path)], capture_output=True, text=True, timeout=INSPECTION_TIMEOUT_SECONDS, check=True, ) for line in result.stdout.splitlines(): columns = line.split() if len(columns) < 14 or not columns[0].isdigit(): continue try: ppi_values.append(min(int(columns[12]), int(columns[13]))) except ValueError: continue except Exception: pass return { "pages": pages, "font_count": fonts, "image_count": images, "pages_with_images": len(pages_with_images), "min_image_ppi": min(ppi_values) if ppi_values else None, "max_image_ppi": max(ppi_values) if ppi_values else None, } def format_output_verification(result, before_summary, after_summary, report_path=None): """壓縮後驗證:文字層是否還在、圖片解析度是否真的降下來。""" lines = ["", "🔍 壓縮後驗證"] if after_summary: lines.append( f"頁數:{after_summary.get('pages')}(壓縮前 {before_summary.get('pages') if before_summary else '未知'})" ) lines.append( f"字型資源:{after_summary.get('font_count')}(壓縮前 {before_summary.get('font_count') if before_summary else '未知'})" ) if after_summary.get("image_count"): lines.append( f"影像解析度:{after_summary.get('min_image_ppi')}–{after_summary.get('max_image_ppi')} ppi" f"(壓縮前 {before_summary.get('min_image_ppi') if before_summary else '未知'}–" f"{before_summary.get('max_image_ppi') if before_summary else '未知'} ppi)" ) else: lines.append("影像:壓縮後沒有點陣圖片(原本是純向量/文字檔)") before_fonts = (before_summary or {}).get("font_count") or 0 after_fonts = after_summary.get("font_count") or 0 if before_fonts and after_fonts: lines.append("✅ 文字層保留:壓縮後仍偵測到字型資源,可搜尋文字仍存在。") elif before_fonts and not after_fonts: lines.append("⚠️ 壓縮後偵測不到字型資源,請確認文字是否遺失。") elif not before_fonts: lines.append("ℹ️ 原檔本來就沒有文字層(純掃描影像),壓縮不會讓它變成可搜尋。") before_pages = (before_summary or {}).get("pages") if before_pages and after_summary.get("pages") and before_pages != after_summary["pages"]: lines.append("⚠️ 頁數不一致,請回報此案例。") else: lines.append("(缺少 poppler 工具,無法產生驗證摘要)") if report_path: lines.append(f"📋 驗證報告:{Path(report_path).name}") return "\n".join(lines) # ============================================================ # 報告 # ============================================================ def human_bytes(value): value = float(value) for unit in ("B", "KB", "MB", "GB"): if value < 1024 or unit == "GB": return f"{value:.1f} {unit}" if unit != "B" else f"{int(value)} B" value /= 1024 def format_compress_report(result, classification=None): """產生介面用的壓縮結果文字。""" if not result.get("ok"): return result.get("message", "❌ 壓縮失敗。") target_text = f"{result['target_ratio'] * 100:.0f}%" if result.get("target_ratio") else "未指定" lines = [ "✅ PDF 壓縮完成", f"📦 壓縮前:{human_bytes(result['input_bytes'])}", f"📦 壓縮後:{human_bytes(result['output_bytes'])}({result['ratio'] * 100:.1f}% of 原檔)", f"🎯 目標:{target_text}", f"🔧 使用設定:{result['used']['dpi']} dpi/JPEG {result['used']['jpeg_quality']}/單色 {result['used']['mono_dpi']} ppi", f"📐 相容版本:PDF {result['compatibility']}", f"🔤 字型:全部嵌入並子集化(MaxSubsetPct=100)", result["note"], ] if classification: lines.append( f"🔎 文件類型:{classification['label']}(字型 {classification['font_count'] if classification['font_count'] is not None else '未知'} 個、" f"影像 {classification['image_count'] if classification['image_count'] is not None else '未知'} 張、" f"頁數 {classification['pages'] if classification['pages'] is not None else '未知'})" ) lines.append(f"💡 {classification['advice']}") if len(result["attempts"]) > 1: lines.append("📉 嘗試紀錄:" + "、".join( f"{item['dpi']}dpi/Q{item['jpeg_quality']} → {human_bytes(item['output_bytes'])}" for item in result["attempts"] )) if result.get("errors"): lines.append("⚠️ 部分嘗試失敗:" + ";".join(result["errors"][-3:])) return "\n".join(lines) def build_report_json(result, classification=None): """驗證報告(與輸出 PDF 同名 .json 寫在工作目錄)。""" return { "input": result.get("input_path"), "output": result.get("output_path"), "inputBytes": result.get("input_bytes"), "outputBytes": result.get("output_bytes"), "ratio": round(result.get("ratio", 0), 4), "metTarget": result.get("met_target"), "targetRatio": result.get("target_ratio"), "usedSettings": result.get("used"), "compatibilityLevel": result.get("compatibility"), "attempts": [ { "dpi": item["dpi"], "jpegQuality": item["jpeg_quality"], "monoDpi": item["mono_dpi"], "outputBytes": item["output_bytes"], "ratio": round(item["ratio"], 4), } for item in result.get("attempts", []) ], "classification": classification, "errors": result.get("errors", []), } def write_report(result, classification=None, path=None): """把驗證報告寫成 JSON,回傳路徑。""" target = Path(path) if path else Path(result["output_path"]).with_suffix(".report.json") target.write_text( json.dumps(build_report_json(result, classification), ensure_ascii=False, indent=2), encoding="utf-8", ) return str(target)