PIL - draw multiline text on image

Solution 1:

You could use textwrap.wrap to break text into a list of strings, each at most width characters long:

import textwrap
lines = textwrap.wrap(text, width=40)
y_text = h
for line in lines:
    width, height = font.getsize(line)
    draw.text(((w - width) / 2, y_text), line, font=font, fill=FOREGROUND)
    y_text += height

Solution 2:

The accepted answer wraps text without measuring the font (max 40 characters, no matter what the font size and box width is), so the results are only approximate and may easily overfill or underfill the box.

Here is a simple library which solves the problem correctly: https://gist.github.com/turicas/1455973