All formats

PyMuPDF

LanguagePython 3.11+
LicenseAGPL-3.0 or commercial license from Artifex
Repositorygithub.com/pymupdf/PyMuPDF
Documentationpymupdf.readthedocs.io
Depends onMuPDF (bundled in the wheels)
Read / writeyes / no (EPUB 2 and 3, unencrypted)

PyMuPDF is the Python binding of MuPDF. It opens EPUB with the same Document and Page API it uses for PDF: the book is laid out into pages of a size you choose, and every page can be searched, rendered or converted. Pre-built wheels include MuPDF, so pip install is all you need on Windows, macOS and Linux.

Use PyMuPDF to get text or page images out of an EPUB, or to convert it to PDF. It doesn’t give you the EPUB’s internal files (OPF, XHTML) and can’t write EPUB: use EbookLib for that. The AGPL license requires you to publish your source code if you distribute your program or run it as a network service; Artifex sells commercial licenses.

Installation#

Shell
pip install pymupdf

Basic usage: open an EPUB and extract text#

Python
import pymupdf

doc = pymupdf.open("book.epub")
doc.layout(width=420, height=595, fontsize=11)  # A5 page in points, 11pt text

print(doc.metadata["format"], "-", doc.metadata["title"], "by", doc.metadata["author"])
print(doc.page_count, "pages,", doc.chapter_count, "chapters")

with open("book.txt", "w", encoding="utf-8") as out:
    for page in doc:
        out.write(page.get_text())
        out.write("\f")  # form feed between pages
doc.close()

The number of pages depends on the layout: change the page size or font size with layout() and the book is paginated again.

How to read the table of contents of an EPUB#

get_toc() returns [level, title, page_number] entries (page numbers start at 1):

Python
for level, title, page in doc.get_toc():
    print("  " * (level - 1) + f"{title} ... {page}")

How to convert EPUB to PDF#

Python
import pymupdf

doc = pymupdf.open("book.epub")
doc.layout(width=420, height=595, fontsize=11)
pdf_bytes = doc.convert_to_pdf()

pdf = pymupdf.open("pdf", pdf_bytes)
pdf.set_toc(doc.get_toc())  # keep the table of contents as PDF bookmarks
pdf.save("book.pdf", garbage=3, deflate=True)

How to render the cover (first page) to PNG#

Python
doc = pymupdf.open("book.epub")
pix = doc[0].get_pixmap(dpi=150)
pix.save("cover.png")

How to search for text in an EPUB#

Python
for page in doc:
    for rect in page.search_for("Cheshire"):
        print(f"page {page.number + 1}: {rect}")

Tips#