The Complete Production SOP: How to Deploy and Run Ghostscript PDF Compression & Repair in Autonomous AI Agents
Step-by-step SOP to install and run Ghostscript PDF Compression in Codex, Claude Code, and Cursor. Includes verified prompts, sandbox rules, and troubleshooting.
Technical Overview & Architectural Context
Autonomous coding agents frequently corrupt PDF assets when attempting ad-hoc file size reduction. Without explicit procedural boundaries, LLMs resort to destructive Python libraries like pypdf or PyMuPDF without understanding downsampling nuances, or they run unconstrained Ghostscript flags that strip font bytecode, destroy embedded CID font mappings, or discard form fields. Furthermore, generic agents fail to verify xref cross-reference integrity post-write, resulting in unopenable, malformed binary files that crash standard PDF viewers. The 'Ghostscript PDF Compression & Repair' skill establishes deterministic execution constraints. It forces agents to utilize audited PostScript device flags (`-sDEVICE=pdfwrite`, `-dCompatibilityLevel=1.4`, `-dPDFSETTINGS=/ebook`), enforce strict non-destructive font re-encoding, and systematically execute linearization (`qpdf --linearize`) for web fast-view. By locking execution parameters to workspace boundaries, it eliminates agent hallucination, prevents binary clobbering, and guarantees byte-level integrity checks prior to marking tasks complete.
Prerequisites & Environment Requirements
Verified Search Intents & Long-Tail Queries Solved
This operational tutorial is engineered to provide deterministic solutions for these developer search queries:
Step-by-Step Execution Playbook
Local Environment Setup & SKILL.md Mounting
Create the local skill manifest directory and inject verified procedural rules into your agent's workspace configuration.
Agent runtimes such as Claude Code and Cursor scan defined directories (`.claude/skills/`, `.cursor/rules/`, or generic agent root `~/.agents/skills/`) to parse SKILL.md frontmatter. Placing the manifest in the target directory informs the agent's intent-matching engine to bind Ghostscript parameter boundaries to incoming PDF optimization requests.
mkdir -p .agents/skills/ghostscript-pdf-compression && cat << 'EOF' > .agents/skills/ghostscript-pdf-compression/SKILL.md
---
name: "ghostscript-pdf-compression"
description: "Shrink oversized PDF file sizes and repair corrupted font encodings using Ghostscript."
metadata:
author: "Artifex"
version: "1.0.0"
runtime_compatibility:
- "codex"
- "claude-code"
- "cursor"
- "windsurf"
triggers:
- "compress large pdf ghostscript"
- "optimize pdf for web fast view"
- "repair damaged pdf file"
permissions:
fs_read: true
fs_write: "workspace"
shell_exec: true
net_access: false
---
# Ghostscript PDF Compression & Repair
Optimizes PDF document sizes via Ghostscript gs CLI: downsampling images (ebook, screen, prepress settings), linearizing for web fast-view, and repairing broken cross-reference tables.
## When to Invoke
Invoke this skill whenever you need to:
- compress large pdf ghostscript
- optimize pdf for web fast view
- repair damaged pdf file
## Execution SOP & Rules
1. Run gs -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dPDFSETTINGS=/ebook -dNOPAUSE -dQUIET -dBATCH -sOutputFile="${OUTPUT_PDF}" "${INPUT_PDF}".
2. Select /screen (72dpi), /ebook (150dpi), or /prepress (300dpi) according to output needs.
3. Use qpdf --linearize on the compressed file to optimize byte-serving for web view.
4. Verify visual readability of fine text and table lines after image downsampling.
## Verification Checklist
- Ensure Ghostscript exit code is 0.
- Run pdfinfo and pdftoppm or mutool to verify page count matches source.
- Confirm file size delta is negative without corrupting font embeddings.
EOF---
name: "ghostscript-pdf-compression"
description: "Shrink oversized PDF file sizes and repair corrupted font encodings using Ghostscript."
triggers:
- "compress large pdf ghostscript"
- "optimize pdf for web fast view"
- "repair damaged pdf file"
---Keep the SKILL.md concise. Supplying exact flags (`-dNOPAUSE -dQUIET -dBATCH`) directly in the frontmatter SOP prevents the agent from invoking verbose debug modes that dump megabytes of PostScript operator logs into the LLM context window.
Ensure that the agent's permission model allows shell execution for `gs` and `qpdf`. If `shell_exec` is set to false in strict sandboxes, the agent will silently attempt python fallback mocks that strip vector art.
System Binary & Dependency Validation
Verify Ghostscript and QPDF binaries exist in the execution environment and test font library availability.
Autonomous agents often fail halfway through PDF processing when required system libraries like libgs, ghostscript, or qpdf are absent. Running an initial health check ensures proper error surfaces are captured before processing critical documents.
which gs && gs --version && which qpdf && qpdf --version || (apt-get update && apt-get install -y ghostscript qpdf)Never execute Ghostscript directly against untrusted PDF inputs without `-dSAFER` enabled (enabled by default in modern gs) to prevent PostScript arbitrary file system execution.
Do not configure PDF outputs to overwrite input source paths in place. Ghostscript opens files incrementally and writing directly to the input descriptor leads to an empty 0-byte corrupted file.
Intent Matching & Trigger Invocation
Trigger the deterministic optimization workflow using audited agent prompts.
Agent runtimes compare user inputs against the SKILL.md `triggers` block. By providing clear targets ('compress large pdf ghostscript', 'optimize pdf for web fast view'), the runtime loads the exact procedural steps into short-term memory.
State the compression target clearly (e.g., target DPI, /ebook vs /screen) in the user prompt to prevent the agent from guessing destructive 72 DPI settings for print-bound documents.
Verification, Structural Linting & Quality Gate
Execute structural cross-reference checks and visual fidelity assertions before releasing the PDF.
The skill mandates running `pdfinfo` and `qpdf --check` to guarantee the output document satisfies PDF 1.4+ specifications and contains valid xref streams.
qpdf --check dist/output_optimized.pdf && pdfinfo dist/output_optimized.pdfCompare the page count between source and destination using `pdfinfo in.pdf | grep Pages` versus `pdfinfo out.pdf | grep Pages` to instantly catch missing pages caused by syntax aborts.
Real-World Scenario: Compress a 120MB Annual Report PDF with Broken xref to Under 15MB for Web Distribution
“We have an oversized 120MB PDF at docs/annual_report.pdf that fails to render properly in web browsers due to corrupt cross-references. Please repair damaged pdf file, compress large pdf ghostscript with /ebook settings, and optimize pdf for web fast view so it linearizes cleanly under 15MB.”
Runtime Troubleshooting & Failure Modes
Root Cause: The source PDF references a non-standard embedded Type 1 or TrueType font whose font descriptors or glyph encodings are corrupted, causing Ghostscript's font loader to panic.
gs -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dPDFSETTINGS=/ebook -dNOPAUSE -dQUIET -dBATCH -dEmbedAllFonts=true -dSubsetFonts=true -dPassThroughJPEGImages=true -sOutputFile=fixed.pdf input.pdfRoot Cause: Linearization tool fails because Ghostscript output was aborted prematurely or the input file had severed trailer dictionaries.
qpdf --fix-qdf --replace-input input.pdf && gs -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 -dPDFSETTINGS=/ebook -dNOPAUSE -dQUIET -dBATCH -sOutputFile=repaired.pdf input.pdfFrequently Asked Questions (Ghostscript PDF Compression & Repair SOP)
Q:Can I use Ghostscript PDF Compression & Repair across Codex, Claude Code, and Cursor simultaneously?
Yes. This skill adheres strictly to universal SKILL.md standards. Placing the file in your project's `.agents/skills/` or runtime-specific config folders (`.claude/skills` or `.cursor/rules`) allows all four runtimes to load the deterministic compression commands identically.
Q:How does Ghostscript PDF Compression & Repair prevent context window overflow during long agent sessions?
Ghostscript can output thousands of lines of PostScript operator telemetry when verbose modes are enabled. This skill enforces `-dQUIET -dNOPAUSE -dBATCH` flags, suppressing standard output while routing critical errors to stderr, saving valuable context tokens.
Q:Does this skill require escalated root or container permissions?
No. The skill maintains a security score of 98/100 by executing entirely within the workspace file tree. It requires read access to the input PDF, write access to the workspace output directory, and local execution rights for standard `gs` and `qpdf` binaries without root privileges.
Ready to equip your autonomous agent with Ghostscript PDF Compression & Repair?
Copy the complete audited SKILL.md specification or download the 1-click zip bundle directly from our verified registry.