Python fpdf 没有给出正确的输出
使用 fpdf 模块时,问题在于使用特殊字符,例如“ć,č,š,đ,ž...
我尝试了这样的简单代码:
from fpdf import FPDF
pdf = FPDF()
pdf.add_page()
pdf.set_font("Arial", size=15)
f = open("data.txt", "r")
for x in f:
pdf.cell(200, 10, txt=x, ln=1, align='C')
pdf.output("mytestdata.pdf")
引发的错误是:UnicodeEncodeError:'latin-1'编解码器可以' t 对位置 77 处的字符 '\u2021' 进行编码:序数不在范围(256)
当我使用 with open
读取文本文件并使用 decode
对其进行解码时latin-1
,输出错误。
with open("data.txt", 'rb') as fh:
txt = fh.read().decode('latin-1')
字母与特殊符号混合在一起。但这是不引发 UnicodeEncodeError
的唯一方法。
data.txt
的内容:
test1: Čč
test2: Ćć
test3: Žž
test4: Đđ
test5: Šš
When using fpdf module, problem is with usage of special characters like 'ć,č,š,đ,ž...
I tried simple code like this:
from fpdf import FPDF
pdf = FPDF()
pdf.add_page()
pdf.set_font("Arial", size=15)
f = open("data.txt", "r")
for x in f:
pdf.cell(200, 10, txt=x, ln=1, align='C')
pdf.output("mytestdata.pdf")
Error raised was: UnicodeEncodeError: 'latin-1' codec can't encode character '\u2021' in position 77: ordinal not in range(256)
When im using with open
to read text file and decode
it with latin-1
, output is wrong.
with open("data.txt", 'rb') as fh:
txt = fh.read().decode('latin-1')
Letters are mixed with special simbols. But it is the only way where UnicodeEncodeError
is not raised.
Content of data.txt
:
test1: Čč
test2: Ćć
test3: Žž
test4: Đđ
test5: Šš
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
添加对 Unicode 字体的支持,并确保以保存的编码读取文件。还要从从文件读取的行中删除尾随换行符,因为它也会出错。
结果:
Add support for a Unicode font and make sure to read the file in the encoding it was saved in. Also strip the trailing newlines from the lines read from the file as it made errors as well.
Result: