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

pdf-to-html — скилл для Claude Code: PDF в читаемый HTML

Превращает PDF в один самодостаточный HTML-файл с картинками, таблицами и порядком чтения. Пригодится, когда хочется читать отчёт с телефона, а не листать страницы.

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

Что делает pdf-to-html

Скилл ведёт PDF по цепочке «извлечь → посмотреть → (перевести) → собрать → проверить». Сначала extract_pdf.py вытаскивает текстовые блоки с размерами шрифта и картинки, отдельно помечая декоративные, и рендерит по PNG на каждую страницу. Потом агент читает эти PNG — без этого шага вёрстка вслепую и таблицы с графиками легко потерять.

Сборка идёт через build_html.py. Скрипт сам выводит уровни заголовков из размера шрифта, выкидывает декор и вшивает картинки в base64 — на выходе один файл, который открывается двойным щелчком. Перевод опционален: параллельный воркфлоу переводит страницы и подписи к графикам, сверяя терминологию, и отдаёт оверлеи units.json и caps.json.

Перед запуском нужны uv и Google Chrome или Chromium. Python-пакеты PyMuPDF, Pillow и numpy подтягиваются через uv run --with, ставить их заранее не надо. Сканы без текстового слоя сначала прогоняют через OCR. Сложные многоколоночные таблицы теряют сетку: PyMuPDF читает таблицу как текстовые блоки, поэтому текст останется, а выравнивание колонок поплывёт — для таких страниц лучше взять doc-to-markdown.

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

  • прочитать PDF-отчёт как веб-страницу на телефоне
  • собрать один HTML-файл с вшитыми картинками и таблицами
  • перевести PDF на другой язык, сохранив графики и подписи
  • отрендерить страницы PDF в PNG и глазами проверить вёрстку
  • проверить готовый HTML в headless Chrome на обрезанные таблицы

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

  • сделай из этого PDF читаемую HTML-страницу
  • переведи этот отчёт на русский, но не потеряй графики
  • хочу почитать этот PDF с телефона — собери HTML

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

1Через Skills CLI (Vercel)

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

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

~/.claude/skills/pdf-to-html/SKILL.md

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

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

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

frontend-visual-qa Проверяет уже отрендеренный интерфейс в реальном браузере: типографику, переполнение, адаптив, маршруты, графики. Пригодится после вёрстки, когда сборка прошла, а глазами никто не смотрел. CX Codex +1 572установок benchmark-due-diligence Проверяет надутый успех конкурента, отделяет маркетинг от реальных сигналов и переносит рабочий сценарий на ваши ресурсы. CX Codex +1 483установок bigdata-skill Выгружает структурированные финансовые данные и новости Bigdata.com (RavenPack) через SDK и REST API. Пригодится для построения датасетов, когда ответов MCP-сервера не хватает. CX Codex +1 473установок auto-repo-setup Диагностирует и починяет окружение репозитория, синхронизацию перед работой и хуки. Пригодится, когда проект не запускается или нужен безопасный commit. CX Codex +1 469установок terminal-screenshot Рендерит вывод консольных команд с ANSI-цветами в PNG-изображение. Это нужно, чтобы агент мог визуально оценить контрастность тем и подсветку синтаксиса в терминале. CX Codex +1 433установок claude-usage-analyst Скилл объясняет, куда ушли токены и деньги в Claude: собирает данные ccusage, показывает модель, кэш и пятичасовые блоки. CX Codex +1 403установок marketplace-health-check Прогоняет параллельный аудит репозитория скиллов: безопасность скриптов, документация, PII, открытые PR и issues, целостность манифеста. CX Codex +1 389установок llm-eval-harness Скилл гоняет чужой LLM-эндпоинт по шести измерениям: доступность, доходимость запроса, скорость, конкурентность, протокол и регрессия качества. CX Codex +1 372установок

Похожие

pdf-design jamditis Собирает PDF-отчёты и заявки на грант из HTML: превью по ходу правок, фирменные цвета, готовый файл на выходе. CX Codex +1 504установок convert-pdf-to-md официальный github Преобразует PDF-документы в Markdown с извлечением таблиц и картинок. Помогает GitHub Copilot анализировать отчёты, договоры и счета без ручного копирования. 138установок paper-poster-html wanshuiyin Собирает постер для научных конференций в виде одного HTML-файла и выгружает в печатный PDF через Chromium. Пригодится авторам статей ICLR, NeurIPS, ICML и CVPR. CX Codex +1 311установок pdf shareAI-lab Скилл учит агента извлекать текст из PDF, собирать документы из Markdown и склеивать файлы. Пригодится, когда в задаче всплывает PDF. CX Codex +1 ★ 79 238звёзд репо translate-pdf wshuyi Переводит текст в PDF на другой язык, сохраняя структуру, цвета и фоны. Пригодится, когда нужно отдать документ на другом языке, а не пересобирать его заново. CX Codex +1 1 200установок kimi-pdf thvroyal Скилл делает PDF из HTML через Paged.js, компилирует LaTeX и разбирает готовые файлы: извлечь текст, склеить, разделить, заполнить формы. CX Codex +1 419установок

Рядом в теме «Тексты и документация»

Всё по теме «Тексты и документация» →

Вопросы о pdf-to-html

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

Выполните npx skills add daymade/claude-code-skills --skill pdf-to-html -a claude-code. Скилл встанет в ~/.claude/skills/pdf-to-html/SKILL.md.

Что делает pdf-to-html?

Конвертирует PDF в один самодостаточный HTML-файл, сохраняя картинки, таблицы, графики и порядок чтения. При желании переводит документ на другой язык, оставляя все иллюстрации на месте.

Что нужно для работы скилла?

uv для запуска Python с инлайн-зависимостями и Google Chrome или Chromium для визуальной проверки. PyMuPDF, Pillow и numpy подтягиваются автоматически через uv run --with.

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

SKILL.md · MIT
---
name: pdf-to-html
disable-model-invocation: true
description: Converts a PDF into one self-contained, readable HTML file that preserves images, tables, charts and reading order — optionally translating it into another language while keeping every figure. Uses structured extraction (PyMuPDF), font-size-driven layout, compressed base64-inlined images (a single portable file), and mandatory headless-Chrome visual verification. Use whenever someone wants to READ a PDF as a web page or clean document, turn a PDF into HTML, or translate a PDF into another language while keeping its images/tables/charts intact — e.g. "PDF 转 HTML", "把这个 PDF 转成中文网页版", "make this report readable", "translate this PDF but don't lose the charts", "I just want to read this PDF on my phone". Distinct from doc-to-markdown (plain Markdown text) and pdf-creator (Markdown→PDF) — this one produces a styled, image-faithful HTML reading experience.
---

# PDF to HTML

Turn a PDF into a single, self-contained, readable HTML file — images, tables,
charts and reading order preserved — and optionally translate it, keeping every
figure in place.

The pipeline is **extract → look → (translate) → build → verify**. The middle
"look" and final "verify" steps are where faithfulness actually comes from: a PDF
is a layout, not just a text stream, so you read the rendered pages before
building and the rendered HTML before delivering.

This skill runs **inline** (no `context: fork`): translation orchestrates a
Dynamic Workflow, and a subagent cannot spawn one.

## When to use / not use

- **Use** when the goal is to *read* a PDF as HTML/web page, to convert a PDF to
  a styled HTML document, or to translate a PDF into another language while
  keeping its figures and tables.
- **doc-to-markdown** instead if they want plain Markdown text (no styling, figures optional).
- **pdf-creator** instead for the reverse direction (Markdown → PDF).

## What it does NOT do

- **Scanned/image-only PDFs** (no text layer): OCR first (e.g. `ocrmypdf`), then use this.
- **Complex multi-column tables**: cell *text* is preserved and readable, but column
  alignment can flatten into a text flow — PyMuPDF reads a table as text blocks, not a
  grid, so the grid lines are gone. Tables that are *images* in the PDF survive as
  images. If the table's grid structure is essential, use **doc-to-markdown** (pandoc
  rebuilds real tables) or convert that page separately.
- **Pixel-perfect facsimile**: output is a clean *re-flow* that keeps images and
  reading order, not a 1:1 copy of the original page layout.
- **Rewriting**: it translates and re-lays-out; it does not summarize, add a TL;DR,
  or editorialize. Faithfulness is the point (see Fidelity below).

## Dependencies

`uv` (runs Python with inline deps), Google Chrome or Chromium (visual
verification). Python packages come via `uv run --with`: PyMuPDF, Pillow, numpy.
Nothing to pre-install beyond Chrome and uv.

## Workflow

Copy this checklist and tick as you go:

```
- [ ] 1. Extract structure + render pages   (extract_pdf.py)
- [ ] 2. Read pages/*.png — SEE the layout, find content vs decorative images
- [ ] 3. (only if translating) run the translation workflow
- [ ] 4. Build the single-file HTML          (build_html.py)
- [ ] 5. Verify visually                      (verify_render.py → Read every segment)
- [ ] 6. Deliver the .html
```

### 1. Extract

```bash
uv run --with pymupdf python scripts/extract_pdf.py input.pdf
```

Writes `input-build/` with `structure.json` (text blocks with font sizes + image
blocks flagged `decorative`), `images/`, and `pages/` (one PNG per page).

### 2. Look before you build

Read `input-build/pages/*.png`. This is not optional: you need to see the real
layout, confirm which images are content vs decoration, and spot tables/charts.
For a long PDF, read every page; for a short one it's quick. This is also where
you understand the document well enough to translate it well.

### 3. Translate (optional)

Only if the user asked for another language. Read
[references/translation_workflow.md](references/translation_workflow.md) and
follow it: a Dynamic Workflow translates pages in parallel, captions data charts,
and reconciles terminology. It produces two overlay files (`units.json`,
`caps.json`) that step 4 consumes. **Do not** hand-translate inline for anything
longer than a page — the workflow keeps terminology consistent and is far faster.

### 4. Build

```bash
# original-language HTML
uv run --with Pillow python scripts/build_html.py input-build/structure.json --out output.html

# translated HTML (overlays from step 3)
uv run --with Pillow python scripts/build_html.py input-build/structure.json --out output.html \
    --translation input-build/units.json --captions input-build/caps.json --lang zh-CN
```

`build_html.py` is **data-driven**: it infers heading levels from font size (most
common size = body; larger steps up to h3/h2/h1), drops decorative images, and
inlines content images as compressed base64 → one portable file. It is not
hand-tuned to any document. If a particular PDF has an unusual structure (e.g.
multi-column, sidebars, a figure the size heuristic misreads), read the script and
adjust — it's short and meant to be edited per document.

### 5. Verify visually (mandatory)

```bash
uv run --with Pillow --with numpy python scripts/verify_render.py output.html
```

Then **Read every `seg-*.png`** and check: fonts render (no tofu boxes), no
clipped tables/figures, headings/lists look right, all expected images present.
Text being correct does not mean the render is correct (failure_cases #7). Fix and
re-verify until it's clean.

A quick structural cross-check is fine too, but count occurrences correctly:
`grep -o '<figure>' output.html | wc -l` — **not** `grep -c` (failure_cases #1).

### 6. Deliver

Hand over the single `.html`. It's self-contained (images inlined), so it opens
with a double-click and nothing can go missing.

## Scripts

| Script | Run with | Purpose |
|--------|----------|---------|
| `scripts/extract_pdf.py` | `uv run --with pymupdf` | PDF → structure.json + images/ + page renders |
| `scripts/build_html.py` | `uv run --with Pillow` | structure.json (+ optional translation/captions) → single-file HTML |
| `scripts/verify_render.py` | `uv run --with Pillow --with numpy` | headless-Chrome render → readable PNG segments |

## Fidelity (read before translating)

The deliverable looks authoritative, so wrong content is worse than ugly content.
The non-negotiable rules — and the specific ways this has gone wrong before — are
in [references/failure_cases.md](references/failure_cases.md). The one that bites
hardest: **never give a real person an inferred translated name, and copy every
number/proper-noun verbatim** (failure_cases #6). Read that file before any
translation run; skim it before any run.

## Next Step

After producing the HTML, suggest the natural follow-up:

```
Conversion complete: output.html (single self-contained file).

Options:
A) Make a PDF of it — run /daymade-docs:pdf-creator if you want a print/share copy (Recommended if they need to send it)
B) Extract the text as Markdown instead — run /daymade-docs:doc-to-markdown (if they wanted editable text, not a reading page)
C) No thanks — the HTML is what I wanted
```

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

Смотрите также

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

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