How to calculate length of string in pixels for specific font and size?

If the font, e.g. "Times New Roman", and size, e.g. 12 pt, is known, how can the length of a string, e.g. "Hello world" be calculated in pixels, maybe only approximately?

I need this to do some manual right alignment of text shown in an Windows application, so I need to adjust the number spaces to get the alignment.


  • An alternative is to ask Windows as follows:

    import ctypes
    def GetTextDimensions(text, points, font):
        class SIZE(ctypes.Structure):
            _fields_ = [("cx", ctypes.c_long), ("cy", ctypes.c_long)]
        hdc = ctypes.windll.user32.GetDC(0)
        hfont = ctypes.windll.gdi32.CreateFontA(points, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, font)
        hfont_old = ctypes.windll.gdi32.SelectObject(hdc, hfont)
        size = SIZE(0, 0)
        ctypes.windll.gdi32.GetTextExtentPoint32A(hdc, text, len(text), ctypes.byref(size))
        ctypes.windll.gdi32.SelectObject(hdc, hfont_old)
        return (,
    print(GetTextDimensions("Hello world", 12, "Times New Roman"))
    print(GetTextDimensions("Hello world", 12, "Arial"))

    This would display:

    (47, 12)
    (45, 12)