Search code examples
pythonfpdf

FPDF encoding on writing not working in Python


I'm trying to create a PDF file using Python and FPDF. I've read the project's page about unicode and I've tryed to follow their instructions, but everytime I run my program, I receave the error:

File "eventsmanager.py", line 8 SyntaxError: Non-ASCII character '\xc3' in file eventsmanager.py on line 8, but no encoding declared; see http://python.org/dev/peps/pep-0263/ for details

This is my program:

from fpdf import FPDF

pdf = FPDF()
pdf.add_page()

pdf.add_font('gargi', '', 'gargi.ttf', uni=True) 
pdf.set_font('gargi', '', 14)
pdf.write(8, 'Olá!!')
pdf.ln(20)

pdf.output('tuto3.pdf', 'F')

Can you help me understanding what I'm doing wrong?


Solution

  • You need to declare that the file encoding is UTF8 as Python 2 defaults to Latin-1. UTF8 became default in Python 3. The linked PEP contain the required line that you have to add at the beginning of the file:

    # coding: utf8
    

    This must be the first line after the #! line

    EMACS and VIM formats are also supported.

    It is sad that the error message doesn't include the solution.