[Python] Creating epub file with cover in python

Discussão em 'Python' iniciado por Stack, Abril 17, 2025.

  1. Stack

    Stack Membro Participativo

    I`m trying to create an epub file in python.The table of content and the content including images of the epub file are both fine, only the cover is not showing up.

    It seems there is an issue with the cover function of the library and there is a workaround :

    https://github.com/aerkalov/ebooklib/issues/198

    Unfortunately, this workaround is not working for me. Does anyone know how to fix this issue?

    import ebooklib
    from ebooklib import epub
    import os
    import re
    from pathlib import Path

    IMAGES_DIR = 'Images'
    STYLES_DIR = 'Styles'
    FONTS_DIR = 'Fonts'
    DOCUMENTS_DIR = 'Text'
    DEFAULT_LANG = 'en'
    DEFAULT_DIRECTION = 'ltr'
    COVER_UID = 'CoverPage_html'
    COVER_TITLE = 'Cover'
    COVER_FILE_NAME = 'cover.xhtml'
    IMAGE_UID = 'cover'
    COVER_XML = """
    <?xml version="1.0" encoding="UTF-8" standalone="no"?>
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <title>%(book_title)s</title>
    </head>
    <body id="template" xml:lang="%(language)s" style="margin:0px; text-align: center; vertical-align: middle; background-color:#fff;">
    <div>
    <img src="%(cover_path)s" style="height:100%%; text-align:center"/>
    </div>
    </body>
    </html>
    """

    def add_cover(epub_book, cover_file_path, IMAGE_FILE_NAME,language='en', cover_title='volume-cover',):
    cover_path = '../{}/{}'.format(IMAGES_DIR, IMAGE_FILE_NAME)
    cover_data = {
    'book_title': epub_book.title,
    'language': language,
    'cover_path': cover_path
    }
    item = epub.EpubHtml(
    uid=COVER_UID,
    title=cover_title,
    file_name='{}/{}'.format(DOCUMENTS_DIR, COVER_FILE_NAME),
    content=COVER_XML % cover_data
    )

    epub_book.add_item(item)
    epub_book.spine.insert(0, item)

    #epub_book.guide.insert(0, {
    # 'type': 'cover',
    # 'href': '{}/{}'.format(DOCUMENTS_DIR, COVER_FILE_NAME),
    # 'title': item.title,
    #})

    image_file = open(cover_file_path, 'rb')

    image = epub.EpubCover()
    image.id = IMAGE_UID
    image.file_name = '{}/{}'.format(IMAGES_DIR, IMAGE_FILE_NAME)
    image.set_content(image_file.read())

    epub_book.add_item(image)

    image_file.close()

    epub_book.add_metadata(
    None, 'meta', '', {
    'name': 'cover',
    'content': IMAGE_UID
    }
    )

    def MakeVolumeEpub(volume_dir,volume_name):
    book = epub.EpubBook()
    # Set metadata
    book.set_title('My Story - ' + volume_name)
    book.set_language('en')

    toc_list = []
    chapter_list = []

    cover_path = os.path.join(volume_dir,IMAGES_DIR, 'cover.jpg')
    cover_content_type = "image/jpeg"
    cover_name='cover.jpg'

    if not Path(cover_path).is_file():
    cover_name='cover.jpeg'
    cover_path = os.path.join(volume_dir,IMAGES_DIR, cover_name)

    if not Path(cover_path).is_file():
    cover_name='cover.png'
    cover_content_type = "image/png"
    cover_path = os.path.join(volume_dir,IMAGES_DIR, cover_name)



    # Add text content
    for item in os.listdir(volume_dir):
    item_path = os.path.join(volume_dir, item)
    if os.path.isdir(item_path) and item.startswith('Chapter '):
    temp_file_chapter_name = DOCUMENTS_DIR + '/' + item.lower().replace(" ", "-") + '.xhtml'
    chapter_sub_folder = item.lower().replace(" ", "-")
    chapter_content_path = os.path.join(item_path, 'content.txt')
    with open(chapter_content_path, 'r', encoding='utf8') as file:
    firstLinePosition = file.tell()
    chapter_title = file.readline()
    file.seek(firstLinePosition)
    chapter_title = re.sub(r'<.*?>', '', chapter_title).strip()
    chapter = epub.EpubHtml(title=chapter_title, file_name=temp_file_chapter_name, content=file.read())
    book.add_item(chapter)
    chapter_list.append(chapter)
    toc_list.append(epub.Link(chapter.file_name, chapter.title, chapter.id))

    #Add images
    images_directory = os.path.join(volume_dir,IMAGES_DIR)
    if os.path.exists(images_directory):
    image_files = [f for f in os.listdir(images_directory) if f.lower().endswith(('.jpg', '.jpeg', '.png', '.gif'))]
    for idx, image_filename in enumerate(image_files, start=1):
    if image_filename.startswith("cover"):
    continue
    image_path = os.path.join(images_directory, image_filename)
    with open(image_path, 'rb') as img_file:
    # Create an EpubItem for the image
    image_item = epub.EpubItem(
    uid=f'{chapter_sub_folder}-image{idx}', # Unique ID for the image
    file_name=f'{IMAGES_DIR}/{image_filename}', # Path inside the EPUB
    media_type='image/jpeg' if image_filename.lower().endswith('.jpg') or image_filename.lower().endswith('.jpeg') else 'image/png', # MIME type
    content=img_file.read() # Content of the image
    )
    book.add_item(image_item)

    book.toc = tuple(toc_list)
    #book.add_item(epub.EpubNcx())
    book.add_item(epub.EpubNav())
    book.spine = ['nav'] + chapter_list

    if Path(cover_path).is_file():
    add_cover(book,cover_path,cover_name)

    print('Creating ' + volume_name)
    epub.write_epub(os.path.join('C:\\Users\\UserName\\Desktop\\Novels','My Story - ' + volume_name + '.epub'), book, None)

    Continue reading...

Compartilhe esta Página