pypublib package
Top-level package for pypublib.
A Python library for creating and manipulating EPUB electronic publications.
This module exposes commonly used classes and functions so users can import them as follows:
from pypublib import Book- Import the Book class
from pypublib import Chapter- Import the Chapter class
from pypublib import read_book, publish_book- Import EPUB I/O functions
from pypublib import Html- Import HTML generation utilities
from pypublib import markdown- Import Markdown conversion module
- pypublib.__version__
Current version of pypublib.
- Type:
str
- pypublib.__author__
Primary author of pypublib.
- Type:
str
- class pypublib.Book(metadata=None)[source]
Bases:
objectRepresents an EPUB book container holding:
- A Book instance manages all data needed for an EPUB publication:
metadata: Dublin Core and custom metadata
chapters: mapping of chapter href to Chapter instances
styles: global CSS stylesheets
images: image assets
fonts: embedded font files
guide: optional navigation aids
cover: filename of the cover image
Notes
A generated UUID is added as identifier if none is provided.
Convenience properties expose common metadata as attributes.
All data are stored in memory. This includes chapters, style sheets, images, and font data as binaries.
Use
publish_book()from the epub module to store all data in an EPUB file. The necessary OPF file is then created on the fly from the data in the Book structure.
- Parameters:
metadata (Dict | None)
- metadata
Dublin Core and custom metadata key-value pairs.
- Type:
dict
- chapters
Mapping of href to Chapter instances.
- Type:
dict
- styles
Mapping of filename to CSS content.
- Type:
dict
- images
Mapping of filename to binary image data.
- Type:
dict
- fonts
Mapping of filename to binary font data.
- Type:
dict
- guide
List of guide reference items.
- Type:
list
- cover
Filename of the cover image.
- Type:
str
- __repr__()[source]
Return a compact debug string representation of the book.
- Returns:
Compact representation including title, author, and asset counts.
- Return type:
str
- add_chapter(chapter, href=None)[source]
Add a new chapter, or replace a chapter using its href as the key.
- Parameters:
chapter (Chapter) – The chapter to add.
href (str, optional) – Custom href to use as key. If None, uses chapter.href. Defaults to None.
- Return type:
None
- add_chapters(*chapters)[source]
Add multiple chapters in order.
- Parameters:
*chapters (Chapter) – Variable length argument list of Chapter instances to add.
- Return type:
None
- add_cover(cover, image)[source]
Add a cover image and set it as the book cover.
Also prepends a synthetic ‘Cover.xhtml’ chapter.
- Parameters:
cover (str) – Filename of the cover image.
image (bytes | bytearray) – Binary image data.
- Return type:
None
- add_font(name, font)[source]
Add an embedded font file.
- Parameters:
name (str) – Target filename inside the EPUB.
font (bytes | bytearray) – Binary font data.
- add_image(name, image)[source]
Add an image asset.
- Parameters:
name (str) – Target filename inside the EPUB.
image (bytes | bytearray) – Binary image data.
- Return type:
None
- add_image_from_file(file)[source]
Add an image asset from a file.
Reads the file as binary and uses the filename as the key.
- Parameters:
file (str) – Path to an image file.
- Return type:
None
- add_images(images)[source]
Add multiple images from a dict of {name: image}.
- Parameters:
images (dict) – Dictionary mapping image names to binary image data.
- Return type:
None
- add_metadata(key, value)[source]
Add or replace an arbitrary metadata key/value pair.
- Parameters:
key (str) – The metadata key.
value – The metadata value.
- add_style(name, sheet)[source]
Add a global stylesheet.
- Parameters:
name (str) – Target filename inside the EPUB.
sheet (str | bytes) – CSS content as string or bytes.
- Return type:
None
- add_style_from_file(file)[source]
Add a global stylesheet from a CSS file.
Reads the file content and uses the filename as the key.
- Parameters:
file (str) – Path to a CSS file.
- Return type:
None
- add_styles(styles)[source]
Add multiple styles from a dict of {name: sheet}.
- Parameters:
styles (dict) – Dictionary mapping stylesheet names to CSS content.
- Return type:
None
- property author: str
Get the primary creator/author (alias for creator).
- Returns:
The creator name.
- Return type:
str
- property cover_image: bytes | bytearray | None
Return the raw cover image content.
- Returns:
The binary cover image data, or None if no cover is set.
- Return type:
bytes | bytearray | None
- property creator: str
Get the primary creator/author.
- Returns:
The creator name.
- Return type:
str
- property date: str
Get the publication date.
- Returns:
Publication date as string (ISO-8601 recommended).
- Return type:
str
- property description: str
Get the book description.
- Returns:
Short description or abstract.
- Return type:
str
- from_contents(contents)[source]
Populate the Book from a contents dictionary, typically extracted from an existing EPUB.
- Parameters:
contents (dict) – Dictionary with book components. Should have keys: ‘metadata’, ‘chapters’, ‘styles’, ‘images’, ‘fonts’, ‘guide’, ‘cover’.
- Return type:
None
- get_chapter(href)[source]
Return the chapter by href or None if not found.
- Parameters:
href (str) – The href of the chapter to retrieve.
- Returns:
The chapter with the specified href, or None if not found.
- Return type:
Chapter | None
- property identifier: str
Get the unique identifier.
- Returns:
Unique identifier (e.g., UUID, ISBN).
- Return type:
str
- property language: str
Get the language code.
- Returns:
Language code (e.g., ‘en’, ‘de’).
- Return type:
str
- property manifest: List[Dict[str, str]]
Generate the manifest entries for the OPF file.
Creates a list of manifest item dictionaries for all chapters, styles, images, and fonts in the book.
- Returns:
List of manifest item dictionaries with keys ‘id’, ‘href’, and ‘media-type’.
- Return type:
list
Note
Cover images are marked with the ‘cover-image’ property.
Generate the nav.xhtml content for EPUB3.
Creates the navigation document with table of contents and landmarks.
- Returns:
XHTML content for nav.xhtml file.
- Return type:
str
- property ncx: str
Generate the toc.ncx content for EPUB2 compatibility.
Creates the Navigation Center eXtended (NCX) document used for navigation in EPUB2 and as a fallback in EPUB3.
- Returns:
NCX XML content.
- Return type:
str
- property opf: str
Generate the complete OPF (Open Packaging Format) XML content.
Creates the content.opf file which defines the EPUB package structure, including metadata, manifest, spine, and guide sections.
- Returns:
Complete OPF XML as a string.
- Return type:
str
Note
The OPF file is the central descriptor of an EPUB archive structure.
- property publisher: str
Get the publisher name.
- Returns:
Publisher name.
- Return type:
str
- remove_chapter(chapter)[source]
Removes the chapter from the book.
- Parameters:
chapter (str) – The chapter or the href of the chapter to remove.
- Returns:
None.
- Return type:
None
- property series: str
Get the series name.
- Returns:
The name of the series this book belongs to.
- Return type:
str
- set_cover(cover)[source]
Set the cover image filename and ensure a cover chapter is the first entry.
- Parameters:
cover (str) – Filename of the cover image.
- Return type:
None
- set_metadata(creator=None, title=None, language='de', identifier=None, description=None, publisher=None, date=None)[source]
Bulk metadata setter for common Dublin Core metadata.
Only non-empty values are applied. Useful for setting multiple metadata fields at once during book initialization.
- Parameters:
creator (str, optional) – Creator/author name. Defaults to None.
title (str, optional) – Book title. Defaults to None.
language (str, optional) – Language code. Defaults to “de”.
identifier (str, optional) – Unique identifier. Defaults to None.
description (str, optional) – Book description. Defaults to None.
publisher (str, optional) – Publisher name. Defaults to None.
date (str, optional) – Publication date. Defaults to None.
- property subject: List[str]
Get the list of subjects/keywords.
- Returns:
Subject keywords.
- Return type:
set
- property title: str
Get the human-readable title of the book.
- Returns:
The book title.
- Return type:
str
- property toc: str
Generate the table of contents.
Alias for the ncx property.
- Returns:
TOC NCX XML content.
- Return type:
str
- class pypublib.Chapter(href, title)[source]
Bases:
objectRepresents a single chapter (XHTML document) within the EPUB.
A Chapter in an EPUB book is an XHTML file which is rendered by ebook reader software. The Chapter structure stores only the BODY content of this file, which can be modified by accessing the content attribute. The HEAD part of the file is generated on the fly by inserting the stored title and stylesheet attributes in a template. This regeneration occurs every time when the read-only HTML property is accessed.
- Parameters:
href (str)
title (str)
- href
Filename inside the EPUB archive.
- Type:
str
- content
The HTML body content of the chapter.
- Type:
str
- styles
List of stylesheet hrefs linked in the chapter head.
- Type:
list[str]
- __repr__()[source]
Return a compact debug string representation of the chapter.
- Returns:
Compact representation including title, href, and styles.
- Return type:
str
- __str__()[source]
Return a neat, human-readable chapter summary. :returns: Neat representation including title, href, and styles. :rtype: str
- Return type:
str
- add_style(style)[source]
Add a stylesheet href to the chapter.
Prevents duplicate stylesheets from being added.
- Parameters:
style (str) – The href of the stylesheet to add.
- Return type:
None
- classmethod from_content(href, title, content, styles=None)[source]
Create a Chapter instance from raw HTML content string.
Strips any existing <body> tags and wraps the content in a full XHTML structure. If styles are provided, they are linked in the <head>.
- Parameters:
href (str) – Filename inside the EPUB archive.
title (str) – Chapter title.
content (str) – Raw HTML content (may include <body> tags which will be stripped).
styles (str | list[str] | None, optional) – List of stylesheet hrefs or a single href as string. Defaults to None.
- Returns:
A new Chapter instance with the provided content.
- Return type:
Example
>>> chapter1 = Chapter.from_content("chapter1.xhtml", "Chapter 1", ... "<p>Hello world</p>", ... ["styles.css"])
- classmethod from_cover(name)[source]
Create a synthetic cover chapter.
Generates a Chapter containing a cover image displayed at full width and height.
- Parameters:
name (str) – Filename of the cover image (used in the img src attribute).
- Returns:
A new Chapter instance with cover styling applied.
- Return type:
- classmethod from_html(href, html)[source]
Create a Chapter instance from a raw HTML string using lxml.html.
The parser is more forgiving than etree and can handle typical HTML errors. Automatically removes XML declarations if present.
- Parameters:
href (str) – Filename inside the EPUB archive.
html (str) – HTML string (may contain typical HTML errors or XML declarations).
- Returns:
A new Chapter instance parsed from the HTML string.
- Return type:
Note
This method removes XML declarations automatically, making it suitable for non-strict HTML parsing. For strict XHTML validation, use
from_xhtml().
- classmethod from_xhtml(href, html)[source]
Create a Chapter instance from a raw XHTML string.
The parser is stricter than lxml.html and expects well-formed XML. Uses etree.fromstring for parsing which enforces XML compliance.
- Parameters:
href (str) – Filename inside the EPUB archive.
html (str) – Well-formed XHTML string.
- Returns:
A new Chapter instance parsed from the XHTML string.
- Return type:
- Raises:
ValueError – If the HTML is not valid XHTML or cannot be parsed.
Note
This method expects strict XML compliance. For more forgiving parsing, use
from_html()instead.
- property html: str
Get the full chapter HTML including HEAD and BODY.
Generates the HEAD section on the fly from the title and styles attributes, and combines it with the stored content attribute in the TEMPLATE_CHAPTER.
- Returns:
Complete XHTML document as string.
- Return type:
str
- property images: List[str]
Get all image src attributes from img tags in this chapter.
Parses the chapter’s HTML and extracts all src attributes from <img> elements.
- Returns:
List of image src paths referenced in this chapter.
- Return type:
list[str]
- property title: str
Get the chapter title.
- Returns:
The chapter title.
- Return type:
str
- class pypublib.Html[source]
Bases:
objectGenerator for common HTML elements.
Provides static methods for creating HTML elements from Python strings. Useful for building HTML content programmatically.
- static blockquote(text)[source]
Generate an HTML blockquote element.
- Parameters:
text (str) – The quoted text.
- Returns:
HTML blockquote element string.
- Return type:
str
- static br()[source]
Generate a line break element.
- Returns:
HTML line break string.
- Return type:
str
- static code(code, language='')[source]
Generate an HTML code block element.
- Parameters:
code (str) – The code content.
language (str, optional) – Programming language for syntax highlighting class. Defaults to empty string.
- Returns:
HTML pre/code element string.
- Return type:
str
- static em(text)[source]
Generate HTML emphasis (italic) element.
- Parameters:
text (str) – The text to emphasize.
- Returns:
HTML emphasis element string.
- Return type:
str
- static header(text, level=1)[source]
Generate an HTML header element.
- Parameters:
text (str) – The header text content.
level (int, optional) – Header level (1-6). Defaults to 1.
- Returns:
HTML header element string (e.g., ‘<h1>…</h1>’).
- Return type:
str
Example
>>> Html.header("Title", level=1) '<h1>Title</h1>'
- static hr()[source]
Generate a horizontal rule (line break) element.
- Returns:
HTML horizontal rule string.
- Return type:
str
- static img(src, alt_text='Image')[source]
Generate an HTML image element.
- Parameters:
src (str) – The image source URL or path.
alt_text (str, optional) – Alternative text for the image. Defaults to ‘Image’.
- Returns:
HTML image element string.
- Return type:
str
- static link(href, text, class_name=None)[source]
Generate an HTML anchor (link) element.
- Parameters:
href (str) – The link URL.
text (str) – The link text displayed to the user.
class_name (str, optional) – CSS class name to apply. Defaults to None.
- Returns:
HTML anchor element string.
- Return type:
str
- static nbsp(count=1)[source]
Generate non-breaking spaces.
- Parameters:
count (int, optional) – Number of non-breaking spaces to generate. Defaults to 1.
- Returns:
HTML non-breaking space entities string.
- Return type:
str
- static ol(items)[source]
Generate an ordered (numbered) HTML list.
- Parameters:
items (list[str]) – List of items to include as list items.
- Returns:
HTML ordered list string with <li> elements.
- Return type:
str
- static p(text, class_name=None)[source]
Generate an HTML paragraph element.
- Parameters:
text (str) – The paragraph text content.
class_name (str, optional) – CSS class name to apply. Defaults to None.
- Returns:
HTML paragraph string.
- Return type:
str
Example
>>> Html.p("Hello world") '<p>Hello world</p>' >>> Html.p("Styled", class_name="intro") '<p class="intro">Styled</p>'
- static pagebreak(id_=1)[source]
Generate a page break element.
Creates a CSS-based page break that works in EPUB readers.
- Parameters:
id (int, optional) – Identifier for the page break (for reference). Defaults to 1.
id_ (int)
- Returns:
HTML div element with page-break styling.
- Return type:
str
- pypublib.init(settings=None, *, log_level=None)[source]
- Parameters:
settings (Dict[str, Any] | None)
log_level (int | None)
- Return type:
Dict[str, Any]
- pypublib.publish_book(book, file_path)[source]
Save the book in EPUB format to the specified file path.
Convenience wrapper around save_book function.
- Parameters:
book (Book) – The Book instance to publish.
file_path (str) – Output file path for the EPUB file.
See also
save_book()for the actual implementation.
- pypublib.read_book(file_path)[source]
Read an EPUB file and return a Book instance.
Validates the file path and EPUB structure before parsing. Returns None if the file cannot be read or parsed.
- Parameters:
file_path (str) – Path to the EPUB file to read.
- Returns:
A Book instance if successful, None if an error occurs.
- Return type:
Book | None
- Raises:
Catches and logs the following exceptions –
FileNotFoundError: File does not exist - zipfile.BadZipFile: Invalid EPUB container - UnicodeDecodeError: Encoding errors in EPUB content - KeyError: Missing required EPUB data - PermissionError: File permission issues
Example
>>> book = read_book("my_book.epub") >>> if book: ... print(f"Loaded: {book.title}")
Submodules
- pypublib.book module
BookBook.metadataBook.chaptersBook.stylesBook.imagesBook.fontsBook.guideBook.coverBook.__repr__()Book.add_chapter()Book.add_chapters()Book.add_cover()Book.add_font()Book.add_image()Book.add_image_from_file()Book.add_images()Book.add_metadata()Book.add_style()Book.add_style_from_file()Book.add_styles()Book.authorBook.cover_imageBook.creatorBook.dateBook.descriptionBook.from_contents()Book.get_chapter()Book.identifierBook.languageBook.manifestBook.navBook.ncxBook.opfBook.publisherBook.remove_chapter()Book.seriesBook.set_cover()Book.set_metadata()Book.subjectBook.titleBook.toc
Opf
- pypublib.chapter module
- pypublib.edit module
- pypublib.epub module
- pypublib.markdown module