當我運行下面的代碼時,我得到以下回溯:
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")
uj5u.com熱心網友回復:
您需要向 PDF 添加支持該語言代碼點的 Unicode 字體。代碼點 U 2019 是 RIGHT SINGLE QUOTATION MARK( ’) 并且不受 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。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/327212.html
