Ebooklib
Ebooklib is a Python library designed to handle EPUB2 and EPUB3 format ebooks. It provides functionalities for reading, writing, and manipulating EPUB files, allowing developers to programmatically create or modify ebook content. The library is actively maintained, with its latest version being 0.20 and a regular release cadence.
Warnings
- breaking As of v0.20, `EpubHtml.get_body_content()` now returns bytes instead of a string. Code expecting a string will need to explicitly decode the result.
- gotcha The default behavior for error throwing during EPUB writing (via `write_epub`) might have changed in v0.19. Previously, certain errors might have halted the process, but now they might be suppressed or optional.
- gotcha While Ebooklib officially supports Python 2.7, Python 2 is end-of-life and no longer maintained. Using Ebooklib in new projects should target Python 3.6+ for security, modern features, and better compatibility with the ecosystem.
- gotcha Older versions (particularly `0.16` to `0.18`) had known issues with correctly resolving relative paths within EPUB content (e.g., links to images, CSS files). Incorrect relative paths can lead to broken or improperly rendered EPUBs.
Install
-
pip install ebooklib
Imports
- EpubBook
from ebooklib import epub
- EpubHtml
from ebooklib import epub
- read_epub
from ebooklib import epub
- write_epub
from ebooklib import epub
Quickstart
import ebooklib
from ebooklib import epub
# Create a new book
book = epub.EpubBook()
# Set metadata
book.set_identifier('sample123456')
book.set_title('My Awesome Book')
book.set_language('en')
book.add_author('John Doe')
# Add chapter
c1 = epub.EpubHtml(title='Intro', file_name='chap_01.xhtml', lang='en')
c1.content = '<h1>Introduction</h1><p>This is an introduction.</p>'
# Add a stylesheet (optional)
style = 'body { font-family: Calibri,sans-serif; }'
nav_css = epub.EpubItem(uid="style_nav", file_name="style/nav.css", media_type="text/css", content=style)
book.add_item(nav_css)
book.add_item(c1)
# Define Table Of Contents
book.toc = (epub.Link('chap_01.xhtml', 'Introduction', 'intro'),)
# Add default NCX and Nav file
book.add_item(epub.EpubNcx())
book.add_item(epub.EpubNav())
# Define spine
book.spine = ['nav', c1]
# Write the book
epub.write_epub('my_awesome_book.epub', book, {})
print("Epub book 'my_awesome_book.epub' created successfully!")