К основному содержанию
скилл CX Codex

photo-to-scanned-pdf — скилл для Claude Code

Скилл photo-to-scanned-pdf превращает снимки документов со смартфона или цифровые файлы в чистые сканы PDF формата A4 с выравниванием и осветлением фона.

MIT 358 установок ★ 1 540 обновлён 2026-11-07

Установить в Claude Code · Через Skills CLI (Vercel) Все способы и платформы ↓
npx skills add daymade/claude-code-skills --skill photo-to-scanned-pdf -a claude-code
Открыть на GitHub

Что делает photo-to-scanned-pdf

Скилл реализует два сценария подготовки документов. Первый берёт фотографии договоров, чеков, бланков или записей, устраняет перспективные искажения, выравнивает фон через noteshrink и собирает страницы в единый PDF формата A4. Второй сценарий работает с готовыми электронными файлами без подписи: генерирует рукописный автограф, накладывает его на нужную строку и стилизует результат под сканированный лист.

Процесс разделяет технические операции и проверку человеком или агентом. Скрипты на базе uv run берут на себя геометрию и пакетную обработку, а порядок страниц определяется строго по их содержанию, потому что имена файлов из мессенджеров часто сбивают хронологию. Цветная бумага обрабатывается отдельно от белой через предварительный баланс белого, иначе оттенок листа попадает в общую палитру и портит чернила со штампами.

Для работы требуются установленная утилита pdftoppm (из пакета Poppler) и CLI-инструмент noteshrink. Без предварительной генерации контактного листа make_contact_sheet.py финальная проверка целостности страниц считается незавершённой.

Какие задачи решает

  • Собрать фотографии договора или чеков в аккуратный скан PDF
  • Устранить перспективные искажения на снимках страниц со смартфона
  • Синтезировать рукописную подпись на цифровом бланке и стилизовать под скан
  • Очистить фон документов от теней без потери читаемости штампов

Примеры запросов агенту

  • Собери из этих фотографий документа один скан в формате PDF
  • Выровняй снимки договора, убери тени и сделай вид отсканированного документа
  • Добавь на этот документ рукописную подпись и преврати его в скан

Как установить photo-to-scanned-pdf

1Через Skills CLI (Vercel)

npx skills add daymade/claude-code-skills --skill photo-to-scanned-pdf -a claude-code

2Вручную: положить файлы

~/.claude/skills/photo-to-scanned-pdf/SKILL.md

Папка скилла целиком; для одного проекта — .claude/skills/photo-to-scanned-pdf/

По шагам, с командами для каждой платформы: Как установить скилл в Claude Code: пять способов

Вопросы о photo-to-scanned-pdf

Как установить photo-to-scanned-pdf в Claude Code?

Выполните в терминале команду npx skills add daymade/claude-code-skills --skill photo-to-scanned-pdf -a claude-code. Файл настроек сохранится по пути ~/.claude/skills/photo-to-scanned-pdf/SKILL.md.

Что делает photo-to-scanned-pdf?

Он прогоняет фото документов через выравнивание перспективы, чистку фона утилитой noteshrink и сборку в A4 PDF, а также умеет синтезировать рукописные подписи на цифровых бланках.

Какие системные зависимости нужны для запуска?

Понадобятся pdftoppm (ставится через brew install poppler), установленный uvx noteshrink и Python-окружение для запуска скриптов через uv run.

Исходный текст

SKILL.md · MIT
---
name: photo-to-scanned-pdf
disable-model-invocation: true
description: >-
  Two pipelines ending at a scanner-look PDF. (1) Phone photos of paper
  documents (contracts, stamped certificates, receipts, forms, handwritten
  notes) → clean scanner-quality PDF: perspective rectification + noteshrink
  whitening + A4 assembly + mandatory whole-document check. Trigger: "把照片
  做成扫描件", "photos to scanned PDF", "make this look scanned", "手机拍的
  文档转 PDF", "盖章文件扫描", replacing pages in an existing scanned PDF,
  any CamScanner-like request. (2) A digital document with no signature yet
  (rendered docx/PDF, confirmation form, contract draft) → make it look
  hand-signed and scanned: synthesize a handwriting-style signature, composite
  it onto the signature line, apply the same scan-look post-processing.
  Trigger: "帮我做个手写签名", "生成签名盖到这份文件上", "做成签过字的扫描件",
  "synthesize a signature", any request for a document that needs to look
  signed without a real photographed signature. Do NOT hand-roll
  levels/contrast enhancement for scan-look — tried and rejected twice; this
  skill's pipeline is the proven one.
---

# Photo → Scanned PDF

Two related pipelines, same destination look, different starting point:
phone photos of paper documents, or a digital document that needs a synthetic
signature before it looks signed. The pipelines that work, and the failure
modes that ship wrong PDFs if skipped.

**Which one do you need?**

| The input is... | Use |
|---|---|
| Existing ID/passport photos needed as printable copies | Read [identity-document copies](references/identity-document-copies.md) before processing; bind required sides/pages and the recipient's accepted copy form |
| Phone photos of an already-signed/stamped paper document | This file, main pipeline below |
| A digital document (docx/PDF) with **no signature yet**, and you need to make it look hand-signed | [references/digital-signature-synthesis.md](references/digital-signature-synthesis.md) |

```
photos ──► rectify (photo_to_scan.py --raw)
       ──► ORDER BY CONTENT, detect colored paper   ← agent eyes, not filenames
       ──► enhance: noteshrink (white batch with -g │ colored pages separately,
                                after white-balance pre-pass)
       ──► assemble_pdf.py → A4 PDF
       ──► make_contact_sheet.py → READ IT, verify EVERY page   ← mandatory
```

**Division of labor**: scripts carry execution; you (the agent) carry the two
judgment steps — content-based page ordering, and whole-document verification.
Neither can be automated away: filenames lie about order, and per-page spot
checks miss wrong-slot bugs. The digital-signature branch shares this same
philosophy with its own two judgment calls — see the reference file.

## Step 0 — Dependencies

```bash
which pdftoppm || brew install poppler   # contact sheet + any PDF rendering
uvx noteshrink --help | head -3          # first run builds it (~30 s)
```

Scripts are `uv run` single-file scripts (PEP 723); OpenCV/PIL/img2pdf resolve
automatically on first run.

## Step 1 — Rectify

```bash
uv run <skill>/scripts/photo_to_scan.py --raw --out-dir work --prefix page \
    photo1.jpg photo2.jpg ...
```

Expected: one `page_NN.jpg` per photo, each tagged `[quad]`. A
`[FULLFRAME-fallback]` tag means the paper outline wasn't found (busy background,
page cut off) — view that photo and decide: retake, or accept the uncropped frame.

The script handles EXIF rotation internally (`cv2.imread` ignores EXIF; phone
photos come rotated — this silently produces sideways pages if you rectify with
raw OpenCV).

## Step 2 — Order by content, detect colored paper (agent judgment)

**Read every rectified image** (batch of ~6 per message) and record two things:

1. **Its identity** — date, title, page number, whatever distinguishes pages.
   Batch-exported photos (WeChat, AirDrop) get timestamps of the *export*
   moment, often all within one second — filename order is meaningless. Real
   case: 17 photos turned out to be in exact reverse document order; only
   content reading caught it.
2. **Its paper color** — white, or colored (blue/yellow/pink stock)? Colored
   pages take a different path in Step 3. If unsure, sample programmatically:
   mean RGB of a blank region; `B > R + 25` ⇒ blue-ish paper.

Build the final page order as an explicit list before proceeding. If pages are
supposed to match an external register (an invoice list, a session table),
cross-check identity against it now — missing/duplicate pages found here cost
seconds; found after delivery they cost a redo.

## Step 3 — Enhance (noteshrink, split by paper color)

**White-paper pages — one batch, global palette:**

```bash
uvx noteshrink -w -g -K -q -b ns -c "true" page_03.jpg page_01.jpg page_07.jpg ...
# inputs IN FINAL PAGE ORDER → outputs ns0000.png, ns0001.png, ... in that order
```

- `-w` white background, `-g` one global palette (uniform ink/stamp color across
  pages), `-K` keep given order, `-c "true"` skips its internal PDF step (we
  assemble ourselves).
- **Pass filenames explicitly.** zsh does not word-split `$VAR` — a file list in
  a variable arrives as one giant "filename", noteshrink exits without output,
  and `-q` keeps it silent. Verify outputs exist (`ls ns0*.png`) rather than
  trusting stdout.

**Colored-paper pages — separate, with white-balance pre-pass:**

```bash
uv run <skill>/scripts/photo_to_scan.py --out-dir work --prefix wb colored_photo.jpg   # no --raw
uvx noteshrink -w -g -K -q -b nc -c "true" work/wb_01.jpg
```

Two distinct failure modes force this split (both shipped as bugs before the
rule existed):

1. **Colored pages inside the `-g` batch poison the whole document** — the paper
   color enters the global palette and white pages come out with tinted
   shadows/artifacts.
2. **noteshrink alone on colored paper whitens the background but not the
   foreground cast** — black ink photographed on blue stock reads blue-purple, a
   red stamp reads maroon. The default (non-`--raw`) mode of `photo_to_scan.py`
   divides out the paper color first, so ink returns to black and stamps to red.

## Step 4 — Assemble

```bash
uv run <skill>/scripts/assemble_pdf.py --out scanned.pdf \
    ns0000.png ns0001.png nc0000.png ns0002.png ...   # FINAL page order
```

Expected: `OK scanned.pdf (N pages, ~0.05 MB/page)`. Edge crop (default
24px top / 12px sides at 200 dpi) removes the sliver of desk surface that
rectification drags in along page borders; document margins dwarf it.

## Step 5 — Verify the WHOLE document (mandatory, not optional)

```bash
uv run <skill>/scripts/make_contact_sheet.py scanned.pdf --out contact.png
```

**Read `contact.png` and check every page**: identity sequence complete and
correct (each date/title where it should be, no duplicates, none missing), no
off-color page, stamps/signatures present. Then spot-read 1–2 pages at full
resolution for text sharpness.

For identity documents, also reconcile the required sides/spread against the
source-coverage table from the linked identity-copy procedure. A readable data
page or matching PDF page count does not establish a complete required spread.

Why whole-document, every time: two shipped-bug stories from the session this
skill was distilled from —

- A page-replacement task wrote the new page into the **wrong slot** (an
  off-by-one in a copy command), silently overwriting a neighboring page. The
  per-page check of the replaced slots passed; the clobbered neighbor was only
  caught by the user.
- A palette-poisoning bug (Step 3 #1) tinted pages that were *not* being
  edited. Checking only the edited pages missed it.

The cost asymmetry is absolute: contact sheet = one Read; a wrong page in a
delivered PDF = redo + lost trust. **"I verified the pages I changed" is not
verification.**

## Replacing pages in an existing scanned PDF

Keep the per-page enhanced PNGs (`ns*/nc*`) as the working set. To replace page
k: process the new photo through Steps 1–3, overwrite that page's PNG, re-run
Steps 4–5. When copying into numbered slots, mind the mapping — slot numbers
shift when photo order was reversed; derive the slot from the page's *content
identity*, never from its position in the photo batch. Then the Step 5 full
check is what actually protects you.

## Troubleshooting

| Symptom | Cause / fix |
|---|---|
| Output "doesn't look scanned" — gray haze, soft text | You hand-rolled levels/curves/divide enhancement. Don't — two attempts were rejected by a real user before switching to noteshrink (background sampling + palette quantization is what produces the flat-white scan look). |
| White pages have tinted shadows | A colored-paper page was inside the `-g` batch. Re-run whites-only batch (Step 3). |
| Ink looks blue/purple, stamp looks maroon on a colored page | noteshrink got the colored page raw. Insert the white-balance pre-pass (`photo_to_scan.py` without `--raw`). |
| noteshrink produced no output, no error | File list passed via an unquoted shell variable under zsh (no word splitting), or paths with spaces. Pass explicit filenames; check `ls ns0*.png`. |
| Page sideways / upside down | EXIF ignored somewhere upstream, or the quad landed landscape. `photo_to_scan.py` corrects EXIF + rotates to portrait; upside-down pages it cannot know — catch at Step 2 and rotate the source photo. |
| `[FULLFRAME-fallback]` on a photo | Paper outline not detected (low contrast vs table, page cut off). Retake against a dark background, or accept full frame + rely on edge crop. |
| Thin dark strip along page edge in the PDF | Desk surface dragged in by rectification. Raise `--crop-top/--crop-side` in `assemble_pdf.py`. |
| Pages in wrong order in the PDF | Filename-order assumption. Order comes from Step 2 content reading, passed explicitly to noteshrink (`-K`) and `assemble_pdf.py`. |

© daymade · MIT · daymade/claude-code-skills

Похожие скиллы

Все скиллы по теме «Тексты и документация» →
openai-pdf OpenAI Плагин openai-pdf помогает читать, генерировать и проверять PDF в Claude Code с контролем вёрстки страниц. ★ 540звёзд репо pdf-reading SeifBenayed Скилл pdf-reading для чтения PDF-файлов с диска: извлечение текста, растеризация страниц, анализ таблиц, картинок и вложений. CX Codex +1 ★ 116звёзд репо pdf официальный openai Читает, создаёт и проверяет PDF через визуальный рендер страниц — агент видит результат, а не только текст. CX Codex +1 14 000установок pdf-to-markdown claesbackman Скилл pdf-to-markdown разбивает PDF на части и переводит документ в Markdown, убирая библиографию и приложения. CX Codex +1 ★ 579звёзд репо pdf-to-docx claude-office-skills Скилл pdf-to-docx для Claude Code конвертирует PDF в редактируемый Word через библиотеку pdf2docx. Правит отчёты и договоры — не читает их. CX Codex +1 6 200установок pdf-processing-pro davila7 Скилл pdf-processing-pro для Claude Code обрабатывает PDF: заполняет формы, извлекает таблицы и распознаёт текст. Включается при пакетной обработке документов. CX Codex +1 5 869установок

Из того же набора102

Весь набор →
openclaw-model-switch Скилл openclaw-model-switch сменяет модель по умолчанию и чинит конфигурацию в OpenClaw. Помогает при ошибках авторизации токена, сбоях маршрутизации и неподдерживаемых уровнях thinking. CX Codex +1 387установок skill-governance Скилл skill-governance для Claude Code сверяет установленные скиллы с тем, что агент видит в каталоге. Он подключается при проверке загрузки, обрезания списка и дубликатов. CX Codex +1 368установок github-review-pr Скилл github-review-pr ревьюит пул-реквесты против живой ветки base: сверяет OID, делает three-way merge и решает, готов ли PR к мёржанию. CX Codex +1 367установок git-safety-net Скилл git-safety-net для Claude Code находит и сохраняет локальные коммиты, незакоммиченные файлы и ветки перед очисткой репозитория. Защищает от потери кода при слияниях и удалении воркдеревьев. CX Codex +1 362установок local-conversation-history Скилл local-conversation-history для Claude Code направляет запросы к нужному читателю истории диалогов. Он различает поиск сказанного и продолжение прежней работы. CX Codex +1 346установок continue-codex-work Скилл continue-codex-work для Claude Code перехватывает прерванную сессию Codex по её Session ID. Включается, когда процесс завис, сжался или требует передачи задач новому агенту. CX Codex +1 344установок claude-code-hooks Скилл claude-code-hooks помогает писать, тестировать, регистрировать и отлаживать хуки Claude Code. Он пригодится, когда правило нужно превратить в блокировку вызова инструмента. CX Codex +1 333установок docx-creator Скилл docx-creator для Claude Code создаёт DOCX из Markdown и помогает экспортировать документы Word/WPS в PDF с проверкой результата. Обрабатывает договоры и документы со сложной вёрсткой. CX Codex +1 323установок

Спонсоры проекта

Компании, которые помогают держать аналитику открытой