2015-11-30

ReportLab Chinese Support

I need to generate a PDF with Chinese characters in a Django project. Generating a PDF is straightforward as ReportLab does the job well. The hard part is to make sure the user can read the Chinese characters in the PDF.
At the end I settled in using the Chinese font provided by the Adobe's Asian Language Packs. That way, if no usable Chinese font is available, the user can download and install the Chinese font on demand automatically. This approach offers good performance since nothing is embedded in the PDF.
The following is the code snippet in registering the Chinese font for ReportLab to use.
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.cidfonts import UnicodeCIDFont
font_chinese = 'STSong-Light' # from Adobe's Asian Language Packs
pdfmetrics.registerFont(UnicodeCIDFont(font_chinese))
...
canvas.setFont(font_chinese)

No comments: