Python3 fpdf 给我一个错误 latin-1 codec can't encode character

Python3 fpdf is giving me an error latin-1 codec can't encode character

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

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

我该如何解决这个问题?是因为我选择了 Arial 作为我的字体选择吗?我想要做的就是将 txt 文件转换为 pdf 文件,所以如果在 Python 中有任何更简单的方法可以做到这一点,我将不胜感激。

import fpdf
pdf = fpdf.FPDF(format='letter')

txt = 'bees and butterflies. I’m not picky. Once they get chatty, they’re fair'

pdf.add_page()
pdf.set_font('Arial', '', 12)
pdf.multi_cell(0, 5, txt,0,'R')
pdf.ln()
pdf.cell(0, 5, 'End')
pdf.output("splintered.pdf")

您需要在 PDF 中添加支持该语言代码点的 Unicode 字体。代码点 U+2019 是右单引号 () 并且不受 Latin-1 编码支持。例如:

import fpdf

pdf = fpdf.FPDF(format='letter')

txt = 'bees and butterflies. I’m not picky. Once they get chatty, they’re fair'

pdf.add_page()
pdf.add_font('Arial', '', 'c:/windows/fonts/arial.ttf', uni=True)  # added line
pdf.set_font('Arial', '', 12)
pdf.multi_cell(0, 5, txt,0,'R')
pdf.ln()
pdf.cell(0, 5, 'End')
pdf.output("splintered.pdf")

输出:

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