Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reportlab pdfgen support for bold truetype fonts

I have been using reportlab pdfgen to create dynamic pdf documents for printing. It has been working very well for a number of years.

We are having a fund raising event coming up, and wish to generate pdf receipts with the 'theme' font we are using (specifically talldeco.ttf).

I have set the font no problem using the following:

        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...

Now comes the issue: some of the text needs to be bold and italics, and the talldeco just comes with 1 file (unlike some of the other fonts). I can bold and italicize text in this font in openoffice.

Per the reportlab users guide (http://www.reportlab.com/software/opensource/rl-toolkit/guide/) page 53, it should be possible and they show some code and the results, but our software is using drawString calls instead of paragraphs. A test app based on the sample noted above:

        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...

Just gives a Key Error on 'TallDeco-Bold'.

Any suggestions?

like image 926
Dan Avatar asked Oct 21 '22 19:10

Dan


1 Answers

TTFont has a subfontIndex parameter.

The following works for me (using reportlab 3.0 on OS X):

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")
like image 194
TimZehta Avatar answered Nov 03 '22 19:11

TimZehta