Skip to content
Advertisement

Python PPTX read slide number (page number)

I’m doing a custom table of content for slides that is generated by Python-PPTX. For the slides, footer and slide numbers already set up, and I can already view it in resulting PPTX. I believe slide numbers already exist, just needed to be read.

My question is, whether the slide number information is accessible from slide object, or perhaps somewhere else? Overall script looks like this:

from pptx import Presentation
prs = Presentation()
for x in 'abc':
    s = prs.slides.add_slide(prs.slide_layouts[6])

    if x=='b':
        s.placeholders[0].text = <str: page number of current slide 's'>

Advertisement

Answer

There is no slide number attribute of a slide as far as I know, all a slide number is is the position of the slide in the presentation. The slide number that appears in a footer is a sld-num field element, that displays this position when you are in the PowerPoint application, but this number is calculated the same way.

It could be there is some special behavior when you create a custom slide show, like skipping slide numbers that are “hidden”, but I haven’t experimented with that.

For general purposes, the easiest way to get it is like this:

slides = prs.slides
for slide in slides:
    print('slide number %d' % slides.index(slide)+1)

I’m not sure if that’s what you were talking about in your comment, but using the index() method on Slides is perhaps more flexible than something like:

for idx, slide in enumerate(slides):
    print('slide number %d' % idx+1)

or

def slide_number(slides, slide):
    for idx, s is enumerate(slides):
         if s == slide:
             return idx+1

You do need to have references to both slides and the slide to make it work.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement