【问题标题】:Reportlab pdfgen support for bold truetype fontsReportlab pdfgen 支持粗体 Truetype 字体
【发布时间】:2012-12-31 11:50:21
【问题描述】:

我一直在使用 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 仅带有 1 个文件(与其他一些字体不同)。我可以在 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”上给出一个关键错误。

有什么建议吗?

【问题讨论】:

    标签: django pdf-generation truetype reportlab


    【解决方案1】:

    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 时对我有用,它确实将样式变化包含在单独的文件中。
    • 在我看来,这并没有回答 OP 的 Q。他的 Q 与单个 TTF 文件有关。此处给出的答案明确引用了 TTC 文件。
    【解决方案2】:

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

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

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

    【讨论】:

    • 这不是任何解决方案,并且取决于 ttf 文件,它甚至可能以 redefining named object: 'toUnicodeCMap:AAAAAA+Font' 之类的错误结束
    猜你喜欢
    • 2012-07-18
    • 2013-01-07
    • 2013-01-08
    • 2015-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多