Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
203 views
in Technique[技术] by (71.8m points)

How to set any font in reportlab Canvas in python?

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?

question from:https://stackoverflow.com/questions/4899885/how-to-set-any-font-in-reportlab-canvas-in-python

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...