Search code examples
pythonunicodefpdf

UnicodeEncodeError: 'latin-1' codec can't encode when trying to write hebrew to a PDF


im trying to write some hebrew words to a pdf file using the FPDF Libary in Python

and im getting an error

UnicodeEncodeError: 'latin-1' codec can't encode characters in position 51-55: ordinal not in range(256)

how can i fix that and write hebrew to the PDF file?

adding my code below

     pdf = FPDF()
    pdf.add_page()
    pdf.set_font("Arial", size=15)
    welcome="היייי"
    pdf.cell(200, 10, txt=welcome, ln=1, align="C")
    pdf.output("simple_demo.pdf")

Solution

  • From set_font documentation:

    Standard fonts use Latin-1 encoding by default, (...)

    and

    Default encoding is not specified, but all text writing methods accept only Unicode for external fonts and one byte encoding for standard.

    Your Arial is a standard family, so it accept only Latin-1 encoding (1 byte). So you should change font, with a non standard one, in order to have a Unicode fonts, so in order to get Hebrew text.