添加在ReportLab中使用的字体

时间:2010-04-16 21:14:35

标签: python fonts reportlab

我正在尝试在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 个答案:

答案 0 :(得分:7)

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

setFont设置您要使用的字体名称,以及drawString

如果您在文档中使用该字体,ReportLab将自动嵌入该字体,您无需在名称下全局注册字体后手动添加该字体。