python-3.xebooklib

Adding stylesheet to epub created with ebooklib Python 3


I have a Python project where I create epub files dynamically. For this I use the ebooklib library. I am trying to add a background image to each page as a form of watermark. Following the instructions on http://docs.sourcefabric.org/projects/ebooklib/en/latest/tutorial.html#creating-epub for adding a stylesheet I write the code

style = 'body { background-image: url(../watermark.png); background-repeat: no-repeat; background-attachment: fixed; }'
nav_css = epub.EpubItem(uid="style_nav",
                        file_name="style/nav.css",
                        media_type="text/css",
                        content=style)
book.add_item(nav_css)

The image doesn't get added. I thought maybe the path wasn't correct, so I changed it to

style = 'body { color: red; }'
nav_css = epub.EpubItem(uid="style_nav",
                        file_name="style/nav.css",
                        media_type="text/css",
                        content=style)
book.add_item(nav_css)

adding red color to the text, so I could see if adding the stylesheet worked. It didn't. When I opened the book in calibri the text was still black throughout. I tried adding nav_css to each chapter, still the same. What am I doing wrong?

Edit: I just want to add that I clicked "Edit" the book in calibri, and the nav.css file does get included. But I'm not seeing any change in style.


Solution

  • After opening the epub in Edit mode in calibri and taking a look at the epub's parts, I finally figured out what was wrong. Turns out I needed to add the nav_css stylesheet to both the book as a whole and each individual chapter where I wanted the style to be applied. I also needed to add the image used as a background-watermark to the book:

    image_content = open('../watermark.png', 'rb').read()
    epub_img = epub.EpubImage(uid='watermark', file_name='watermark.png', content=image_content)
    book.add_item(epub_img)
    

    Finally, I'm adding this last as it may help someone else, it seems calibri has a universal setting somewhere to display text as black by default. Even when I applied the style correctly, I didn't get to see the entire text as red (I did, however, see the background image). It was only when I opened the epub in Edit mode that I could see the red text in the preview.