gpt4 book ai didi

python - PyFPDF、HTMLMixin、Python 无法打印 HTML

转载 作者:行者123 更新时间:2023-12-05 01:30:40 29 4
gpt4 key购买 nike

我无法使用 PyFPDF 输出 HTML 消息.当我尝试 write the HTML to the PDF document我得到一个错误:

Traceback (most recent call last):
File "/Users/elcid/Projects/so_test/test.py", line 8, in <module>
pdf.write_html("<b>Sample HTML</b>")
File "/Users/elcid/.pyenv/versions/so/lib/python3.9/site-packages/fpdf/html.py", line 400, in write_html
text = h2p.unescape(text) # To deal with HTML entities
AttributeError: 'HTML2FPDF' object has no attribute 'unescape'

违规代码:

from fpdf import FPDF, HTMLMixin

class PDF(FPDF, HTMLMixin):
pass

pdf = PDF()
pdf.add_page()
pdf.write_html("<b>Sample HTML</b>")
pdf.output("html.pdf")

我正在使用 Python 3.9。有什么见解吗?谢谢!

最佳答案

这似乎是 PyFPDF 中的错误。在内部,write_html 方法试图通过调用 Python 的 HTMLParser 类的子类的 unescape 方法来转义 HTML,而不是简单地调用 html.unescape 因为它应该。

PyFPDF 六年没更新了no longer actively maintained .我建议尝试使用它的现代 fork 和继任者 fpdf2 .

example from the documentation似乎运行良好:

from fpdf import FPDF, HTMLMixin

class PDF(FPDF, HTMLMixin):
pass

pdf = PDF()
pdf.add_page()
pdf.write_html("""
<h1>Big title</h1>
<section>
<h2>Section title</h2>
<p><b>Hello</b> world. <u>I am</u> <i>tired</i>.</p>
<p><a href="https://github.com/PyFPDF/fpdf2">PyFPDF/fpdf2 GitHub repo</a></p>
<p align="right">right aligned text</p>
<p>i am a paragraph <br />in two parts.</p>
<font color="#00ff00"><p>hello in green</p></font>
<font size="7"><p>hello small</p></font>
<font face="helvetica"><p>hello helvetica</p></font>
<font face="times"><p>hello times</p></font>
</section>
<section>
<h2>Other section title</h2>
<ul><li>unordered</li><li>list</li><li>items</li></ul>
<ol><li>ordered</li><li>list</li><li>items</li></ol>
<br>
<br>
<pre>i am preformatted text.</pre>
<br>
<blockquote>hello blockquote</blockquote>
<table width="50%">
<thead>
<tr>
<th width="30%">ID</th>
<th width="70%">Name</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Alice</td>
</tr>
<tr>
<td>2</td>
<td>Bob</td>
</tr>
</tbody>
</table>
</section>
""")
pdf.output("html.pdf")

确保卸载 PyFPDF,因为它们使用相同的模块名称。

关于python - PyFPDF、HTMLMixin、Python 无法打印 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66910951/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com