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

pdf-to-markdown · claesbackman — скилл для Claude Code: что делает и как установить

Скилл pdf-to-markdown разбивает PDF на части и переводит документ в Markdown, убирая библиографию и приложения.

MIT ★ 579 обновлён 2026-10-28

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

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

Скилл преобразует PDF в текстовый Markdown с разметкой страниц. Основной сценарий опирается на утилиту pdftotext из пакета poppler. При таком подходе скрипт запускает pdftotext -layout и обрабатывает поток через awk: вставляет заголовки с номерами страниц каждые 20 страниц и отсекает служебные хвосты документа вроде разделов «References», «Bibliography» или «Appendix».

Если poppler в системе нет, скилл переключается на инструмент Read и считывает файл пачками до 20 страниц. Без установленной pdftotext обработка больших статей затягивается: чтение через Read занимает до 60 секунд на порцию в 20 страниц и может упереться в таймаут ожидания субагентов.

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

  • конвертировать академическую статью из PDF в Markdown
  • отрезать списки литературы и приложения при чтении документа
  • разобрать длинный PDF на части с отметками страниц
  • прочитать объёмный отчёт без перерасхода контекста модели

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

  • Конвертируй paper.pdf в markdown
  • Преобразуй research.pdf в читаемый markdown с помощью скилла pdf-to-markdown
  • Извлеки основной текст из docs/annual-report.pdf

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

1Через Skills CLI (Vercel)

npx skills add claesbackman/AI-research-feedback --skill pdf-to-markdown -a claude-code

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

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

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

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

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

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

Выполните команду npx skills add claesbackman/AI-research-feedback --skill pdf-to-markdown -a claude-code в терминале.

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

Он извлекает текст из PDF, расставляет блочные маркеры номеров страниц и автоматически останавливает конвертацию на библиографии или приложениях.

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

Для быстрого режима требуется утилита pdftotext из состава poppler, иначе скилл будет медленно читать файл блоками через инструмент Read.

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

SKILL.md · MIT
---
name: pdf-to-markdown
description: Split a PDF into chunks and convert it to readable markdown text. Use when the user wants to read, extract, or convert a PDF document.
user-invocable: true
argument-hint: [path/to/file.pdf]
allowed-tools: Read, Bash(mdls *), Bash(pdftotext *), Bash(which *), Write
---

# PDF Split & Convert

Convert a PDF file to readable markdown text. Handles large PDFs efficiently.

## Input

- `$ARGUMENTS[0]` — Path to the PDF file (required)

## Choose the method first

Before reading anything, check whether `pdftotext` (part of poppler) is available:

```bash
which pdftotext
```

- **If available** → use the **pdftotext path** below. It is 10–100× faster than the Read tool, uses no model context for the text content, and doesn't suffer from stream idle timeouts. **Always prefer this for PDFs longer than ~30 pages.**
- **If not available** → fall back to the **Read-tool path**. Warn the user that large PDFs (>40 pages) may hit stream idle timeouts when run in subagents (~12 min cap). Prefer running in the main conversation for large files.

## Resolve the path and get page count

1. If the path is relative, resolve it relative to the current working directory.
2. Run `mdls -name kMDItemNumberOfPages "<pdf_path>"` to get the total page count. If `mdls` is unavailable or returns `(null)`, use `pdftotext` or Read to probe.

## Method A — pdftotext (preferred)

Extract the full PDF to text in one shot, then trim at references/appendix and add page markers. `pdftotext` emits a form-feed character (`\f`) at every page break — use that for pagination.

Reference implementation (bash + awk):

```bash
PDF="$1"
OUT="${PDF%.pdf}.md"
TITLE=$(basename "${PDF%.pdf}")
TMPTXT=$(mktemp)

pdftotext -layout "$PDF" "$TMPTXT"

awk -v title="$TITLE" '
BEGIN {
    print "# " title
    print ""
    page = 1
    printf "---\n## Pages %d-%d\n---\n", page, page+19
    next_marker = page + 20
}
{
    # Convert form-feed page breaks to newlines and count pages
    n = gsub(/\f/, "\n")
    if (n > 0) {
        page += n
        if (page >= next_marker) {
            printf "\n---\n## Pages %d-%d\n---\n", next_marker, next_marker+19
            next_marker += 20
        }
    }

    # Build a stripped copy for heading detection.
    # CRITICAL: strip both form feeds AND embedded newlines — gsub above inserts
    # newlines into $0, which will defeat regex anchors like ^ and $ if you skip this.
    stripped = $0
    gsub(/[\f\n]/, "", stripped)
    sub(/^[ \t]+/, "", stripped)
    sub(/[ \t]+$/, "", stripped)

    if (length(stripped) > 0) {
        # References / Bibliography — standalone word, optionally numbered, short, no prose punctuation
        if (length(stripped) < 50 && stripped !~ /[(),;]/) {
            if (stripped ~ /^([0-9]+\.?[ \t]+)?(References|REFERENCES|Bibliography|BIBLIOGRAPHY)$/) exit
            if (stripped == "Works Cited") exit
        }

        # Appendix — length up to ~120 chars (some titles are long), no prose punctuation
        if (length(stripped) < 120 && stripped !~ /[(),;]/) {
            # "Appendix A" alone (bare letter, no title)
            if (stripped ~ /^Appendix[ \t]+[A-Z][0-9]*$/) exit
            # "Appendix A. Title" or "Appendix A: Title" — punctuation REQUIRED to avoid
            # matching body-text references like "Appendix H examines the effect..."
            if (stripped ~ /^Appendix[ \t]+[A-Z][0-9]*[.:][ \t]+[A-Z].*$/) exit
            # "APPENDIX A" variants
            if (stripped ~ /^APPENDIX[ \t]+[A-Z][0-9]*([ \t]+.*)?$/) exit
            # "Online Appendix [A]"
            if (stripped ~ /^Online[ \t]+Appendix([ \t]+[A-Z].*)?$/) exit
            # "Supplemental/Supplementary/Internet Appendix"
            if (stripped ~ /^(Supplement(al|ary)|Internet)[ \t]+Appendix([ \t]+.*)?$/) exit
        }
    }

    print
}
' "$TMPTXT" > "$OUT"

rm -f "$TMPTXT"
echo "Wrote $OUT ($(wc -l < "$OUT") lines)"
```

After running, **sanity-check the output**:

```bash
# Should print nothing if trimming worked
grep -cE "^[[:space:]]*(References|Bibliography|REFERENCES|BIBLIOGRAPHY)[[:space:]]*$" "$OUT"

# Eyeball last few lines — should be prose/conclusion, not body-of-table or mid-paragraph
tail -5 "$OUT"
```

If the tail looks truncated mid-paragraph, the heading detection likely fired on a false positive. If the tail shows references or appendix content, the detection missed the heading — inspect the PDF text around that area and extend the regex.

## Method B — Read tool (fallback when pdftotext unavailable)

1. Read the PDF in chunks of up to 20 pages at a time using the Read tool's `pages` parameter: 1-20, 21-40, 41-60, etc.
2. Focus on the **MAIN TEXT ONLY**. Stop including content once you hit "References", "Bibliography", "Works Cited", or an appendix section. If references appear mid-chunk, keep everything before them and drop the rest.
3. Compile output:
   - Save alongside the PDF with a `.md` extension.
   - Header: `# [Original Filename]`
   - Page markers between chunks: `---\n## Pages X-Y\n---`
   - Preserve extracted text as-is.

**Warning:** The Read tool is slow for large PDFs (roughly 30–60 seconds per 20-page chunk). A 60-page paper can take 3–4 minutes, and sub-agents have a ~13-minute stream idle timeout that this can hit. When running a batch of conversions, run them sequentially in the main conversation or use Method A.

## Heading-detection pitfalls (hard-won lessons)

These false positives broke earlier attempts — keep them in mind whether you use Method A or B:

- **Parenthetical references in body text** like `(see Appendix B.5)` — exclude lines containing `(`, `)`, `,`, or `;`.
- **Body text starting with "Appendix X ..."** like `Appendix H examines the differential effect...` — require punctuation (`.` or `:`) immediately after the appendix letter when a title follows. Bare "Appendix A" alone on a line is still valid.
- **Line-wrapped headings** — `pdftotext` can wrap `Online Appendix` across two lines if the PDF's layout is unusual. You'll see `Online` on one line and `Appendix` on the next. The regex above matches the joined form; if you see false trims at a lone `Appendix` line, inspect and tighten.
- **Form-feed at start of page** — `pdftotext` emits `\f` as the first character on every new page. After `gsub(/\f/, "\n")` on `$0`, the line has an embedded `\n` that defeats `^` / `$` anchors unless you also `gsub(/[\f\n]/, "", stripped)` on your detection copy.
- **Length thresholds** — simple "< 50 chars" is too tight for appendix titles. "Appendix A. Merging Mortgages with the Real Estate Database" is 59 chars. Use ~120 for appendix patterns, ~50 for bare References.
- **Numbered section headings** — some papers format as `7 References` or `7. References`. Allow an optional leading number.

## Report results

Tell the user:
- Method used (pdftotext vs Read tool)
- Total pages processed
- Output file path and final line count
- Where trimming occurred (last section / page number included)
- Any pages that were unreadable or empty

For batch conversions, print a summary table and note any files whose trim point looks suspicious (very short output, or output ending mid-sentence).

© claesbackman · MIT · claesbackman/AI-research-feedback

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

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

Сначала — pdf-to-markdown от других авторов.

pdf-to-markdown PSPDFKit-labs Скилл pdf-to-markdown для Claude Code и Codex. Превращает PDF в структурированный Markdown: заголовки, таблицы, списки и порядок чтения сохраняются. Извлекает текст для анализа или передачи агенту. CX Codex +1 870установок pdf-to-markdown aliceisjustplaying Скилл pdf-to-markdown загружает весь PDF в контекст агента как структурированный Markdown с таблицами и картинками, а не фрагментами по grep. CX Codex +1 14установок pdf-to-markdown lttr Скилл pdf-to-markdown распознаёт отсканированные и графические PDF-документы через визуальное чтение и сохраняет чистый Markdown рядом с оригиналом. CX Codex +1 5установок PDF to Markdown dudko-dev Сервер PDF to Markdown подключает ИИ-агента к API pdf2md и помогает подготовить запрос на преобразование PDF в Markdown. Для работы нужно войти в аккаунт dudko.dev. CX Codex +1 pdf официальный openai Читает, создаёт и проверяет PDF через визуальный рендер страниц — агент видит результат, а не только текст. CX Codex +1 14 000установок photo-to-scanned-pdf daymade Скилл photo-to-scanned-pdf превращает снимки документов со смартфона или цифровые файлы в чистые сканы PDF формата A4 с выравниванием и осветлением фона. CX Codex +1 358установок openai-pdf OpenAI Плагин openai-pdf помогает читать, генерировать и проверять PDF в Claude Code с контролем вёрстки страниц. ★ 540звёзд репо pdf-reading SeifBenayed Скилл pdf-reading для чтения PDF-файлов с диска: извлечение текста, растеризация страниц, анализ таблиц, картинок и вложений. CX Codex +1 ★ 116звёзд репо convert-documents-to-markdown firecrawl Скилл convert-documents-to-markdown для Claude Code конвертирует офисные документы, таблицы и PDF в GitHub-Flavored Markdown через утилиту anydoc. Извлекает данные из DOCX и XLSX без ручной вычитки. CX Codex +1 13 700установок

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

Весь набор →
audit-analysis Скилл audit-analysis запускает отдельного субагента, который враждебно проверяет изменённый код эмпирического анализа против базовой ветки и ищет ошибки до того, как их найдёт рецензент. CX Codex +1 ★ 579звёзд репо explain-diff Скилл explain-diff превращает разбор изменений кода в автономную HTML-страницу с викториной. Он пригодится, когда нужно объяснить diff и проверить, как он влияет на эмпирические результаты. CX Codex +1 ★ 579звёзд репо review-paper-light Скилл review-paper-light для Claude Code проверяет экономическую статью перед отправкой в журнал: оценивает вклад, идентификацию и причинные выводы за минуту. CX Codex +1 ★ 579звёзд репо review-paper-code Скилл review-paper-code проверяет воспроизводимость расчётов в научных статьях на LaTeX с кодом на Stata, R или Python и сверяет эмпирические выводы с кодовой базой. CX Codex +1 ★ 579звёзд репо explorable-deck Скилл explorable-deck для Claude Code создаёт презентации Quarto на reveal.js: последовательный рассказ и наглядные сцены под управлением докладчика. Задачи — лекции, конференции и разбор научных статей. CX Codex +1 ★ 579звёзд репо explorable-beamer Скилл explorable-beamer собирает PDF-презентации Beamer в explorable-стиле Ники Кейс: одна мысль на кадр, живой пример, раскрывающиеся стадии TikZ и appendix с ответвлениями. CX Codex +1 ★ 579звёзд репо explorable-pptx Скилл explorable-pptx создаёт презентации PowerPoint в стиле объяснительных моделей с заметками к каждому слайду и проверкой скриншотов. CX Codex +1 ★ 579звёзд репо paper-version Скилл paper-version для Claude Code преобразует LaTeX-статью в краткую версию для широкой аудитории и готовит HTML-страницу. Объясняет результаты исследования без академического жаргона. CX Codex +1 ★ 579звёзд репо

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

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