Python reportlab库之使用自定义字体(含demo)

有些时候我们需要使用自定义的字体,例如生成文档中存在一些生僻字,系统自带的字体可能无法显示,我们就可以使用字库更全的字体。

具体代码如下:

import os.path
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.pdfbase.pdfmetrics import registerFont, stringWidth

base_path = os.path.dirname(__file__)
registerFont(TTFont('song', os.path.join(base_path, 'song.ttf')))
registerFont(TTFont('jiagu', os.path.join(base_path, 'HYChenTiJiaGuWen.ttf')))

w,h=256,256
fontSize=200
d = shapes.Drawing(w, h)
d.add(shapes.String(w/2-fontSize/2, h/2-fontSize/2+20, '中',
                            fontName='jiagu',
                            fontSize=fontSize))
renderPDF.drawToFile(d, 'word.pdf', 'word')

生成结果

Jietu20190727-073058@2x.jpg
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容