reportlab 中文问题[已解决]
2018-08-22 本文已影响763人
lilith买买买
问题
用reportlab生成pdf文件,碰到中文就会变成黑色的小方块,如下图。
![](https://img.haomeiwen.com/i1604189/3feb03488e70a0c5.png)
解决方法
1.下载中文字体SimSun.ttf
2.把下载下来的字体放到/Library/Python/2.7/site-packages/reportlab/fonts文件夹下。(文件夹根据自己安装的reportlab的路径来)
3.注册字体并使用
from reportlab.platypus import SimpleDocTemplate, Image, Paragraph
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
pdfmetrics.registerFont(TTFont('SimSun', 'SimSun.ttf')) #注册字体
styles = getSampleStyleSheet()
styles.add(ParagraphStyle(fontName='SimSun', name='Song', leading=20, fontSize=12)) #自己增加新注册的字体
Paragraph(describe, styles['Song']), #使用新字体
![](https://img.haomeiwen.com/i1604189/f38c3f72383f9a5d.png)
还有文字换行问题,暂时用了下面的方式
Paragraph(u'<br/>%s<br/>' % describe, styles['Song'])
参考:
https://stackoverflow.com/questions/30328945/setfont-in-reportlab-django