Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Font size in Python Pillow and Microsoft Word

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!

like image 467
aTree Avatar asked Dec 17 '25 11:12

aTree


2 Answers

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

like image 99
Ajeet Verma Avatar answered Dec 19 '25 00:12

Ajeet Verma


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))
like image 32
aTree Avatar answered Dec 18 '25 23:12

aTree



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!