aerkalov/ebooklib

Include a font file, or any arbitrary file?

aaannestad opened this issue · 1 comments

What's the proper method to include a font file in a built epub file? The documentation seems to say nothing about including fonts, only about discovering that an item is one via get_type().

Is it possible to simply include arbitrary files in the epub? If it is, I could include the font file very straightforwardly (and have separate css files etc I could simply include into the built epub file).

It is possible. Anything you are going to use in the CSS files (fonts, images, ...) you can add to the book as ebooklib.epub.EpubItem with proper name and media type. This will create correct metadata in the EPUB to embed the files in the EPUB file.

For instance:

                        name = os.path.basename(font_name)
                        extension = os.path.splitext(font_name)[-1].lower()
                        font = ebooklib.epub.EpubItem()
                        font.file_name = "{}/{}".format(FONTS_DIR, name)
                        font.set_content(content)

                        # try to set the right font media type
                        # http://www.idpf.org/epub/301/spec/epub-publications.html#sec-core-media-types
                        if extension in self.OPENTYPE_FONTS:
                            font.media_type = 'application/vnd.ms-opentype'
                        elif extension in self.WOFF_FONTS:
                            font.media_type = 'application/font-woff'

                        epub_book.add_item(font)

And then you need to add CSS to each chapter (ebooklib.epub.EpubHtml). This will create correct tags in the header of the chapter. The best way to do it is maybe write plugin which would do it for you (so you don't have to do it for each file). Check the link bellow and wirterplugins/base_writerplugin.py we used for themes.

Booktype was the software for which the library was developed and you can check here in the method _add_theme_assets how it is done. You can check how the Covers and other stuff is managed. Would be good to add this to the documentation.

https://github.com/booktype/Booktype/blob/master/lib/booktype/convert/epub/converter.py