为ReportLab添加字体

12
我正在尝试向Python的ReportLab添加字体,以便在函数中使用。该函数使用canvas.Canvas在PDF中绘制一些文本,没有什么复杂的,但是由于布局问题,我需要添加一个等宽字体。
当我尝试使用我能找到的少量信息注册字体时,似乎起作用了。但是当我尝试从我的Canvas对象调用.addFont('fontname')时,我一直收到“PDFDocument实例没有属性'addFont'”的错误。
这个函数只是没有被实现吗?我如何获得除了.getAvailableFonts列出的10个左右默认字体之外的其他字体?谢谢。
以下是我尝试实现的一些示例代码:
from reportlab.pdfgen import canvas
c = canvas.Canvas('label.pdf')
c.addFont('TestFont') #This throws the error listed above, 
                      #regardless of what argument I use (whether it refers 
                      #to a font or not).
c.drawString(1,1,'test data here')
c.showPage()
c.save()

为了注册字体,我尝试了

from reportlab.lib.fonts import addMapping
from reportlab.pdfbase import pdfmetrics

pdfmetrics.registerFont(TTFont('TestFont', 'ghettomarquee.ttf'))
addMapping('TestFont', 0, 0, 'TestFont')

“ghettomarquee.ttf”只是我随便找到的一个字体。

1个回答

8
c.setFont('TestFont')
c.drawString(1,1,'test data here')

使用setFont设置字体名称,drawString用于绘制字符串。
如果您在文档中使用字体,ReportLab将自动嵌入该字体,您不必在全局注册字体名称后手动添加它。

1
第一行是不是应该写成 c.setFont('TestFont') - drevicko

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接