我正在尝试向 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”只是我随意使用的一种随机字体。
最佳答案
c.setFont('TestFont')
c.drawString(1,1,'test data here')
setFont
设置您要使用的字体名称,以及 drawString
。
如果您在文档中使用该字体,ReportLab 将自动嵌入该字体,您无需在全局名称下注册该字体后手动添加它。
关于python - 添加用于 ReportLab 的字体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2656145/