'latin-1' codec can't encode characters
blinking-led opened this issue · 5 comments
When I using cycrylic caracters a see "UnicodeEncodeError: 'latin-1' codec can't encode characters in position 0-7: ordinal not in range(256)"
Error details
I use a list of Cyrillic symbols and get errors, but a list of Latin symbols works well.
Minimal code
from fpdf import FPDF
pdf = FPDF()
tableHeadres = ["один","два","три"] # get error
tableHeadres = ["one","two","three"] # get OK
with pdf.table() as table:
for tHead in tableHeadres:
row = table.row()
row.cell(tHead)
...
Environment
Windows 10 x64
Python 3.10
fpdf2==2.7.8
I found the same questions from 2022 and 2023 years, but it closed )
Hi @blinking-led
Can you copy/paste the exact error you are getting?
I tried running your snippet and it works OK with a TTF font, and I get the following when using a built-in font:
fpdf.errors.FPDFUnicodeEncodingException: Character "о" at index 0 in text is outside the range of characters supported by the font used: "helveticaB". Please consider using a Unicode font.
If you are getting the same error, please use a TTF font that contains the characters you are trying to use, since Cyrillic characters are not available in PDF built-in fonts.
I found old solution here https://pyfpdf.readthedocs.io/en/latest/Unicode/index.html but use it without uni=True
error:
return text.encode(self.core_fonts_encoding).decode("latin-1")
UnicodeEncodeError: 'latin-1' codec can't encode characters in position 0-3: ordinal not in range(256)The above exception was the direct cause of the following exception:
...
fpdf.errors.FPDFUnicodeEncodingException: Character "о" at index 0 in text is outside the range of characters supported by the font used: "helveticaB". Please consider using a Unicode font.
Is it really too hard to use built-in system fonts without copying them to a working folder? Why I cant use buidin Arial font?
Working solution. Using font was downloaded from the Web.
from fpdf import FPDF
pdf = FPDF()
pdf.add_page()
pdf.add_font('DejaVu', 'B', 'DejaVuSansCondensed.ttf')
pdf.set_font('DejaVu', 'B', 14)
tableHeadres = ["один","два","три"] # get error
#tableHeadres = ["one","two","three"] # get OK
with pdf.table() as table:
for tHead in tableHeadres:
row = table.row()
row.cell(tHead)
pdf.output("unicode.pdf", 'F')
I think you are mixing up system fonts with PDF core fonts. The core fonts don't have Cyrillic characters.
You can use the Arial system font. Assuming you are using windows it would look like this:
from fpdf import FPDF
pdf = FPDF()
pdf.add_page()
pdf.add_font("arial", "", "C:\\Windows\\Fonts\\arial.ttf")
pdf.add_font("arial", "b", "C:\\Windows\\Fonts\\arialbd.ttf")
pdf.set_font("arial", "", 12)
tableHeadres = ["один","два","три"] # get error
#tableHeadres = ["one","two","three"] # get OK
with pdf.table() as table:
for tHead in tableHeadres:
row = table.row()
row.cell(tHead)
@andersonhc Thank you for your solution, and sorry for my panic! )