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

作者: iCloudEnd | 来源:发表于2019-07-27 07:31 被阅读3次

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

    具体代码如下:

    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

    相关文章

      网友评论

        本文标题:Python reportlab库之使用自定义字体(含demo)

        本文链接:https://www.haomeiwen.com/subject/rphsrctx.html