3

I want to make images in Python Pillow with text, insert the images into a Microsoft Word document, and have the font size in the image match the font size in the document. How do I make the font sizes match?

My Microsoft Word is set to insert images at 220 dpi, and I saw online that the default dpi for Pillow is 96, so I tried multiplying the font size in Pillow by 220/96, but the image font size still doesn't match the document font size.

Here's example code:


from PIL import Image, ImageDraw, ImageFont

fontSize = 12
## fontSize *= 220/96 ## adjust from PIL dpi to word dpi (didn't work)
font = ImageFont.truetype("TR Times New Roman Regular.ttf", size=fontSize)

im = Image.new("RGB", (100,100), "black")
draw = ImageDraw.Draw(im)

draw.text((10,40),"example text", fill="white", font = font)

im.show()
im.save("output.png")

Thanks!

2 Answers 2

1

When working with Pillow, the font size you pass to ImageFont.truetype() is always in points, but points only convert correctly to pixels when the image has the correct DPI set.

By default, Pillow creates images at 72 DPI, and if you save without specifying DPI, Word interprets the image using its own DPI rules.

So the mismatch perhaps happens because of the followings:

  • Pillow renders your text at 72 DPI
  • Word places images at ~220 DPI
  • and the PNG you save doesn't include DPI metadata unless you *explicitly *set it

To fix it:

  • you can set the DPI on the image when saving and
  • Pillow will correctly scale the text relative to that DPI,
  • and Word will display it at the expected physical size.

code:

from PIL import Image, ImageDraw, ImageFont

font_size = 12
font_size *= int(220/72)
font = ImageFont.truetype("D:\\automation\\times.ttf", size=font_size)

# Create an image, physical size does not matter
im = Image.new("RGB", (400, 200), "black")
draw = ImageDraw.Draw(im)

draw.text((10, 80), "example text", fill="white", font=font)

# Important: save with the same DPI Word uses (220)
im.save("output.png", dpi=(220, 220))

output.png:

enter image description here

verify: enter image description here

Sign up to request clarification or add additional context in comments.

Comments

1

The default dpi in Pillow is 72, not 96, so the correct code is:

from PIL import Image, ImageDraw, ImageFont

fontSize = 12
fontSize *= 220/72 ## adjust from PIL dpi to word dpi\
font = ImageFont.truetype("TR Times New Roman Regular.ttf", size=fontSize)

im = Image.new("RGB", (100,100), "black")
draw = ImageDraw.Draw(im)

draw.text((10,40),"example text", fill="white", font = font)

im.show()
im.save("output.png", dpi=(220,220))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.