[reportlab-users] Built-in versus embedded fonts

Robin Becker robin at reportlab.com
Mon Jun 22 06:05:53 EDT 2015


On 22/06/2015 10:03, Glenn Linderman wrote:
> On 6/22/2015 1:16 AM, Marius Gedminas wrote:
........
>>> I vaguely recall implementing this "proxy for reality" late one night in a
>>> coding frenzy... is there an easy way to obtain stringWidth for a TTF font?
>> This works fine with all kinds of fonts:
>>
>>      canvas.stringWidth(text, font_name, font_size)
>
> Thanks for the response, but it doesn't work with my TTFont ones, as far as I
> can tell... I get the same errors as reported in my last message, but with a
> slightly different call stack.
>
......

in the very latest reportlab code you can do this

from reportlab.pdfgen.canvas import Canvas
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.pdfbase.pdfmetrics import registerFont, registerFontFamily
registerFont(TTFont('arial','arial.ttf'))
registerFont(TTFont('arial-bold','arialbd.ttf'),)
registerFont(TTFont('arial-italic','ariali.ttf'),)
registerFont(TTFont('arial-bolditalic','arialbi.ttf'),)
registerFontFamily('arial',
		normal='arial',
		bold='arial-bold',
		italic='arial-italic',
		boldItalic='arial-bolditalic',)
sample = 'Hello World'
from reportlab.pdfbase.pdfmetrics import stringWidth
print "stringWidth(%r,'arial',12) = %s" % (sample,stringWidth(sample, 'arial',12))

canv = Canvas('thello.pdf',initialFontName='arial')
print "canv.stringWidth(%r) = %s" % (sample,canv.stringWidth(sample))

canv.drawString(72,72,sample)
canv.save()


the above produces

> C:\code\hg-repos\reportlab\tmp>thello.py
> stringWidth('Hello World','arial',12) = 62.015625
> canv.stringWidth('Hello World') = 62.015625


ie we added in initialFontName, initialFontSize & initialLeading arguments to 
the Canvas class. In addition the above shows that if the ttf is registered (the 
font family stuff is additional) then both pdfmetrics.stringWidth and 
canvas.stringWidth give reasonable results.


So Glenn, if you just use the register font stuff above

eg

from reportlab.pdfgen.canvas import Canvas
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.pdfbase.pdfmetrics import registerFont, registerFontFamily
registerFont(TTFont('arial','arial.ttf'))
sample = 'Hello World'
from reportlab.pdfbase.pdfmetrics import stringWidth
print "stringWidth(%r,'arial',12) = %s" % (
          sample,stringWidth(sample, 'arial',12))

does this cause an error?
-- 
Robin Becker


More information about the reportlab-users mailing list