I am trying to convert text file into pdf in Python but I am getting error. Why is it happening and how can I fix it?
Here my code:
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")
Output: Error
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)
All the standard fonts in fpdf use latin-1
encoding. If you want to write characters that aren't in the latin-1
set, you'll need to use set_font
to specify an external font.
Reference: https://pyfpdf.readthedocs.io/en/latest/reference/set_font/index.html
Otherwise you'll have to convert your string to latin-1
(using the encode
method) and specify whether to ignore or replace the bad characters (i.e. the ones that don't exist in latin-1
).