Skip to main content

A simple Python EPUB 3.0 generator with a single API call

Project description

EPUB Generator

A simple Python EPUB 3.0 generator with a single API call.

ci pip install epub-generator pypi epub-generator python versions license

Quick Start

Installation

pip install epub-generator

Generate Your First Book in 5 Minutes

from epub_generator import generate_epub, EpubData, BookMeta, TocItem, Chapter, TextBlock, TextKind

# Prepare book data
epub_data = EpubData(
    meta=BookMeta(
        title="My First Book",
        authors=["John Doe"],
    ),
    chapters=[
        TocItem(
            title="Chapter 1",
            get_chapter=lambda: Chapter(
                elements=[
                    TextBlock(kind=TextKind.HEADLINE, level=0, content=["Chapter 1"]),
                    TextBlock(kind=TextKind.BODY, level=0, content=["This is the first paragraph."]),
                    TextBlock(kind=TextKind.BODY, level=0, content=["This is the second paragraph."]),
                ]
            ),
        ),
    ],
)

# Generate EPUB file
generate_epub(epub_data, "my_book.epub")

That's it! You now have a valid EPUB 3.0 ebook file.

Features

  • Minimal API: Just one function call generate_epub()
  • EPUB 3.0: Generates standards-compliant EPUB 3.0 format
  • Rich Content: Supports text, images, tables, math formulas (block-level and inline), footnotes, custom HTML tags
  • Flexible Structure: Nested chapters, prefaces, cover images
  • Math Support: LaTeX to MathML/SVG conversion with inline formula support
  • Type Safe: Full type annotations included

Advanced Usage

Add Cover and Complete Metadata

from datetime import datetime, timezone
from pathlib import Path
from epub_generator import generate_epub, EpubData, BookMeta, TocItem, Chapter, TextBlock, TextKind

epub_data = EpubData(
    meta=BookMeta(
        title="Complete Example",
        description="A book with full metadata",
        publisher="Example Publisher",
        isbn="978-0-123456-78-9",
        authors=["Author One", "Author Two"],
        editors=["Editor"],
        translators=["Translator"],
        modified=datetime.now(timezone.utc),
    ),
    cover_image_path=Path("cover.png"),  # Cover image
    chapters=[
        TocItem(
            title="Chapter 1",
            get_chapter=lambda: Chapter(
                elements=[
                    TextBlock(kind=TextKind.HEADLINE, level=0, content=["Chapter 1"]),
                    TextBlock(kind=TextKind.BODY, level=0, content=["Main content..."]),
                ]
            ),
        ),
    ],
)

generate_epub(epub_data, "book_with_cover.epub")

Nested Chapter Structure

from epub_generator import generate_epub, EpubData, TocItem, Chapter, TextBlock, TextKind

epub_data = EpubData(
    chapters=[
        TocItem(
            title="Part 1",
            children=[  # Nested sub-chapters
                TocItem(
                    title="Chapter 1.1",
                    get_chapter=lambda: Chapter(
                        elements=[
                            TextBlock(kind=TextKind.BODY, level=0, content=["Content 1.1..."]),
                        ]
                    ),
                ),
                TocItem(
                    title="Chapter 1.2",
                    get_chapter=lambda: Chapter(
                        elements=[
                            TextBlock(kind=TextKind.BODY, level=0, content=["Content 1.2..."]),
                        ]
                    ),
                ),
            ],
        ),
    ],
)

generate_epub(epub_data, "book_with_nested_chapters.epub")

Add Images

from pathlib import Path
from epub_generator import generate_epub, EpubData, TocItem, Chapter, TextBlock, TextKind, Image

epub_data = EpubData(
    chapters=[
        TocItem(
            title="Chapter 1",
            get_chapter=lambda: Chapter(
                elements=[
                    TextBlock(kind=TextKind.BODY, level=0, content=["Here's an image:"]),
                    Image(
                        path=Path("image.png"),  # Image path
                        alt_text="Image description",
                    ),
                ]
            ),
        ),
    ],
)

generate_epub(epub_data, "book_with_images.epub")

Add Footnotes

from epub_generator import generate_epub, EpubData, TocItem, Chapter, TextBlock, TextKind, Mark, Footnote

epub_data = EpubData(
    chapters=[
        TocItem(
            title="Chapter 1",
            get_chapter=lambda: Chapter(
                elements=[
                    TextBlock(
                        kind=TextKind.BODY,
                        level=0,
                        content=[
                            "This is text with a footnote",
                            Mark(id=1),  # Footnote marker
                            ".",
                        ],
                    ),
                ],
                footnotes=[
                    Footnote(
                        id=1,
                        contents=[
                            TextBlock(kind=TextKind.BODY, level=0, content=["This is the footnote content."]),
                        ],
                    ),
                ],
            ),
        ),
    ],
)

generate_epub(epub_data, "book_with_footnotes.epub")

Add Tables

from epub_generator import generate_epub, EpubData, TocItem, Chapter, TextBlock, TextKind, Table

epub_data = EpubData(
    chapters=[
        TocItem(
            title="Chapter 1",
            get_chapter=lambda: Chapter(
                elements=[
                    TextBlock(kind=TextKind.BODY, level=0, content=["Here's a table:"]),
                    Table(
                        html_content="""
                        <table>
                            <tr><th>Name</th><th>Age</th></tr>
                            <tr><td>Alice</td><td>25</td></tr>
                            <tr><td>Bob</td><td>30</td></tr>
                        </table>
                        """
                    ),
                ]
            ),
        ),
    ],
)

generate_epub(epub_data, "book_with_tables.epub")

Add Math Formulas

Block-level formulas:

from epub_generator import generate_epub, EpubData, TocItem, Chapter, TextBlock, TextKind, Formula, LaTeXRender

epub_data = EpubData(
    chapters=[
        TocItem(
            title="Chapter 1",
            get_chapter=lambda: Chapter(
                elements=[
                    TextBlock(kind=TextKind.BODY, level=0, content=["Pythagorean theorem:"]),
                    Formula(latex_expression="x^2 + y^2 = z^2"),  # Block-level formula
                ]
            ),
        ),
    ],
)

# Render math formulas using MathML
generate_epub(epub_data, "book_with_math.epub", latex_render=LaTeXRender.MATHML)

Inline formulas embedded in text:

epub_data = EpubData(
    chapters=[
        TocItem(
            title="Chapter 1",
            get_chapter=lambda: Chapter(
                elements=[
                    TextBlock(
                        kind=TextKind.BODY,
                        level=0,
                        content=[
                            "The Pythagorean theorem ",
                            Formula(latex_expression="a^2 + b^2 = c^2"),  # Inline formula
                            " is fundamental. Einstein's equation ",
                            Formula(latex_expression="E = mc^2"),
                            " shows mass-energy equivalence.",
                        ],
                    ),
                ]
            ),
        ),
    ],
)

generate_epub(epub_data, "book_with_inline_math.epub", latex_render=LaTeXRender.MATHML)

Add Custom HTML Tags

You can embed custom HTML tags within text content:

from epub_generator import generate_epub, EpubData, TocItem, Chapter, TextBlock, TextKind, HTMLTag

epub_data = EpubData(
    chapters=[
        TocItem(
            title="Chapter 1",
            get_chapter=lambda: Chapter(elements=[TextBlock(
                kind=TextKind.BODY,
                level=0,
                content=[
                    "This is normal text with ",
                    HTMLTag(
                        name="span",
                        attributes=[("class", "highlight"), ("style", "color: red;")],
                        content=["highlighted content"],
                    ),
                    " and more text with ",
                    HTMLTag(
                        name="strong",
                        content=["bold text"],
                    ),
                    ".",
                ],
            )]),
        ),
    ],
)

generate_epub(epub_data, "book_with_html_tags.epub")

Add Prefaces

from epub_generator import generate_epub, EpubData, BookMeta, TocItem, Chapter, TextBlock, TextKind

epub_data = EpubData(
    meta=BookMeta(title="Book with Prefaces"),
    prefaces=[  # Preface chapters
        TocItem(
            title="Preface",
            get_chapter=lambda: Chapter(
                elements=[
                    TextBlock(kind=TextKind.HEADLINE, level=0, content=["Preface"]),
                    TextBlock(kind=TextKind.BODY, level=0, content=["This is the preface content..."]),
                ]
            ),
        ),
    ],
    chapters=[  # Main chapters
        TocItem(
            title="Chapter 1",
            get_chapter=lambda: Chapter(
                elements=[
                    TextBlock(kind=TextKind.BODY, level=0, content=["Main content..."]),
                ]
            ),
        ),
    ],
)

generate_epub(epub_data, "book_with_prefaces.epub")

API Reference

Core Function

generate_epub()

def generate_epub(
    epub_data: EpubData,
    epub_file_path: PathLike,
    lan: Literal["zh", "en"] = "zh",
    table_render: TableRender = TableRender.HTML,
    latex_render: LaTeXRender = LaTeXRender.MATHML,
) -> None:

Parameters:

  • epub_data: Complete ebook data
  • epub_file_path: Output file path
  • lan: Language ("zh" or "en", defaults to "zh")
  • table_render: Table rendering mode (defaults to TableRender.HTML)
  • latex_render: Math formula rendering mode (defaults to LaTeXRender.MATHML)

Data Types

EpubData

Complete EPUB book data structure.

@dataclass
class EpubData:
    meta: BookMeta | None = None                # Book metadata
    get_head: ChapterGetter | None = None       # Head chapter without TOC entry
    prefaces: list[TocItem] = []                # Preface chapters
    chapters: list[TocItem] = []                # Main chapters
    cover_image_path: Path | None = None        # Cover image path

BookMeta

Book metadata information.

@dataclass
class BookMeta:
    title: str | None = None                    # Book title
    description: str | None = None              # Description
    publisher: str | None = None                # Publisher
    isbn: str | None = None                     # ISBN
    authors: list[str] = []                     # Authors list
    editors: list[str] = []                     # Editors list
    translators: list[str] = []                 # Translators list
    modified: datetime | None = None            # Modification timestamp

TocItem

Table of contents item with title, content, and optional nested children.

@dataclass
class TocItem:
    title: str                                  # Chapter title
    get_chapter: ChapterGetter | None = None    # Chapter content getter
    children: list[TocItem] = []                # Nested sub-chapters

Chapter

Complete content of a single chapter.

@dataclass
class Chapter:
    elements: list[ContentBlock] = []           # Main content blocks
    footnotes: list[Footnote] = []              # Footnotes

Content Block Types

ContentBlock is a union of:

  • TextBlock: Text paragraph

    @dataclass
    class TextBlock:
        kind: TextKind                                # BODY | HEADLINE | QUOTE
        level: int                                    # Heading level (0→h1, 1→h2, max h6; only for HEADLINE)
        content: list[str | Mark | Formula | HTMLTag] # Text with optional marks, inline formulas, and HTML tags
    
  • Image: Image reference

    @dataclass
    class Image:
        path: Path                                # Image file path (absolute)
        alt_text: str = "image"                   # Alt text
    
  • Table: HTML table

    @dataclass
    class Table:
        html_content: str                         # HTML table markup
    
  • Formula: Mathematical formula

    @dataclass
    class Formula:
        latex_expression: str                     # LaTeX expression
    
  • HTMLTag: HTML tag

    @dataclass
    class HTMLTag:
        name: str                                 # Tag name (e.g., "span", "div")
        attributes: list[tuple[str, str]] = []    # List of (attribute, value) pairs
        content: list[str | Mark | Formula | HTMLTag] = [] # Inner HTML content
    

Footnote

Footnote/citation.

@dataclass
class Footnote:
    id: int                                     # Footnote ID
    has_mark: bool = True                       # Whether contains mark indicator
    contents: list[ContentBlock] = []           # Content blocks

Mark

Footnote reference marker.

@dataclass
class Mark:
    id: int                                     # Reference ID, matches Footnote.id

Configuration Options

TextKind

Text type enumeration.

class TextKind(Enum):
    BODY = "body"                               # Regular paragraph
    HEADLINE = "headline"                       # Chapter heading
    QUOTE = "quote"                             # Quoted text

TableRender

Table rendering mode.

class TableRender(Enum):
    HTML = "html"                               # HTML rendering

LaTeXRender

Math formula rendering mode.

class LaTeXRender(Enum):
    MATHML = "mathml"                           # MathML rendering

Development

Install Development Dependencies

poetry install

Run Tests

python -m pytest tests/

Requires epubcheck to validate generated EPUB files.

License

MIT License

Author

Tao Zeyu i@taozeyu.com

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

epub_generator-0.1.7.tar.gz (20.8 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

epub_generator-0.1.7-py3-none-any.whl (25.5 kB view details)

Uploaded Python 3

File details

Details for the file epub_generator-0.1.7.tar.gz.

File metadata

  • Download URL: epub_generator-0.1.7.tar.gz
  • Upload date:
  • Size: 20.8 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/2.1.3 CPython/3.13.4 Darwin/25.2.0

File hashes

Hashes for epub_generator-0.1.7.tar.gz
Algorithm Hash digest
SHA256 9934899a552f2e915b0d3d22e7ea158858448de25163e95e12a5282c62e3da4a
MD5 449a8702f5165ddd1c74bd0822a51430
BLAKE2b-256 d04e13740c4940e785a47c78b6f8231311f32825a3d08d73b61f9723e1423202

See more details on using hashes here.

File details

Details for the file epub_generator-0.1.7-py3-none-any.whl.

File metadata

  • Download URL: epub_generator-0.1.7-py3-none-any.whl
  • Upload date:
  • Size: 25.5 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/2.1.3 CPython/3.13.4 Darwin/25.2.0

File hashes

Hashes for epub_generator-0.1.7-py3-none-any.whl
Algorithm Hash digest
SHA256 e727d6fd8251bcc7a452b4fe0d63dc87b7f34e7b6b0891d482ff6c5a33dfad19
MD5 b2d0df5eea7600e686af3c5607285c63
BLAKE2b-256 a7726bd5c1b66b306e9ea0d72b39dd80f36adff5951e8f97a2be534c24975671

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page