phos
phos

Reputation: 83

Justify text using Pillow / Python

I am using Pillow 7.2.0 in Python 3 to insert text into an image with a fixed size.

I now want to insert text with a fixed font and font size into a specific width and have it justified, like a fixed text-box. The text should be justified within the text-box so it touches the left and right end. I don't see any documentation for how to do this.

What is the most reasonable method to do this?

I do want for it to be able to squish the text horizontally to fit the text-box without creating a second line, although it is seldom the case.

As a sidenote I was looking through the documentation for Pillow and was wondering what the anchor parameter does. I didn't find any explanation for it.

ImageDraw.text(... anchor=None, ...)

Upvotes: 6

Views: 954

Answers (1)

Nulano
Nulano

Reputation: 1343

Pillow does not have a built-in way to justify text. The best way to justify text is to break it by spaces and insert spaces to fill the remaining space.

from PIL import Image, ImageDraw, ImageFont

font = ImageFont.truetype("arial.ttf", 20)
text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.\n"\
       "Pellentesque accumsan nec felis ut vulputate."

image_width = 600
im = Image.new("RGB", (image_width, 80), "white")
d = ImageDraw.Draw(im)

y = 10
for line in text.split("\n"):
    words = line.split(" ")
    words_length = sum(d.textlength(w, font=font) for w in words)
    space_length = (image_width - words_length) / (len(words) - 1)
    x = 0
    for word in words:
        d.text((x, y), word, font=font, fill="black")
        x += d.textlength(word, font=font) + space_length
    y += 30

example of justified text

Upvotes: 7

Related Questions