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

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


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source