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!
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:
To fix it:
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:

verify:

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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With