使用 ebooklib 时如何更改封面文件中的 html?

Posted

技术标签:

【中文标题】使用 ebooklib 时如何更改封面文件中的 html?【英文标题】:How do I change the html in the cover file when using ebooklib? 【发布时间】:2021-07-04 19:16:09 【问题描述】:

我面临的问题是我不喜欢 ebooklib 为我的封面制作的 html 文件。本来想用svg标签等,其他Ebooklib项目,设置内容就是怎么改html,见教程。

在我的代码中,我尝试

book = epub.EpubBook()
book.set_cover(cover_image, open(cover_image, 'rb').read())
cover_page = book.get_item_with_id('cover')
cover_page.content = some_html

但是以这种方式更改内容似乎对封面没有任何作用。

【问题讨论】:

【参考方案1】:

来自https://github.com/aerkalov/ebooklib/blob/master/ebooklib/epub.py,ebooklib 的 EpubCoverHtml 在它的 get_content 方法中设置内容,但它似乎没有使用它,而且似乎没有办法编辑内容,因为它总是在这个方法中重新生成。

def get_content(self):
        """
        Returns content for cover page as HTML string. Content will be of type 'str' (Python 2) or 'bytes' (Python 3).
        :Returns:
          Returns content of this document.
        """

        self.content = self.book.get_template('cover')

        tree = parse_string(super(EpubCoverHtml, self).get_content())
        tree_root = tree.getroot()

        images = tree_root.xpath('//xhtml:img', namespaces='xhtml': NAMESPACES['XHTML'])

        images[0].set('src', self.image_name)
        images[0].set('alt', self.title)

        tree_str = etree.tostring(tree, pretty_print=True, encoding='utf-8', xml_declaration=True)

        return tree_str

要实际修改封面 html 的外观,您似乎必须修改模板:

cover_template = six.b('''<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:epub="http://www.idpf.org/2007/ops" lang="en" xml:lang="en">
 <head>
  <style>
    body  margin: 0em; padding: 0em; 
    img  max-width: 100%; max-height: 100%; 
  </style>
 </head>
 <body>
   <img src=""  />
 </body>
</html>''')
book.set_template(name='cover', value=cover_template)

注意:这实际上是默认模板。

【讨论】:

以上是关于使用 ebooklib 时如何更改封面文件中的 html?的主要内容,如果未能解决你的问题,请参考以下文章

制作PDF时如何替换Sphinx封面

歌曲更改时如何更新 MPMusicPlayerController

通过python的ebooklib修改epub文件,但是<head>里面的所有内容都丢失了

Facebook时间线封面照片iphone

如何在音频文件中添加艺术品,以显示在专辑封面中?

TagLib - 从 MP3 中提取专辑封面 (Powershell)