Python3 HTML转PDF

3
如何在Python3中将HTML转换为PDF?
Xhtml2pdf不能在Python3中工作,会出现错误:
import xhtml2pdf.pisa as pisa Traceback (most recent call last): File "", line 1, in File "/home/hound/test/python/test_env/lib/python3.4/site-packages/xhtml2pdf/init.py", line 41, in from xhtml2pdf.util import REPORTLAB22 File "/home/hound/test/python/test_env/lib/python3.4/site-packages/xhtml2pdf/util.py", line 302 raise Exception, "box not defined right way" ^ SyntaxError: invalid syntax
2个回答

4
到目前为止,我发现最好的选择是weasyprint
根据文档from weasyprint import HTML HTML('http://weasyprint.org/').write_pdf('/tmp/weasyprint-website.pdf') 它真的很容易使用。在我浪费时间尝试在Python 3中让xhtml2pdf和其他工具工作失败后,这个工具节省了我大量时间。

2
关于WeasyPrint的快速笔记:我在表格单元格中遇到了长字符串重叠的问题。找不到正确的CSS属性将其设置为换行而不是截断。结果正确的答案是overflow-wrap: break-word;,还需要设置width: x; - deusofnull

3

我曾经也遇到过同样的错误。目前,xhtml2pdf只在其预发行版本(0.2b1)中支持Python3 (更多信息请参见https://pypi.python.org/pypi/xhtml2pdf)。我通过卸载之前的xhtml2pdf版本并安装预发布版本来解决了这个问题。

pip install --pre xhtml2pdf

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接