Home > Enterprise >  Python fpdf is not giving correct output
Python fpdf is not giving correct output

Time:03-02

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: Šš

CodePudding user response:

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.

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

Result:

PDF result

  • Related