Python使用pdfkit生成PDF目录(TOC)报XTSE0010错误问题咨询
报错原因
当前抛出的XTSE0010解析错误直接原因是toc.xsl为空文件,底层依赖的wkhtmltopdf无法读取到有效的XSL样式表结构。
方案1:无需自定义样式的最简实现
如果不需要调整目录的默认样式,完全不需要指定xsl-style-sheet参数,pdfkit自带默认目录生成逻辑,直接传入空字典启用toc功能即可:
pdfkit.from_file( book_html_filename, book_pdf_filename, configuration=config, toc={}, # 传空字典即可启用默认目录 options=options, cover=cover_html_filename, cover_first=True )
默认目录会自动识别HTML中的h1~h6标签生成层级结构,自带页码和跳转链接。
方案2:自定义目录样式(toc.xsl编写规范)
如果需要调整目录的字体、缩进、引导线、标题样式等效果,可使用以下可直接运行的基础XSL模板,根据需求修改样式部分即可:
<?xml version="1.0" encoding="UTF-8"?> <xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:outline="http://wkhtmltopdf.org/outline" xmlns="http://www.w3.org/1999/xhtml"> <xsl:output doctype-public="-//W3C//DTD XHTML 1.0 Strict//EN" doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd" indent="yes" /> <xsl:template match="outline:outline"> <html> <head> <title>目录</title> <style> * { margin: 0; padding: 0; box-sizing: border-box; font-family: "SimSun", serif; } h1 { text-align: center; font-size: 22px; margin: 20px 0 30px 0; } .toc-level { list-style: none; } /* 按需调整不同层级的缩进、字号、间距 */ .toc-level-1 { margin-left: 0; font-size: 16px; margin-bottom: 10px;} .toc-level-2 { margin-left: 2em; font-size: 15px; margin-bottom: 8px;} .toc-level-3 { margin-left: 4em; font-size: 14px; margin-bottom: 6px;} .toc-item { display: flex; justify-content: space-between; width: 100%; } .toc-link { text-decoration: none; color: #000; flex: 1; border-bottom: 1px dotted #ccc; /* 目录引导线样式 */ } .toc-page { text-align: right; min-width: 3em; padding-left: 5px; } </style> </head> <body> <h1>目录</h1> <ul class="toc-level toc-level-1"> <xsl:apply-templates select="outline:item/outline:item"/> </ul> </body> </html> </xsl:template> <xsl:template match="outline:item"> <li> <div class="toc-item"> <a class="toc-link" href="{@link}"> <xsl:value-of select="@title"/> </a> <span class="toc-page"> <xsl:value-of select="@page"/> </span> </div> <xsl:if test="outline:item"> <ul class="toc-level toc-level-{@level + 1}"> <xsl:apply-templates select="outline:item"/> </ul> </xsl:if> </li> </xsl:template> </xsl:stylesheet>
XSL编写注意事项
- 文件开头必须是
<?xml version="1.0" encoding="UTF-8"?>,不能有前置空行、空格等其他内容 - 必须引入
http://wkhtmltopdf.org/outline命名空间,才能正常读取wkhtmltopdf生成的大纲数据,核心可调用属性如下:@title:对应HTML标题标签的文本内容@level:对应标题层级,h1对应level1,h2对应level2,以此类推@page:对应内容所在的PDF页码@link:对应跳转锚点,点击目录可跳转至对应内容页
- 样式调整直接修改
<style>标签内的CSS即可,和普通网页CSS写法完全一致
额外目录配置示例
可在toc参数中添加配置调整目录生成规则:
toc = { 'xsl-style-sheet': 'toc.xsl', 'toc-depth': '3', # 最多显示3级目录 'disable-toc-links': False # 保留目录跳转功能 }
内容的提问来源于stack exchange,提问作者yishaistreamline
相关产品推荐
相关产品推荐

