我无法使用PyFPDF输出超文本标记语言消息。当我尝试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。有什么见解吗?谢谢!
发布于 2021-04-02 04:15:09
这似乎是PyFPDF中的一个错误。在内部,write_html方法试图通过调用Python的HTMLParser类的子类的unescape方法来转义HTML,而不是像它应该的那样简单地调用html.unescape。
PyFPDF已经六年没有更新了,现在是no longer actively maintained。我推荐尝试一下它的现代分支和后继者,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,因为它们使用相同的模块名。
https://stackoverflow.com/questions/66910951
复制相似问题