在FPDF2中写入网址时出现字符编码错误

时间:2019-03-27 15:17:33

标签: python python-3.x pdf unicode

我正在使用Python 3.7,并且正在运行FPDF 2.0.3(https://pypi.org/project/fpdf2/)的python端口。我正在处理许多unicode符号,其中一些需要成为URL的一部分。我可以毫无问题地将它们写为文本,但是当Unicode符号成为我的URL的一部分时,我总是收到错误消息。

试图使用html.escape(str)进行转义,但这没有用 使用write_html(html_as_str)重写了代码,这也不起作用

这是工作代码:

add = "Chronique d‘Égypte (CdE)" ##this is actually pulled in from a MYSQL query using PYMYSQL
from fpdf import FPDF
pdf = FPDF('P', 'mm', 'A4')
pdf.add_page()
pdf.add_font('base', '', r'C:\Fonts\DejaVuSans.ttf', uni=True)
pdf.set_font('base', '',12)
pdf.write(5, add)
pdf.output("goodfile.pdf", "F")

使用此脚本,我可以打印出字符串。但是,我希望将字符串打印出来并成为这样的url的一部分:

add = "Chronique d‘Égypte (CdE)" ##this is actually pulled in from a MYSQL query using PYMYSQL
from fpdf import FPDF
pdf = FPDF('P', 'mm', 'A4')
pdf.add_page()
pdf.add_font('base', '', r'C:\Fonts\DejaVuSans.ttf', uni=True)
pdf.set_font('base', '',12)
pdf.write(5, add, 'https://www.example.org/index.php?searchterm='+add)
pdf.output("goodfile.pdf", "F")

第二个脚本失败,并在控制台中显示以下错误消息:

Traceback (most recent call last):
  File ".\print.py", line 543, in <module>
    pdf.output(Filename+'_CORPUS.pdf', 'F')
  File "C:\Users\me\AppData\Local\Programs\Python\Python37\lib\site-packages\fpdf\fpdf.py", line 1239, in output
    buffer = self.buffer.encode("latin1")
UnicodeEncodeError: 'latin-1' codec can't encode character '\u2018' in position 1587960: ordinal not in range(256)

错误消息本身非常令人困惑,因为添加导致错误的字符串的部分发生在第470行附近。而回溯仅提及第543行。

我希望输出是我pdf中的可单击链接,打开默认浏览器并转到带有PDF中字符的指定URL。我不能用普通引号替换此字符,因为它给了我该网站其他结果(在这种情况下,没有)。

还有,有人可以添加标签FPDF2来帮助对其进行正确分类吗?

0 个答案:

没有答案