【问题标题】:How do I change the html in the cover file when using ebooklib?使用 ebooklib 时如何更改封面文件中的 html?
【发布时间】: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

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

【问题讨论】:

    标签: python epub ebooklib


    【解决方案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="" alt="" />
     </body>
    </html>''')
    book.set_template(name='cover', value=cover_template)
    

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

    【讨论】:

      猜你喜欢
      • 2021-12-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-29
      • 2020-10-22
      • 2014-11-07
      • 2018-01-18
      • 2021-09-16
      • 1970-01-01
      相关资源
      最近更新 更多