My initial months working with win32com saw me searching and reading MSDN Object Model References, reading other peoples win32com python code, and trawling VBA snippets whilst bashing away in a python IDE trying to get the function I was after. So here are my tips in reading the MSDN object references with the intent of replicating the functionality using win32com in Python.
The structure is roughly:
Step 1: Import modules and constants
from MSOconstants.MSO import constants as MSO
from MSOconstants.MSPPT import constants as MSPPT
Step 2: Create and set-up references to a powerpoint application, presentation, slide, add a diamond and save the presentation.
pptApp= win32com.client.gencache.EnsureDispatch (“Powerpoint.Application”)
presentation = pptApp.Presentations.Add()
slide = presentation.Slides.Add(1, MSPPT.ppLayoutBlank)
myDiamond = slide.Shapes.AddShape(MSO.msoShapeDiamond, Top=100,Left=100, Width=20, Height=20)
So far so good. I have a powerpoint slide with diamond thus:
Let’s say I want to add a bar to the slide that represents timeline between two dates such that I can place myDiamond on the timeline at a place that represents that point in time along the timeline; say 1/4 along the timeline.
I need to:
- Determine Slide Dimension
- Draw a box the width of the slide using the slide dimension
- place myDiamond 1/4 away along the box
Step 3: Determine Slide Dimension
A slide is dimensioned in pixels. I want to get the dimensions of my slide. I google “msdn powerpoint slide width” and get this link as the first entry.
So we need an object that represents the presentation “Application.ActivePresentation” so that we can call the PageSetup objects SlideWidth property. In our case we have a reference to the presentation in the variable “presentation“. So we call the presentation.PageSetup.SlideWidth property
for me it is 960 pixels.
Note: we can’t use “with” statements in Python.
Step 4: Draw a box the width of the slide using the slide dimension
I google “msdn powerpoint add shape” and get this link first
And hyperlink off to MsoAutoShapeType ctrl+f to find msoShapeRoundedRectangle
create a rectangle from left=0, 50 pixels down from the top, 960 pixels wide and 10 pixels in height:
RRect = slide.Shapes.AddShape(MSO.msoShapeRoundedRectangle, 0, 50, 960, 10)
Step 5: Place myDiamond 1/4 away along the box
Google “msdn powerpoint shape position” and get this first link
scroll down the page and you’ll see that it has a property called “left” and “top”
I want myDiamond 1/4 along 960 pixels and in the centre of 10 pixels high box that is 50 pixels down.
myDiamond.Top = 50-10/2