Python3中FPDF库出现'latin-1'编码错误的修复方案及TXT转PDF的替代实现方法
先看你遇到的错误回溯:
Traceback (most recent call last):
File "C:\demo\test.py", line 11, in
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字体无关,问题出在你用的旧版fpdf(即fpdf1)默认采用latin-1编码,而你的文本里包含’(对应Unicode字符\u2019,也就是弯单引号)这种超出latin-1字符范围的特殊字符,导致编码失败。
修复方案一:升级到fpdf2(推荐)
fpdf2是旧fpdf的官方升级版本,原生支持UTF-8编码,能完美处理各种特殊字符,用法和旧版几乎一致,改几行代码就能解决问题:
- 先安装fpdf2:
pip install fpdf2
- 修改你的代码:
from fpdf import FPDF # 注意导入写法和旧版略有区别 pdf = FPDF(format='letter') txt = 'bees and butterflies. I’m not picky. Once they get chatty, they’re fair' pdf.add_page() # 使用fpdf2内置的支持UTF-8的字体(第一次运行会自动下载) pdf.set_font("DejaVuSans", size=12) pdf.multi_cell(0, 5, txt, 0, 'R') pdf.ln() pdf.cell(0, 5, 'End') pdf.output("splintered.pdf")
如果你想用系统里的Arial Unicode MS字体,也可以替换set_font的参数,但内置的DejaVuSans更省心,不需要额外配置。
修复方案二:临时处理特殊字符(不推荐)
如果非要继续用旧版fpdf,你可以手动替换文本里的特殊字符,比如把’换成普通单引号':
txt = 'bees and butterflies. I’m not picky. Once they get chatty, they’re fair'.replace('’', "'")
但这种方法治标不治本,遇到其他特殊字符(比如中文、其他语种字符)还是会报错,所以只适合临时应急。
更简便的TXT转PDF方法
如果你的需求只是单纯把TXT文件转成PDF,推荐用pdfkit,它基于wkhtmltopdf工具,能一键完成转换,代码超简洁:
- 安装依赖:
pip install pdfkit # 还需要安装wkhtmltopdf: # Windows:去官网下载安装包,配置环境变量 # Linux:sudo apt-get install wkhtmltopdf # Mac:brew install wkhtmltopdf
- 转换代码:
import pdfkit # 直接将TXT文件转为PDF pdfkit.from_file("你的输入文件.txt", "输出文件.pdf")
这个方法不需要手动处理排版、字体,适合快速实现需求。
内容的提问来源于stack exchange,提问作者Silver Wolf2r




