Python3 fpdf 给我一个错误 latin-1 编解码器无法编码字符

Sil*_*f2r 1 python pdf utf-8 pyfpdf txt

当我运行下面的代码时,我得到以下回溯:

\n
Traceback (most recent call last):\n  File "C:\\demo\\test.py", line 11, in <module>\n    pdf.output("splintered.pdf")\n  File "C:\\demo\\lib\\site-packages\\fpdf\\fpdf.py", line 1065, in output\n    self.close()\n  File "C:\\demo\\lib\\site-packages\\fpdf\\fpdf.py", line 246, in close\n    self._enddoc()\n  File "C:\\demo\\lib\\site-packages\\fpdf\\fpdf.py", line 1636, in _enddoc\n    self._putpages()\n  File "C:\\demo\\lib\\site-packages\\fpdf\\fpdf.py", line 1170, in _putpages\n    p = self.pages[n].encode("latin1") if PY3K else self.pages[n]\nUnicodeEncodeError: \'latin-1\' codec can\'t encode character \'\\u2019\' in position 74: ordinal not in range(256)\n
Run Code Online (Sandbox Code Playgroud)\n

我该如何解决?是因为我选择了 Arial 作为字体吗?我想做的就是将 txt 转换为 pdf 文件,因此如果有任何更简单的方法可以在 Python 中执行此操作,我将不胜感激。

\n
import fpdf\npdf = fpdf.FPDF(format=\'letter\')\n\ntxt = \'bees and butterflies. I\xe2\x80\x99m not picky. Once they get chatty, they\xe2\x80\x99re fair\'\n\npdf.add_page()\npdf.set_font(\'Arial\', \'\', 12)\npdf.multi_cell(0, 5, txt,0,\'R\')\npdf.ln()\npdf.cell(0, 5, \'End\')\npdf.output("splintered.pdf")\n
Run Code Online (Sandbox Code Playgroud)\n

Mar*_*nen 5

您需要将支持该语言代码点的 Unicode 字体添加到 PDF。代码点 U+2019 是右单引号 ( \xe2\x80\x99),Latin-1 编码不支持。例如:

\n
import fpdf\n\npdf = fpdf.FPDF(format=\'letter\')\n\ntxt = \'bees and butterflies. I\xe2\x80\x99m not picky. Once they get chatty, they\xe2\x80\x99re fair\'\n\npdf.add_page()\npdf.add_font(\'Arial\', \'\', \'c:/windows/fonts/arial.ttf\', uni=True)  # added line\npdf.set_font(\'Arial\', \'\', 12)\npdf.multi_cell(0, 5, txt,0,\'R\')\npdf.ln()\npdf.cell(0, 5, \'End\')\npdf.output("splintered.pdf")\n
Run Code Online (Sandbox Code Playgroud)\n

输出:

\n

正确的 PDF 输出

\n

有关更多语言示例,请参阅https://pyfpdf.readthedocs.io/en/latest/Unicode/index.html

\n