11

我正在尝试向 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' 只是我躺在身边的一种随机字体。

4

1 回答 1

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

setFont设置您要使用的字体名称,然后drawString.

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

于 2010-04-16T21:45:32.973 回答