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)
3

There are 3 best solutions below

1
On BEST ANSWER

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).

0
On

I suggest you to change your code as below since it worked for me very NICE:

for i in f:
    pdf.cell(200, 10, txt=i.encode('utf-8').decode('latin-1'), ln = 1, align = 'C')
0
On

It's because the default fonts for pyfpdf are latin-1 encoded.

You will need to download a utf-8 encoded font like Arial (https://www.freefontspro.com/14454/arial.ttf), place it in the same directory as the python file, and add the font using

fpdf.add_font("Arial", "", "arial.ttf", uni=True)

when you set the font use 'Arial'