我正在尝试在 Python 中将文本文件转换为 pdf,但出现错误。为什么会发生这种情况以及如何解决?
这是我的代码:
import fpdf
from fpdf import FPDF
pdf = FPDF()
pdf.add_page()
pdf.set_font("Arial", size=15)
f = open("textfile.txt", "r")
for i in f:
pdf.cell(200, 10, txt=i, ln = 1, align = 'C')
pdf.output("Output.pdf")
输出:错误
p = self.pages[n].encode("latin1") if PY3K else self.pages[n]
UnicodeEncodeError: 'latin-1' codec can't encode character '\u2013' in position 88: ordinal not in range(256)
fpdf使用的所有标准字体latin-1
编码。如果你想写的字符不在latin-1
设置,你需要使用set_font
指定外部字体。
参考:https://pyfpdf.readthedocs.io/en/latest/reference/set_font/index.html
否则你必须将字符串转换为latin-1
(使用encode
方法)并指定是否忽略或替换坏字符(即不存在于latin-1
).
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)