使用 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' codec can't encode character '\u2021' in position 77: ordinal not in range(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: ??
uj5u.com熱心網友回復:
添加對 Unicode 字體的支持,并確保以保存檔案的編碼讀取檔案。還要從檔案讀取的行中去除尾隨換行符,因為它也會出錯。
from fpdf import FPDF
pdf = FPDF()
pdf.add_page()
pdf.add_font('Arial', '', 'c:/windows/fonts/arial.ttf', uni=True) # added line
pdf.set_font('Arial', size=15)
with open("data.txt", encoding='utf8') as f:
for x in f:
pdf.cell(200, 10, txt=x.strip(), ln=1, align='C')
pdf.output("mytestdata.pdf")
結果:

轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/436449.html
標籤:Python python-3.x pdf 统一码 pyfpdf
