Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python fpdf is not giving correct output

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading