Pixel size of a String in Python

2

I would like to know how to make a Python code that checks the size of a string (in pixels).

Assuming we have a string 'ALCON BOTTON FISH 50G' I would like to know what its pixel size is to center on a square I am plotting with reportlab (I am using absolute plotting - stating the x and y position - because I can not find an automatic make this centralization)

    
asked by anonymous 03.12.2018 / 20:47

1 answer

1

There is no single calculation because the resulting size depends on the source. In Arial 12 is a size, in Times New Roman 12 will give another ... if you use bold, it changes too.

Kerning still exists, which is the difference in spacing between two letters, depending on which letters are:

So it's hard to figure this out without drawing the font. An example in Pillow has the function ImageFont.getsize() :

>>> arial = PIL.ImageFont.truetype('Arial', 12)
>>> arial.getsize('Palavra')
(42, 11)
    
04.12.2018 / 11:21