使用ebooklib创建嵌套章节层级EPUB的方法及问题解决
使用ebooklib创建嵌套章节层级EPUB的方法及问题解决
嘿,我来帮你搞定用ebooklib做嵌套章节EPUB时遇到的这几个问题!先梳理下你当前代码里的核心问题,再一步步调整到符合你需求的状态。
你的三个问题其实都和内容的组织逻辑有关:
- 用
epub.Section做TOC分组,但它本身没有对应的可跳转内容文件,所以点击会报「目标不存在」; - 把前言(preamble)单独做成了一个
epub.EpubHtml,导致它变成了独立章节; - 每个子章节都单独用
epub.EpubHtml,所以强制产生了不必要的分页。
核心解决方案思路
把同一个Section下的所有内容(标题、前言、子章节)整合到同一个HTML文件里,然后通过锚点链接实现TOC的嵌套层级,这样既解决了跳转问题,又能让同Section内的内容连续显示,只有不同Section之间才分页。
修改后的完整代码
# /// script # dependencies = [ # "ebooklib" # ] # /// from ebooklib import epub def create_epub(): book = epub.EpubBook() book.set_title("Minimal EPUB Example") book.set_language("en") book.add_author("Author Name") # Section 1:整合标题、前言、子章节到同一个HTML文件 section1_content = """ <h1 id="section1">Section 1</h1> <p>Here is some preamble about what is going to happen in Chapter 1</p> <h2 id="chapter1">Chapter 1</h2> <p>This is the contents of Section 1, Chapter 1.</p> <h2 id="chapter2">Chapter 2</h2> <p>This is the contents of Section 1, Chapter 2.</p> """ section1 = epub.EpubHtml( title="Section 1", file_name="section1.xhtml", content=section1_content, ) # Section 2:同理整合所有内容 section2_content = """ <h1 id="section2">Section 2</h1> <p>Preamble for section 2.</p> <h2 id="section2-chapter1">Chapter 1</h2> <p>Section 2, Chapter 1.</p> """ section2 = epub.EpubHtml( title="Section 2", file_name="section2.xhtml", content=section2_content, ) # 将整合后的Section添加到书籍 book.add_item(section1) book.add_item(section2) # 定义嵌套TOC:Section作为父分组,子项是指向对应锚点的可跳转链接 book.toc = ( (epub.Section("Section 1"), [ epub.Link("section1.xhtml", "Section 1", "#section1"), epub.Link("section1.xhtml", "Chapter 1", "#chapter1"), epub.Link("section1.xhtml", "Chapter 2", "#chapter2"), ]), (epub.Section("Section 2"), [ epub.Link("section2.xhtml", "Section 2", "#section2"), epub.Link("section2.xhtml", "Chapter 1", "#section2-chapter1"), ]), ) # 书脊配置:每个Section对应一个页面,不同Section间分页,同Section内内容连续 book.spine = ["nav", section1, section2] # 添加必要的导航文件 book.add_item(epub.EpubNcx()) book.add_item(epub.EpubNav()) # 生成EPUB文件 epub.write_epub("minimal_epub.epub", book, {}) print("EPUB created: minimal_epub.epub") if __name__ == "__main__": create_epub()
关键改动说明
- 解决Section链接报错:现在所有TOC可点击项都是
epub.Link,指向真实存在的HTML文件和内部锚点(比如#section1),点击时能准确定位到对应内容; - 合并前言与子章节:同一个Section的标题、前言、子章节都放在一个HTML文件里,前言不再是独立章节,而是Section开头的内容,后面直接跟子章节,完全符合你想要的排版;
- 消除不必要的分页:每个Section对应一个
epub.EpubHtml,所以只有不同Section之间会自动分页,同Section内的所有内容都是连续显示的。
如果希望Section本身也能直接点击跳转,还可以把父项的epub.Section换成epub.Link,比如:
book.toc = ( (epub.Link("section1.xhtml", "Section 1", "#section1"), [ epub.Link("section1.xhtml", "Chapter 1", "#chapter1"), epub.Link("section1.xhtml", "Chapter 2", "#chapter2"), ]), (epub.Link("section2.xhtml", "Section 2", "#section2"), [ epub.Link("section2.xhtml", "Chapter 1", "#section2-chapter1"), ]), )
这样父级的Section标题也能直接跳转到对应页面的开头,体验更流畅。
测试一下这个代码生成的EPUB,应该能完美解决你遇到的三个问题!
备注:内容来源于stack exchange,提问作者Paul
相关产品推荐
相关产品推荐

