wkhtmltox无法处理HTML文档中的mathjax数学公式

问题描述

使用 wkhtmltox 转换带有 mathjax 的 HTML 网页文件,发现网页中的数学公式在 Chromium 浏览器中能正常显示,而在转换得到的 PDF 文档中无法显示。

我使用的转换命令是:

wkhtmltopdf test.html out.pdf

生成的 PDF 文档与原 HTML 文档对比如图:

请问怎样才能让 wkhtmltopdf 正确处理 HTML 文档中的 mathjax 数学公式,使其可以在生成的 PDF 文档中正常显示?

相关信息

$ wkhtmltopdf --debug-javascript test.html out.pdf
Loading pages (1/6)
Warning: file:///home/user/test.html:11 SyntaxError: Parse error
Warning: https://gcore.jsdelivr.net/npm/mathjax@3/es5/tex-chtml.js:1 SyntaxError: Parse error
Counting pages (2/6)
Resolving links (4/6)                                                       
Loading headers and footers (5/6)                                           
Printing pages (6/6)
Done
  • 输入的 HTML 文档内容:
<!doctype html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>测试</title>
<script>
MathJax = {
  options: {
    renderActions: {
      find: [10, function (doc) {
        for (const node of document.querySelectorAll('script[type^="math/tex"]')) {
          const display = !!node.type.match(/; *mode=display/);
          const math = new doc.options.MathItem(node.textContent, doc.inputJax[0], display);
          const text = document.createTextNode('');
          node.parentNode.replaceChild(text, node);
          math.start = {node: text, delim: '', n: 0};
          math.end = {node: text, delim: '', n: 0};
          doc.math.push(math);
        }
      }, '']
    }
  }
};
</script>
<script type="text/javascript" src="https://gcore.jsdelivr.net/npm/mathjax@3/es5/tex-chtml.js" async></script></head>
<body>
<h3 id="_1">测试</h3>
<p>
<script type="math/tex; mode=display">
e^x
</script>
</p>

</body>
</html>

感觉像是没有正确传导公式字体给 wkhtmltopdf 造成的公式显示不了,你用 css 定义个公式字体试试

非常感谢大家的回复!刚才找到了一个比较 “歪门邪道” 的解决方法:用知乎的API将 LaTeX 公式转换成图片。这样生成的PDF中公式就可以正常显示了。

具体操作是,对原 HTML 文档的代码进行修改,要显示公式的地方不使用 JS 脚本,而是使用下面的代码:

<img alt="" src="https://www.zhihu.com/equation?tex=公式代码">

参考资料:


根据网上的一些说法,wkhtmltox 无法处理mathjax公式,可能是因为wkhtmltox使用的渲染引擎版本较低,不支持较新版本的mathjax,因而造成公式无法显示。

非常感谢您的建议!我经过尝试,问题已经解决。具体方法是:

首先,在网页的CSS样式表中加入显示公式所需的字体。

之前的CSS内容(片段)是:

body {
    margin: 0 auto;
    font-family: "更纱黑体 UI SC", "Apple Color Emoji";
    color: #34495E;
    line-height: 1.5;
    padding: 16px;
    background-color: #ffffff;
    font-size: 16px;
}

修改后,加入字体 "MathJax_Math", "MathJax_Main", "MathJax_Size1", "MathJax_Size2"

body {
    margin: 0 auto;
    font-family: "更纱黑体 UI SC", "Apple Color Emoji", "Segoe UI Emoji", "MathJax_Math", "MathJax_Main", "MathJax_Size1", "MathJax_Size2";
    color: #34495E;
    line-height: 1.5;
    padding: 16px;
    background-color: #ffffff;
    font-size: 16px;
}

然后,调整 wkhtmltopdf 转换文档时的参数,增加 JavaScript 脚本加载的等待时间,待公式渲染完成后再进行转换。

修改后的转换命令是:

wkhtmltopdf --javascript-delay 5000 test.html out.pdf