summaryrefslogtreecommitdiff
path: root/app/figments/ebook.py
blob: 81210a455ec5e11464fb01a7fc16d0c001669034 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import os
from ebooklib import epub

from django.conf import settings
from typogrify.filters import typogrify


def generate_epub_file(f):
    book = epub.EpubBook()

    # add metadata
    book.set_identifier('lux23')
    book.set_title(f.title)
    book.set_language('en')

    book.add_author('Scott Gilbertson')

    # intro chapter
    c1 = epub.EpubHtml(title='Introduction', file_name='intro.xhtml', lang='en')
    c1.content = u'<html><head></head><body><h1>Forward</h1><p>Thank you for downloading my story <em>%s</em>. I hope you enjoy it and please feel free to email me if you have any questions or comments.</p> <p>If you enjoy this story and would like to read more, head on over to <a href="https://luxagraf.net/figments/">luxagraf.net</a>.</p><p>&ndash; Scott Gilbertson <br/> &nbsp;&nbsp;sng@luxagraf.net</p></body></html>' % f.title

    # chapter
    c2 = epub.EpubHtml(title=f.title, file_name='story.xhtml')
    c2.content = '<h1>%s</h1>' % f.title
    c2.content += typogrify(f.body_html)

    # add chapters to the book
    book.add_item(c1)
    book.add_item(c2)
    # create table of contents
    # - add section
    # - add auto created links to chapters

    book.toc = (epub.Link('intro.xhtml', 'Introduction', 'intro'),
                epub.Link('story.xhtml', f.title, 'story'),
                )

    # 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: 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, c2]
    path, filename = os.path.split(f.get_absolute_url())
    fpath = '%s%s/' % (settings.FLATFILES_ROOT, path)
    if not os.path.isdir(fpath):
        os.makedirs(fpath)
    bk = '%s%s.epub' % (fpath, f.slug)
    # create epub file
    epub.write_epub(bk, book, {})