首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >PyFPDF、HTMLMixin、Python无法打印超文本标记语言

PyFPDF、HTMLMixin、Python无法打印超文本标记语言
EN

Stack Overflow用户
提问于 2021-04-02 04:09:12
回答 1查看 679关注 0票数 2

我无法使用PyFPDF输出超文本标记语言消息。当我尝试write the HTML to the PDF document时,我得到一个错误:

代码语言:javascript
复制
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'

有问题的代码:

代码语言:javascript
复制
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。有什么见解吗?谢谢!

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 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似乎运行正常:

代码语言:javascript
复制
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,因为它们使用相同的模块名。

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66910951

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档