Python PPTX module - Setting presentation to loop until Escape

95 Views Asked by At

I'm trying to set a .pptx presentation to loop until Escape is pressed. Usually this is done in Powerpoint in the Set up Slide Show Dialog, but I'm doing it with the python pptx module. I have tested with opc-diag and determined that the only difference when that option is selected is that there is a tag like this in the /ppt/presProps.xml part of the powerpoint file: <p:showPr loop="1" showNarration="1">

Now, in my python code, I have tried something to this extent with no success:

def xpath(el, query):
    nsmap = {'p': 'http://schemas.openxmlformats.org/presentationml/2006/main'}
    return etree.ElementBase.xpath(el, query, namespaces=nsmap)
    
presentation = Presentation()
p = "http://schemas.openxmlformats.org/presentationml/2006/main"
ele = etree.Element(etree.QName(p, "showPr"), attrib={'loop': '1'})

# this does not work... Expecting element, getting presentation. 
xpath(presentation, './/p:presentationPr')[0].getparent().insert(-1, ele)

I need to append the element for showPr to the root element of the presentation, but the xpath function is expecting an element, where I have just the presentation being passed. I do not know how to access the root node to append the showPr loop bit.

Any help would be appreciated.

I've tried the above code, which I was expecting to produce my desired result of setting <p:showPr loop="1" showNarration="1"> inside the /ppt/presProps.xml file but it is expecting an element, and I'm passing the presentation object. I don't know how to proceed.

1

There are 1 best solutions below

6
On BEST ANSWER

You're on the right track, but there are a few more steps:

  1. You need to get the PresentationProperties "part", which is an XML document distinct from the Presentation part. (The files inside the .pptx zip archive are called parts in the OPC lingo.)
from pptx.opc.constants import RELATIONSHIP_TYPE as RT

prs_part = presentation.part
prs_props_part = prs_part.part_related_by(RT.PML_PRES_PROPS)
  1. You need to to get the root element of the prs_props part:
from pptx.oxml import parse_xml

presentationPr = parse_xml(prs_props_part.blob)

Then you should be able to run your XPath expressions against that presentationPr element.

This should work to print the XML out to have a look at it, which will confirm the steps so far have worked:

from pptx.oxml.xmlchemy import serialize_for_reading

print(serialize_for_reading(presentationPr))