Search code examples
pythonunicodefontsfpdf

Unreadable text after printing to PDF


I need to print text to PDF but the text I am printing is non-ascii. Base on the output of my code, it generate something like this

[][][][][][][] (A box ;) )

I'm trying to figure out how to print non-ascii text to PDF. Thanks!

#!/usr/bin/env python
# -*- coding: utf-8 -*- 

def sample():
    pdf = fpdf.FPDF()
    pdf.add_page()
    text = '안녕하세요'
    pdf.add_font('DejaVu', '', 'fpdf\\unifont\\DejaVuSansCondensed.ttf', uni=True)
    pdf.set_font('DejaVu', '', 9)

    pdf.text(x=data_column, y=start_y + (3 * charheight),
                 txt=str(u": {0}".format(text)))


Solution

  • You're using a font that doesn't support Hangul characters. The fpdf docs use the eunjin font for Hangul:

    # Add a Alee Unicode font (uses UTF-8)
    # General purpose Hangul truetype fonts that contain Korean syllable 
    # and Latin9 (iso8859-15) characters.
    pdf.add_font('eunjin', '', 'Eunjin.ttf', uni=True)
    pdf.set_font('eunjin', '', 14)
    pdf.write(8, u'Korean: 안녕하세요')