How to set any font in reportlab Canvas in python?

srisar picture srisar · Feb 4, 2011 · Viewed 33.8k times · Source

I'm using reportlab to create pdfs. When I try to set a font using the following method, I get a KeyError:

pdf = Canvas('test.pdf')
pdf.setFont('Tahoma', 16)

But if I use 'Courier' instead of 'Tahoma' there isn't a problem. How can I use Tahoma?

Answer

Reiner Gerecke picture Reiner Gerecke · Feb 4, 2011

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.