"""Compress a PDF file in-place using Ghostscript.""" from __future__ import annotations import shutil import subprocess import tempfile from pathlib import Path def compress_pdf_ghostscript( pdf_path: "str | Path", quality: str = "screen", ) -> bool: """Compress a PDF in-place using Ghostscript. Runs gs with downsampling (96 dpi color/gray, 200 dpi mono). Replaces the original file only when the compressed output is strictly smaller. Returns True if the file was replaced, False if gs is not available, the file does not exist, compression failed, or the output was not smaller. Args: pdf_path: Path to the PDF file to compress (modified in-place on success). quality: Ghostscript PDFSETTINGS profile. One of "screen", "ebook", "printer", "prepress". Returns: True if the file was compressed and replaced, False otherwise. """ path = Path(pdf_path) gs = shutil.which("gs") if not gs or not path.exists(): return False with tempfile.TemporaryDirectory() as tmpdir: compressed = Path(tmpdir) / "compressed.pdf" cmd = [ gs, "-sDEVICE=pdfwrite", "-dCompatibilityLevel=1.4", f"-dPDFSETTINGS=/{quality}", "-dDownsampleColorImages=true", "-dDownsampleGrayImages=true", "-dDownsampleMonoImages=true", "-dColorImageResolution=96", "-dGrayImageResolution=96", "-dMonoImageResolution=200", "-dNOPAUSE", "-dQUIET", "-dBATCH", f"-sOutputFile={compressed}", str(path), ] try: subprocess.run(cmd, check=True, capture_output=True) except subprocess.CalledProcessError: return False if compressed.exists() and compressed.stat().st_size < path.stat().st_size: import shutil as _sh _sh.copy2(str(compressed), str(path)) return True return False