PyMuPDF
| Language | Python 3.11+ |
|---|---|
| License | AGPL-3.0 or commercial license from Artifex |
| Repository | github.com/pymupdf/PyMuPDF |
| Documentation | pymupdf.readthedocs.io |
| Depends on | MuPDF (bundled in the wheels) |
| Read / write | yes / 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#
pip install pymupdf
Basic usage: open an EPUB and extract text#
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):
for level, title, page in doc.get_toc():
print(" " * (level - 1) + f"{title} ... {page}")
How to convert EPUB to PDF#
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#
doc = pymupdf.open("book.epub")
pix = doc[0].get_pixmap(dpi=150)
pix.save("cover.png")
How to search for text in an EPUB#
for page in doc:
for rect in page.search_for("Cheshire"):
print(f"page {page.number + 1}: {rect}")
Tips#
- Accessing a page by absolute number lays out the book up to that page; for large books, load pages by
(chapter, page)withdoc.load_page((chapter, pno)), which is faster. - Page numbers change after
layout(). Usedoc.make_bookmark((chapter, pno))before anddoc.find_bookmark(bm)after to keep the reader’s position. pymupdf.open(stream=data, filetype="epub")opens an EPUB from bytes in memory.