I made it possible to insert (center) an image in the center of PowerPoint using python-pptx and Pillow (PIL).
python-pptx is a library that allows you to create PowerPoint from python. It's very convenient, but when you insert an image into a slide, you can only specify the insertion position in the upper left coordinates of the image. I wanted to center it, but I wasn't sure if there was such an option in python-pptx. Therefore, centering was realized by reading the image separately with a library called Pillow and acquiring the image size.
macOS Catalina version 10.15.3 python3.7.0
pip install python-pptx
pip install Pillow
from pptx import Presentation
from pptx.util import Inches
from PIL import Image
IMG_PATH = "/path/to/img_file"
IMG_DISPLAY_HEIGHT = Inches(3) #The height of the image when displayed on a slide. For the time being, set it to 3 inches.
SLIDE_OUTPUT_PATH = "test.pptx" #Slide output path
#Definition of slide object
prs = Presentation()
#Get slide size
SLIDE_WIDTH = prs.slide_width #
SLIDE_HEIGHT = prs.slide_height
#Add blank slides
blank_slide_layout = prs.slide_layouts[6]
slide = prs.slides.add_slide(blank_slide_layout)
#Get the image size and get the aspect ratio
im = Image.open(IMG_PATH)
im_width, im_height = im.size
aspect_ratio = im_width/im_height
#Calculate the size of the displayed image
img_display_height = IMG_DISPLAY_HEIGHT
img_display_width = aspect_ratio*img_display_height
#Calculate the upper left coordinates of the image when centering
left = ( SLIDE_WIDTH - img_display_width ) / 2
top = ( SLIDE_HEIGHT - img_display_height ) / 2
#Add images to slides
slide.shapes.add_picture(IMG_PATH, left, top, height = IMG_DISPLAY_HEIGHT)
#Output slide
prs.save(SLIDE_OUTPUT_PATH)
With the above code, you can make a PowerPoint slide with the figure centered as shown below. (The test image was taken by the author)
The Pillow part can be anything as long as the aspect ratio of the original image can be calculated, so for example opencv can be used instead. According to the documentation, python-pptx has a class called Image that has a size property, and it seems possible to get the size from it, but I didn't know how to do it. It's not smart to use Pillow just to get the image size, so if anyone knows how to do it with python-pptx alone, I'd appreciate it if you could teach me.
That's all for this article. Thank you for reading this far.
Recommended Posts