Skip to content

Instantly share code, notes, and snippets.

@bitsgalore
Created March 15, 2016 16:57
Show Gist options
  • Save bitsgalore/4c830a301f33f584c041 to your computer and use it in GitHub Desktop.
Save bitsgalore/4c830a301f33f584c041 to your computer and use it in GitHub Desktop.
Create EPUB 3 from html5 file using ebooklib library
# coding=utf-8
## Demo: create EPUB 3 file from input html file
## Adapted from ebooklib basic_create sample
import codecs
from ebooklib import epub
if __name__ == '__main__':
book = epub.EpubBook()
# add metadata
book.set_identifier('test123456')
book.set_title('Sample book KB')
book.set_language('nl')
book.add_author('Mental Theo')
# all text from html file
# NOTE: must be HTML 5!
# If necessary use pandoc to convert to html5:
# pandoc -t html5 test.htm -o test5.html
f = codecs.open('test5.html', encoding='utf-8')
text = f.read()
f.close()
c1 = epub.EpubHtml(title='Hoofdstuk 1', file_name='hoofdstuk_1.xhtml', lang='en')
c1.content= text
# add chapters to the book
book.add_item(c1)
# create table of contents
book.toc = (c1,)
# add navigation files
book.add_item(epub.EpubNcx())
book.add_item(epub.EpubNav())
# define css style
style = '''
@namespace epub "http://www.idpf.org/2007/ops";
body {
font-family: Cambria, Liberation Serif, Bitstream Vera Serif, Georgia, Times, Times New Roman, serif;
}
h2 {
text-align: left;
text-transform: uppercase;
font-weight: 200;
}
ol {
list-style-type: none;
}
ol > li:first-child {
margin-top: 0.3em;
}
nav[epub|type~='toc'] > ol > li > ol {
list-style-type:square;
}
nav[epub|type~='toc'] > ol > li > ol > li {
margin-top: 0.3em;
}
'''
# add css file
nav_css = epub.EpubItem(uid="style_nav", file_name="style/nav.css", media_type="text/css", content=style)
book.add_item(nav_css)
# create spine
book.spine = ['nav', c1]
# create epub file
epub.write_epub('testKB.epub', book, {})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment