How to set any font in reportlab Canvas in python?

北城以北 提交于 2019-11-28 16:41:59

Perhabs Tahoma is a TrueType font, and you need to register it first. According to the user guide of ReportLab you need to do this:

from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont

pdfmetrics.registerFont(TTFont('Vera', 'Vera.ttf'))
pdfmetrics.registerFont(TTFont('VeraBd', 'VeraBd.ttf'))
pdfmetrics.registerFont(TTFont('VeraIt', 'VeraIt.ttf'))
pdfmetrics.registerFont(TTFont('VeraBI', 'VeraBI.ttf'))

canvas.setFont('Vera', 32)
canvas.drawString(10, 150, "Some text encoded in UTF-8")
canvas.drawString(10, 100, "In the Vera TT Font!")

The canvas object has a getAvailableFonts method that should return all currently registered (and therefore usable) fonts.

Pranay Majmundar

Start at Reiner's answer.

It is perfect with one caveat.

Reportlab only searches for fonts in predefined folders:

TTFSearchPath = (
            'c:/winnt/fonts',
            'c:/windows/fonts',
            '/usr/lib/X11/fonts/TrueType/',
            '/usr/share/fonts/truetype',
            '/usr/share/fonts',             #Linux, Fedora
            '/usr/share/fonts/dejavu',      #Linux, Fedora
            '%(REPORTLAB_DIR)s/fonts',      #special
            '%(REPORTLAB_DIR)s/../fonts',   #special
            '%(REPORTLAB_DIR)s/../../fonts',#special
            '%(CWD)s/fonts',                #special
            '~/fonts',
            '~/.fonts',
            '%(XDG_DATA_HOME)s/fonts',
            '~/.local/share/fonts',
            #mac os X - from
            #http://developer.apple.com/technotes/tn/tn2024.html
            '~/Library/Fonts',
            '/Library/Fonts',
            '/Network/Library/Fonts',
            '/System/Library/Fonts',
            )

If you're trying to use a ttf font that you've downloaded off of the internet, and would like that font available on all your servers, I would suggest the following:

  • Add the font to your project in any directory. e.g.: /project_root/app/lib/reportlabs/fonts/
  • Make sure you have something like BASE_DIR/ROOT_DIR in your settings:

    BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    
  • add the following line to a python file that generates pdf:

    import reportlab
    from django.conf import settings
    reportlab.rl_config.TTFSearchPath.append(str(settings.BASE_DIR) + '/app/lib/reportlabs/fonts')
    pdfmetrics.registerFont(TTFont('Copperplate', 'Copperplate-Gothic-Bold.ttf'))
    

By adding DejaVuSans Font to application solved my problem. Here is the snippet of code

pdfmetrics.registerFont(TTFont('DejaVuSans','DejaVuSans.ttf'))

And use UTF8 for all coding.:)

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!