koreyba

convert-pdf-to-epub

Convert PDF books to EPUB format for e-readers. Use when user asks to convert PDF to EPUB, create an e-book from PDF, make PDF readable on Kindle/phone/tablet, or extract book content from PDF. Handles: chapter detection, image extraction with optimization, footnotes/endnotes with hyperlinks, reading order for multi-column layouts. Validates conversion quality automatically.

koreyba 38 2 Updated 9mo ago

Resources

9
GitHub

Install

npx skillscat add koreyba/claude-skill-pdf-to-epub/convert-pdf-to-epub

Install via the SkillsCat registry.

SKILL.md

PDF to EPUB Converter

Convert PDF documents to high-quality EPUB files with automatic chapter detection, image optimization, and footnote hyperlinking.

Quick Start

# Run conversion (from skill directory)
python -m scripts.convert input.pdf output.epub

# Validate result
python -m scripts.validate input.pdf output.epub

Workflow Overview

The conversion follows a 3-phase process with an optional 4th phase for adaptation:

โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”     โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”     โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  1. ANALYZE     โ”‚ โ”€โ”€โ–บ โ”‚  2. CONVERT     โ”‚ โ”€โ”€โ–บ โ”‚  3. VALIDATE    โ”‚
โ”‚  - PDF structureโ”‚     โ”‚  - Apply config โ”‚     โ”‚  - Check qualityโ”‚
โ”‚  - Generate cfg โ”‚     โ”‚  - Build EPUB   โ”‚     โ”‚  - Report issuesโ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜     โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜     โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                                                        โ”‚
                                                        โ–ผ
                                              โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
                                              โ”‚  4. ADAPT       โ”‚
                                              โ”‚  (if needed)    โ”‚
                                              โ”‚  - Tune config  โ”‚
                                              โ”‚  - Modify code  โ”‚
                                              โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜

Phase 1: Analyze

Before converting, analyze the PDF to determine the best configuration:

# Open PDF and examine structure
import fitz  # pymupdf
doc = fitz.open("input.pdf")

# Check for:
# 1. Number of pages
# 2. Presence of images
# 3. Multi-column layout (compare text block x-coordinates)
# 4. Footnotes/endnotes (numbers in margins or at page bottom)
# 5. Font sizes (for heading detection thresholds)

Generate initial config based on analysis:

  • Fiction book: Use default y_sort reading order
  • Academic paper: Enable xy_cut for columns
  • Magazine: Enable image optimization, use xy_cut

Ask user to confirm the proposed configuration before proceeding.

Phase 2: Convert

Run the conversion with the generated config:

from conversion.converter import Converter
from conversion.models import ConversionConfig

config = ConversionConfig(
    page_ranges=PageRanges(skip=[1, 2], content=(3, -3)),
    exclude_regions=ExcludeRegions(top=0.05, bottom=0.05),
    reading_order_strategy="y_sort",  # or "xy_cut" for columns
    image_optimization=ImageOptimizationConfig(enabled=True),
)

converter = Converter(strategy="simple")
result = converter.convert(pdf_path, epub_path, config)

# Check confidence
if result.reading_order_confidence < 0.7:
    print("Warning: Low confidence in reading order")

Phase 3: Validate

Always validate the conversion result:

from validation.completeness_checker import CompletenessChecker
from validation.order_checker import OrderChecker

# Check text completeness
completeness = CompletenessChecker().check(pdf_text, epub_text)
print(f"Completeness: {completeness.score:.1%}")  # Should be > 95%

# Check reading order
order = OrderChecker().check(pdf_chunks, epub_chunks)
print(f"Order score: {order.score:.1%}")  # Should be > 80%

Quality gates:

  • Completeness < 95%: Text is being lost
  • Order score < 80%: Reading order is wrong

Phase 4: Adapt (if validation fails)

See Decision Tree below.


Decision Tree: When Things Go Wrong

Validation failed?
โ”‚
โ”œโ”€โ–บ Text loss > 5%?
โ”‚   โ”œโ”€โ–บ Check exclude_regions (headers/footers being cut?)
โ”‚   โ”‚   โ†’ Try: exclude_regions.top: 0.03 (reduce from 0.05)
โ”‚   โ”œโ”€โ–บ Check page_ranges (skipping too many pages?)
โ”‚   โ”‚   โ†’ Try: page_ranges.skip: [] (don't skip any)
โ”‚   โ””โ”€โ–บ Still failing? โ†’ See reference/troubleshooting.md#text-loss
โ”‚
โ”œโ”€โ–บ Wrong reading order?
โ”‚   โ”œโ”€โ–บ PDF has columns?
โ”‚   โ”‚   โ†’ Try: reading_order_strategy: "xy_cut"
โ”‚   โ”œโ”€โ–บ Columns detected but wrong?
โ”‚   โ”‚   โ†’ Try: multi_column.threshold: 0.3 (more sensitive)
โ”‚   โ””โ”€โ–บ Still failing? โ†’ See reference/troubleshooting.md#order
โ”‚
โ”œโ”€โ–บ Headings not detected?
โ”‚   โ”œโ”€โ–บ Headings only slightly larger than body?
โ”‚   โ”‚   โ†’ Try: heading_detection.font_size_threshold: 1.1
โ”‚   โ””โ”€โ–บ Custom font patterns?
โ”‚   โ”‚   โ†’ May need to modify structure_classifier.py (ADAPTABLE)
โ”‚
โ”œโ”€โ–บ Footnotes not linking?
โ”‚   โ”œโ”€โ–บ Non-standard format (not [1] or (1))?
โ”‚   โ”‚   โ†’ Add pattern to FootnoteDetector.PATTERNS
โ”‚   โ””โ”€โ–บ See reference/troubleshooting.md#footnotes
โ”‚
โ””โ”€โ–บ Other issue?
    โ””โ”€โ–บ See reference/troubleshooting.md

Three-Layer Architecture

The codebase is organized into three layers with different modification policies:

Layer 1: FROZEN (Do Not Modify)

These files implement fixed specifications or deterministic algorithms:

File Reason
core/epub_builder.py EPUB3 spec is fixed
core/text_segmenter.py Validation depends on identical chunking
validation/* Metrics must be reproducible

Never modify these files unless there's a fundamental bug.

Layer 2: CONFIGURABLE (Try Config First)

Before changing code, try adjusting configuration:

ConversionConfig:
โ”œโ”€โ”€ page_ranges         # Which pages to process
โ”œโ”€โ”€ exclude_regions     # Margins to ignore (headers/footers)
โ”œโ”€โ”€ multi_column        # Column detection settings
โ”œโ”€โ”€ reading_order_strategy  # "y_sort" or "xy_cut"
โ”œโ”€โ”€ heading_detection   # Font size thresholds
โ”œโ”€โ”€ footnote_processing # Footnote patterns
โ”œโ”€โ”€ image_optimization  # Compression settings
โ””โ”€โ”€ metadata           # Title, author, language

See reference/config-tuning.md for all parameters.

Layer 3: ADAPTABLE (Can Modify If Config Fails)

These files contain heuristics that may need tuning for specific PDFs:

File What You Can Modify
conversion/strategies/* Create new strategy subclass
detectors/structure_classifier.py Heading detection heuristics
detectors/reading_order/* Add custom sorter algorithm
detectors/footnote_detector.py Add new footnote patterns

See reference/code-adaptation.md for guidelines.


Project Structure

<skill-directory>/
โ”œโ”€โ”€ SKILL.md                     # This file
โ”œโ”€โ”€ requirements.txt             # Python dependencies
โ”œโ”€โ”€ core/                        # FROZEN: Core algorithms
โ”‚   โ”œโ”€โ”€ epub_builder.py          # EPUB3 file creation
โ”‚   โ”œโ”€โ”€ pdf_extractor.py         # PDF text/image extraction
โ”‚   โ”œโ”€โ”€ text_segmenter.py        # Deterministic chunking
โ”‚   โ””โ”€โ”€ image_optimizer.py       # Image compression
โ”‚
โ”œโ”€โ”€ conversion/                  # Main conversion logic
โ”‚   โ”œโ”€โ”€ converter.py             # Orchestrator
โ”‚   โ”œโ”€โ”€ models.py                # Data classes & configs
โ”‚   โ”œโ”€โ”€ strategies/              # ADAPTABLE: Conversion strategies
โ”‚   โ”‚   โ”œโ”€โ”€ base_strategy.py     # Template method pattern
โ”‚   โ”‚   โ””โ”€โ”€ simple_strategy.py
โ”‚   โ””โ”€โ”€ detectors/               # ADAPTABLE: Detection heuristics
โ”‚       โ”œโ”€โ”€ structure_classifier.py
โ”‚       โ”œโ”€โ”€ reading_order/
โ”‚       โ”œโ”€โ”€ footnote_detector.py
โ”‚       โ””โ”€โ”€ endnote_formatter.py
โ”‚
โ”œโ”€โ”€ validation/                  # FROZEN: Quality checking
โ”‚   โ”œโ”€โ”€ completeness_checker.py
โ”‚   โ””โ”€โ”€ order_checker.py
โ”‚
โ”œโ”€โ”€ scripts/                     # CLI entry points
โ”‚   โ”œโ”€โ”€ analyze.py
โ”‚   โ”œโ”€โ”€ convert.py
โ”‚   โ””โ”€โ”€ validate.py
โ”‚
โ”œโ”€โ”€ reference/                   # Documentation
โ”‚   โ”œโ”€โ”€ workflow.md
โ”‚   โ”œโ”€โ”€ architecture.md
โ”‚   โ”œโ”€โ”€ troubleshooting.md
โ”‚   โ”œโ”€โ”€ config-tuning.md
โ”‚   โ””โ”€โ”€ code-adaptation.md
โ”‚
โ””โ”€โ”€ examples/                    # Example configurations
    โ”œโ”€โ”€ fiction-simple.json
    โ”œโ”€โ”€ academic-multicol.json
    โ””โ”€โ”€ magazine-images.json

Example Configurations

Fiction Book (simple layout)

{
  "page_ranges": {"skip": [1, 2], "content": [3, -3]},
  "exclude_regions": {"top": 0.05, "bottom": 0.05},
  "reading_order_strategy": "y_sort",
  "heading_detection": {"font_size_threshold": 1.2}
}

Academic Paper (2-column)

{
  "page_ranges": {"skip": [1], "content": [2, -1]},
  "exclude_regions": {"top": 0.08, "bottom": 0.08},
  "reading_order_strategy": "xy_cut",
  "multi_column": {"enabled": true, "threshold": 0.4}
}

Magazine (images + columns)

{
  "reading_order_strategy": "xy_cut",
  "multi_column": {"enabled": true, "column_count": 2},
  "image_optimization": {
    "enabled": true,
    "max_width": 800,
    "jpeg_quality": 75
  }
}

Reference Documentation

For detailed information, see:


Common Commands

# Full conversion with validation (from skill directory)
python -m scripts.convert input.pdf output.epub && \
python -m scripts.validate input.pdf output.epub

# Analyze PDF structure
python -m scripts.analyze input.pdf

Quality Metrics

After conversion, always check:

Metric Good Warning Bad
Text completeness > 98% 95-98% < 95%
Reading order > 90% 80-90% < 80%
Confidence > 0.8 0.6-0.8 < 0.6

If any metric is in "Warning" or "Bad" range, follow the Decision Tree above.