Skip to content

Instantly share code, notes, and snippets.

@Kraballa
Last active January 11, 2022 23:18
Show Gist options
  • Save Kraballa/4766be4bfcd1273a6e5c3d0c89b2ba59 to your computer and use it in GitHub Desktop.
Save Kraballa/4766be4bfcd1273a6e5c3d0c89b2ba59 to your computer and use it in GitHub Desktop.
Provides a class for easy epub file generation. Input files can be regular txt files or more advanced (x)html files. For installation simply get the library 'ebooklib' via pip. Made for Python 3.7.3
from ebooklib import epub
# HOW TO:
# 1. create instance of the class
# 2. set important metadata
# 3. add chapter files and give them a title
# 4. write the finished epub file to disc
class EbookGenerator():
def __init__(self):
self.book = epub.EpubBook()
self.chapter_index = 0
self.book.set_language('en')
def set_metadata(self, title, author, book_id):
self.book.add_author(author)
self.book.set_title(title)
self.book.set_identifier(book_id)
def add_chapter(self, chapter_title, chapter_file):
chapter = epub.EpubHtml(title=chapter_title, file_name='chap' + str(self.chapter_index) + '.xhtml', lang='hr')
# read input file and add it as a single chapter; also append spine and table of contents, so readers can parse order correctly
with open(chapter_file, 'r', encoding='utf-8') as file_content:
text = file_content.readlines()
chapter.content = '<br>'.join(text)
self.book.add_item(chapter)
# Some devices can select an element from the table of contents to start the file at instead of the beginning, atleast that's what I think it is
self.book.toc.append(epub.Link(chapter.file_name, chapter.title,chapter.file_name))
self.book.spine.append(chapter)
self.chapter_index += 1
def write_epub(self):
# add default NCX and Nav file - not sure what they do, the library used has little undocumentation
self.book.add_item(epub.EpubNcx())
self.book.add_item(epub.EpubNav())
# define and add css - dunno enough about css to be able to make anything useful here, left it at default
style = 'BODY {color: white;}'
nav_css = epub.EpubItem(uid="style_nav", file_name="style/nav.css", media_type="text/css", content=style)
self.book.add_item(nav_css)
# compile and output to file
epub.write_epub(self.book.title + '.epub', self.book, {})
if __name__ == '__main__':
ebook = EbookGenerator()
# ebook.set_metadata('TITLE','AUTHOR','')
# ebook.add_chapter("CHAPTER NAME","CHAPTER TEXT FILE")
# ebook.write_epub()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment