Reportlab pdfgen支持加粗的TrueType字体

7

我一直在使用reportlab pdfgen创建动态pdf文档进行打印,这个工具已经在过去的几年中非常有效。

我们即将举办一次筹款活动,并希望使用我们正在使用的“主题”字体(具体来说是talldeco.ttf)生成pdf收据。

我已经成功设置了字体,使用了以下代码:

        from reportlab.pdfbase import pdfmetrics 
        from reportlab.pdfbase.ttfonts import TTFont 
        ttfFile = "/usr/share/fonts/truetype/ttf-tall-deco/TALLDECO.TTF"
        pdfmetrics.registerFont(TTFont("TallDeco", ttfFile))
        p.setFont("TallDeco", 18) # Was Times-Bold...

现在遇到的问题是:一些文本需要加粗和斜体,而talldeco只有一个文件(不像其他字体那样)。我可以在openoffice中使用这个字体来加粗和斜体文本。
根据reportlab用户指南(http://www.reportlab.com/software/opensource/rl-toolkit/guide/)第53页所述,应该是可能的,并且他们展示了一些代码和结果,但是我们的软件正在使用drawString调用而不是段落。基于上述示例的测试应用程序:
        from reportlab.pdfbase import pdfmetrics 
        from reportlab.pdfbase.ttfonts import TTFont 
        from reportlab.pdfbase.pdfmetrics import registerFontFamily
        ttfFile = "/usr/share/fonts/truetype/ttf-tall-deco/TALLDECO.TTF"
        pdfmetrics.registerFont(TTFont("TallDeco", ttfFile))
        registerFontFamily('TallDeco',normal='TallDeco',bold='TallDeco-Bold',italic='TallDeco-Italic',boldItalic='TallDeco-BoldItalic')
        p.setFont("TallDeco-Bold", 18) # Was Times-Bold...

在'TallDeco-Bold'上只会出现关键错误。

有什么建议吗?

2个回答

7

TTFont有一个subfontIndex参数。

以下内容对我有效(在OS X上使用reportlab 3.0):

menlo_path = "/System/Library/Fonts/Menlo.ttc"
pdfmetrics.registerFont(ttfonts.TTFont("Menlo", menlo_path,
                                       subfontIndex=0))
pdfmetrics.registerFont(ttfonts.TTFont("Menlo-Bold", menlo_path,
                                       subfontIndex=1))
pdfmetrics.registerFont(ttfonts.TTFont("Menlo-Italic", menlo_path,
                                       subfontIndex=2))
pdfmetrics.registerFont(ttfonts.TTFont("Menlo-BoldItalic", menlo_path,
                                       subfontIndex=3))
pdfmetrics.registerFontFamily("Menlo", normal="Menlo", bold="Menlo-Bold",
                              italic="Menlo-Italic",
                              boldItalic="Menlo-boldItalic")

尽管这种方法并没有解决原始问题,但在使用包含样式变化的单独文件的Consolas字体时,这种方法对我很有效。 - Todd
在我看来,这并没有回答原帖中提出的问题。他的问题与一个TTF文件有关。这里给出的答案明确提到了一个TTC文件。 - GaryMBloom

-1

需要定义粗体、斜体和粗斜体字体。

pdfmetrics.registerFont(TTFont("TallDeco-Bold", ttfFile))
pdfmetrics.registerFont(TTFont("TallDeco-Italic", ttfFile))
pdfmetrics.registerFont(TTFont("TallDeco-BoldItalic", ttfFile))

但是因为它们都指向同一个ttfFile,输出将全部看起来像默认的TallDeco,即没有加粗或斜体


这不是任何解决方案,而且根据ttf文件的情况,它甚至可能会出现错误,例如“重新定义命名对象:'toUnicodeCMap:AAAAAA+Font'”。 - DimmuR

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