Skip to content

Instantly share code, notes, and snippets.

@dmahugh
Last active December 1, 2021 08:13
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save dmahugh/f642607d50cd008cc752f1344e9809e6 to your computer and use it in GitHub Desktop.
Save dmahugh/f642607d50cd008cc752f1344e9809e6 to your computer and use it in GitHub Desktop.
WIN32 automation of PowerPoint
"""Requires pypiwin32 - see installation instructions at https://github.com/mhammond/pywin32
"""
import random
import win32com.client
# for other shape types, see MsoAutoShapeTypeEnumeration:
# https://msdn.microsoft.com/en-us/vba/office-shared-vba/articles/msoautoshapetype-enumeration-office
SHAPE_OVAL = 9
# for other layout options, see PpSlideLayout Enumeration:
# https://msdn.microsoft.com/en-us/vba/powerpoint-vba/articles/ppslidelayout-enumeration-powerpoint
LAYOUT_BLANK = 12
def random_circle(slide):
"""Add a random circle to a slide."""
size = random.randrange(20, 160, 20) # random size between 20-160
# random position, keep circle at least 10 points from edge of slide ...
x_pos = random.randint(10, slide.parent.PageSetup.SlideWidth - size - 10)
y_pos = random.randint(10, slide.parent.PageSetup.SlideHeight - size - 10)
shape = slide.Shapes.AddShape(SHAPE_OVAL, x_pos, y_pos, size, size)
shape.Fill.ForeColor.RGB = random.randint(0, 2**32 - 1) # random color
shape.Line.Visible = 0 # no border
def main():
"""Launch PowerPoint, creat presentation, slide, and shapes."""
powerpoint = win32com.client.Dispatch('PowerPoint.Application')
presentation = powerpoint.Presentations.Add() # create presentation
slide = presentation.Slides.Add(1, LAYOUT_BLANK) # add a blank slide
for _ in range(100):
random_circle(slide) # add 100 random circles
if __name__ == '__main__':
main()
@dmahugh
Copy link
Author

dmahugh commented Apr 3, 2019

Here's a tweet with an animated GIF that shows the output of this code: https://twitter.com/dmahugh/status/962911161548095488

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment