analitics

Pages

Monday, February 27, 2023

Python 3.11.0 : EbookLib python library - part 002.

The last version 3.3 of this file type was published by the EPUB 3 Working Group as a Candidate Recommendation Snapshot on 21 February 2023 ...
I haven't written about the ePub format and python since 2022 because I was busy with all kinds of tasks.
Then I presented a short introduction with some examples on how to create an ePUB file, see that tutorial article.
I like this file type, especially the last format that allows many features, including inserting SVG vector files.
Installing the package is easy on a windows 10 with the pip utility.
pip install ebooklib --user
In the folder with the svg image named cover.svg I created a python file with this content.
from ebooklib import epub

# Create a new EPUB book
book = epub.EpubBook()

# Set the book metadata
book.set_title('My EPUB Book')
book.set_language('en')

# Add a cover image
cover_svg = epub.EpubItem(uid="cover_svg", file_name="cover.svg", media_type="image/svg+xml", content=open("cover.svg").read())
book.add_item(cover_svg)

# Create a new chapter for the cover page
cover_page = epub.EpubHtml(title='Cover Page', file_name='cover.xhtml', lang='en')
cover_page.content = '<img alt="Cover Image" src="cover.svg" />'

# Add the cover page to the book
book.add_item(cover_page)

# Add a chapter to the book
chapter1 = epub.EpubHtml(title='Chapter 1', file_name='chap_1.xhtml', lang='en')
chapter1.content = '<h1>Chapter 1</h1><p>This is the first chapter of my book.</p>'

# Add the chapter to the book
book.add_item(chapter1)

# Create the spine
book.spine = [cover_page, chapter1]

# Generate the EPUB file
epub.write_epub('my_book.epub', book, {})
after running the script this was the result a epub file named my_book.epub.
The result is this simple epub with an SVG file from Wikipedia, see the screenshot take with the Sumatra PDF free software.