pdf-snapshot-tester
БесплатноБез исполняемых скриптовНе проверенUse when generated PDFs (invoices, contracts, regulatory filings) must not shift layout, or a template, font or PDF library is changing. Renders pages to…
от testland★ 18 звёзд на GitHubОб этом скилле
pdf-snapshot-tester
PDFs are binary documents with embedded fonts, embedded images, and CreationDate/ID metadata. Direct binary diff is useless. The canonical approach: render per-page to image, then pixel-diff against approved baselines.
When to use
- Invoice / contract / regulatory-filing PDFs where layout regression is unacceptable.
- Pre-deploy gate before changing PDF generation library, font pack, or template.
- Cross-engine verification (WeasyPrint output vs Chromium
page.pdf()output) - the per-engine generation setup, agreement tests, and version pinning live in references/cross-engine-regression.md.
How to use
- Install Poppler (
pdftocairo/pdfinfo) pluspdf2imageand Pillow. - Generate the PDF under test and render each page to PNG at
dpi=150(300 for regulatory filings). - On the first run, save the rendered pages as approved baselines under
tests/pdf-baselines/. - On later runs, pixel-diff each page against its baseline and assert the diff ratio stays under threshold (~0.005).
- For long PDFs, target only the changed pages with
first_page/last_page. - Pin the production font pack in CI and normalize PDF metadata so baselines stay reproducible - see references/deterministic-rendering.md.
- After an intentional layout change, re-run with
UPDATE_PDF_BASELINES=1and commit the new baseline images.
Step 1 - Install Poppler + pdf2image
# Linux
apt-get install -y poppler-utils
# macOS
brew install poppler
# Python wrapper
pip install pdf2image pillow
Poppler ships pdftocairo + pdftoppm - the workhorses for
PDF → image.
Step 2 - Render PDF pages to images
from pdf2image import convert_from_path
from pathlib import Path
pages = convert_from_path(
"out.pdf",
dpi=150,
fmt="png",
output_folder=str(Path("rendered")),
paths_only=True,
)
dpi=150 balances diff sensitivity vs file size. Increase to 300
for high-stakes documents (regulatory filings).
CLI alternative:
pdftocairo -png -r 150 out.pdf rendered/page
# produces rendered/page-1.png, rendered/page-2.png, ...
Step 3 - Pixel-diff against baseline
from PIL import Image, ImageChops
def pixel_diff(actual_path, baseline_path, threshold=0.001):
a = Image.open(actual_path).convert("RGB")
b = Image.open(baseline_path).convert("RGB")
if a.size != b.size:
return 1.0 # full mismatch on dimension change
diff = ImageChops.difference(a, b)
bbox = diff.getbbox()
if not bbox:
return 0.0
diff_pixels = sum(1 for px in diff.getdata() if any(c > 5 for c in px))
total = a.size[0] * a.size[1]
return diff_pixels / total
Or use pixelmatch (Node) for a maintained reference impl.
Step 4 - Per-page assertion
def test_invoice_pdf_matches_baseline(tmp_path):
actual_pdf = tmp_path / "invoice.pdf"
generate_invoice(invoice_id="inv_001", out=actual_pdf)
pages = convert_from_path(actual_pdf, dpi=150)
for i, page_img in enumerate(pages, start=1):
actual = tmp_path / f"actual-{i}.png"
page_img.save(actual, "PNG")
baseline = Path(f"tests/pdf-baselines/inv_001-{i}.png")
diff_ratio = pixel_diff(actual, baseline)
assert diff_ratio < 0.005, f"Page {i} diff ratio {diff_ratio:.4f}"
Step 5 - Page-range targeting
For long PDFs (statements, prospectuses), test only changed pages:
pages = convert_from_path(
"out.pdf",
dpi=150,
first_page=2,
last_page=5,
)
CLI:
pdftocairo -png -r 150 -f 2 -l 5 out.pdf rendered/page
Step 6 - Update-baseline workflow
Add an opt-in update mode (analogous to Jest snapshots):
import os
def assert_pdf_matches(actual_pdf, baseline_dir, threshold=0.005):
update = os.environ.get("UPDATE_PDF_BASELINES") == "1"
pages = convert_from_path(actual_pdf, dpi=150)
for i, page_img in enumerate(pages, start=1):
baseline = baseline_dir / f"page-{i}.png"
if update or not baseline.exists():
page_img.save(baseline, "PNG")
continue
diff = pixel_diff_img(page_img, Image.open(baseline))
assert diff < threshold, f"Page {i} diff {diff}"
Run UPDATE_PDF_BASELINES=1 pytest tests/pdf/ after intentional
changes; commit the new baseline images.
Deterministic rendering
Non-deterministic PDF metadata (/CreationDate, /ID, /ModDate) and
host font substitution both invalidate baselines. Normalize metadata
with qpdf and detect missing fonts via Poppler stderr before diffing:
references/deterministic-rendering.md.
Worked example
A billing service renders invoice.pdf from an HTML template; the team
is about to swap the body font and needs proof no invoice layout shifts.
- On
main, run the suite once with `UPDATE_PDF_BASELINES
Установить pdf-snapshot-tester в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
Вложенные файлы
FAQ
Что делает скилл pdf-snapshot-tester?
Use when generated PDFs (invoices, contracts, regulatory filings) must not shift layout, or a template, font or PDF library is changing. Renders pages to images and pixel-diffs them against approved baselines, strips volatile metadata, and compares HTML-to-PDF engines.
Как установить скилл pdf-snapshot-tester?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл pdf-snapshot-tester запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
docx
Use this skill whenever the user wants to create, read, edit, or manipulate Word documents (.docx files) or Word templates (.dotx files). Triggers include…
от AnthropicUse this skill whenever the user wants to do anything with PDF files. This includes reading or extracting text/tables from PDFs, combining or merging multiple…
от Anthropicxlsx
Use this skill any time a spreadsheet file is the primary input or output. This means any task where the user wants to: open, read, edit, or fix an existing…
от Anthropicpptx
Use this skill any time a .pptx or .potx file is involved in any way — as input, output, or both. This includes: creating slide decks, pitch decks, or…
от Anthropic