python-pptx icon indicating copy to clipboard operation
python-pptx copied to clipboard

Producing a blank presentation from an existing PPTX

Open anotherdev23 opened this issue 9 years ago • 14 comments

Hello Steve and community I've been trying to open an existing PPTX file and use it as a template to produce new presentations using the same layout.

So I'm trying to accomplish this by first loading an existing presentation (Which contains a bunch of slides) and then I delete each slide from it in order to produce a blank PPTX but keeping the slide master. Here is the code I found for deleting slides:

    id_dict = {slide.id: [i, slide.rId] for i, slide in enumerate(prs.slides._sldIdLst)}
    slide_id = slide.slide_id
    prs.part.drop_rel(id_dict[slide_id][1])
    del prs.slides._sldIdLst[id_dict[slide_id][0]]

The code visually deletes the slides from the presentation, but when I try to open the resulting PPTX file PowerPoint says that there is a problem with the file and that it needs to be repaired. If I unzip the PPTX I see that there are some dangling references to the slides that were deleted.

I know I could just simply click repair and the file will be cleared by PowerPoint; or I could also just open the original PPTX and manually remove all the slides from it, then save it as a blank presentation. But I'm just curious to know if someone knows of a better way to achieve this.

Thanks in advance

anotherdev23 avatar Aug 29 '17 18:08 anotherdev23

What are the dangling references you mention?

scanny avatar Aug 29 '17 19:08 scanny

I did a compare side by side between the damaged and repaired presentation, here are the references that weren't deleted and that are causing the resulting PPTX to be corrupted:

[Left: damaged file | Right: PPTX repaired by PowerPoint] http://imgur.com/mTQ5WDK http://imgur.com/PkpXPrj http://imgur.com/8uxbUeh http://imgur.com/DIZIC8p http://imgur.com/dt7hjTG http://imgur.com/iisuUkt

I'm trying to fix those differences by hand and then will try to pack the files again into a PPTX to see if that resolves the problem. If so, I could look for a way to automate the process: unzip the presentation + apply fixes + zip presentation again. However it doesn't sound like the best way to approach this.

Any suggestions?

anotherdev23 avatar Aug 30 '17 05:08 anotherdev23

I think the root cause is in the fifth screen grab, where there are two slides referred to from viewProps.xml. Those relationships would cause the slide parts to be retained (although they wouldn't show) and their notes slides would come with them. That accounts for the extra content types you're seeing in the first screen grab.

So I think you're going to need to get rid of that element (or at least its children) and also remove the relationships (rId1 and rId2 in this case it looks like). That should give you a clean save in this limited case.

The second one (app.xml) I think you can ignore; at least leave it until the end; I don't think that would cause a repair error by itself.

The rId numbers will change on a save, that's not going to trigger a repair error. They're arbitrary and as long as they match what's in the .rels file, it doesn't matter what they are. python-pptx takes care of keeping all that straight based on the relationships from each part.

scanny avatar Aug 30 '17 06:08 scanny

You sir are brilliant! I proceeded and did the following changes:

  • From "ppt/viewProps.xml" removed:
<p:sldLst>
	<p:sld collapse="1" r:id="rId1"/>
	<p:sld collapse="1" r:id="rId2"/>
</p:sldLst>
  • Then from "ppt/_rels/viewProps.xml.rels" removed:
<Relationship Id="rId2" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slide" Target="slides/slide52.xml"/>
<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/slide" Target="slides/slide51.xml"/>

And that did the trick, I compressed back the files into a PPTX and this time it opened without problems.

For now I'm planning to automate this fix by writing some code that will unzip the file, get rid of those references and then will compress the file into a PPTX again. But apart from that approach, do you know if there is a more effective solution that could be implemented from the python-pptx library?

anotherdev23 avatar Aug 30 '17 20:08 anotherdev23

I suppose any way that gets it done is as good as the next. But all these operations are possible "within" python-pptx, although they're mostly not part of the API. Because they're not API items, they're subject to change between versions without deprecation notice. However, that is actually rare these days as the package has become pretty stable.

The key part of the code you'd need to use is pptx.opc. OPC stands for Open Packaging Convention and deals with all the details of getting each of the 'parts' (zip file member files roughly) into the right place with the right relationships.

That would allow you to locate the viewProps part, probably by content type or maybe relationship type from the presentation part. Then you could use lxml (XPath maybe) to modify the XML it contains. I don't believe it is parsed yet, so you'd need to look at XmlPart to see how that's done. The raw XML text is in the .blob attribute of the part. You can get it from there then put it back before saving after you've made the edits.

Then the relationships belong to the viewProps part, so you can sort through those and remove whichever ones you don't want.

Let me know if you're keen and I can help you find the bits you need. A deluxe approach would be to "monkey-patch" in a ViewPropsPart(XmlPart) object you write which would take care of loading it for you and give you access to the root element. You can even patch in additional custom element classes for the XML elements if you were inclined. That makes the XPath and certain other things easier by obviating the need for Clark-style namespace specification.

scanny avatar Aug 30 '17 20:08 scanny

Sure thing Steve! let me know where can we start.

anotherdev23 avatar Aug 31 '17 16:08 anotherdev23

So there are two steps, get rid of the XML, and then get rid of the relationships.

I'd start with the XML.

So first step is to get a reference to the view props part. For that you want to know who has a relationship to it, I expect that would be the presentation.xml part (you have to browse the .rels files to determine these things). So there the strategy would be to get the presentation part and then call .part_related_by() to get the view props part. You could confirm you had the right one by dumping the XML in the .blob of the part to the console.

Why don't you take a start on that and let me know where you run into trouble.

scanny avatar Aug 31 '17 18:08 scanny

So looks like these are the relations that we want to drop: http://imgur.com/uKriQ9r http://imgur.com/ygbkJcf

Inside each part I can see the corresponding blob and I confirmed that those are the dangling slides.

anotherdev23 avatar Aug 31 '17 19:08 anotherdev23

Yes, but all you need to do is drop the relationships and thereby "orphan" those parts. They won't be included in the save if they're not accessible via some relationship "path" from the presentation part (or maybe it starts at the package level, I'd have to look through the code).

Anyway, how I would approach this is be iterating the relationships from the view props part and dropping any that have the relationship type of SLIDE (if that's the matching one here). The relationship types enumeration is in pptx.opc.constants. So you would have something roughly like this:

from .constants import RELATIONSHIP_TYPE as RT

view_props_part = ... however you get it
rels = view_props_part.rels
for rel in rels:
    if rel.reltype == RT.SLIDE:
        del rels[rel.rId]

I think you might need to use rels.values in the for loop; I'm not sure that iteration is implemented on that class but it inherits from dict. You'll see what's needed when you try it out I expect.

Also check out Part.drop_rel() and Part._rel_ref_count() in that same module. It might make sense to make sure there aren't multiple references to that relationship.

scanny avatar Aug 31 '17 20:08 scanny

Thanks Steve, I tried removing the conflicting relations using "del" and/or "drop_rel", but after that the file still resulted in a damaged state. So instead I decided to do a direct modification to the blob attribute of the viewProp part and that worked just fine! The generated PPTX opened without issues.

Here is a short sample code:

from pptx import Presentation
from lxml import etree
from pptx.opc.constants import RELATIONSHIP_TYPE as RT

prs = Presentation("original.pptx")
self.delete_slides(prs, enumerate(prs.slides), 0)  # This is a separate method that deletes all slides

view_props = prs.part.part_related_by(RT.VIEW_PROPS)
tree = etree.fromstring(view_props.blob)  # I get the blob XML string and parse it with etree
elements = tree.xpath('.//*[local-name()="sldLst"]')  # I get the conflicting elements

for element in elements:
    element.getparent().remove(element)  # I get rid of the conflicting elements

# Then I convert the modified XML back to string and assign it to the blob attrib 
view_props.blob = etree.tostring(tree, xml_declaration=True, encoding="UTF-8", standalone="yes")
prs.save("blank.pptx")

I'll still continue trying the "drop_rel" and "del" methods. There must be something that I'm missing that still makes the file to be generated in a bad state when I try that approach.

anotherdev23 avatar Sep 01 '17 00:09 anotherdev23

Well, as I had mentioned about "two parts" above, you need to do both. So you need to edit the XML like you've done here, and you also have to remove the relationships from the view props part. It may load without a repair error if you leave the relationships in there, but I think you'll find the slide parts are still being saved, like slides\slide1.xml etc.

scanny avatar Sep 01 '17 02:09 scanny

You were right about that too (Not surprisingly of course!). The slide parts were still being saved and here is the small code portion that I was missing:

for rel in list(view_props.rels):
    if view_props.rels[rel].reltype == RT.SLIDE:
        del view_props.rels[rel]

Actually let me summarize the whole code implemented for the ease of reading:

def delete_slides(prs, slides):
    for slide in slides:
        slide = slide[1]  # A tuple is received, index "1" contains the slide object
        # The following lines were obtained from another issue posted here on GitHub
        id_dict = {slide.id: [i, slide.rId] for i, slide in enumerate(prs.slides._sldIdLst)}
        slide_id = slide.slide_id
        prs.part.drop_rel(id_dict[slide_id][1])
        del prs.slides._sldIdLst[id_dict[slide_id][0]]

def generate_blank_pptx():
    prs = Presentation("original.pptx")
    delete_slides(prs, enumerate(prs.slides))
    
    # The following lines were written thanks to the recommendations from Steve
    view_props = prs.part.part_related_by(RT.VIEW_PROPS)
    tree = etree.fromstring(view_props.blob)
    elements = tree.xpath('.//*[local-name()="sldLst"]')

    for element in elements:
        element.getparent().remove(element)

    view_props.blob = etree.tostring(tree, xml_declaration=True, encoding="UTF-8", standalone="yes")

    # Removing dangling slides relations
    for rel in list(view_props.rels):
        if view_props.rels[rel].reltype == RT.SLIDE:
            del view_props.rels[rel]

    prs.save("blank.pptx")

anotherdev23 avatar Sep 01 '17 03:09 anotherdev23

@scanny looks like we are good to close this issue. :-)

Once again, thanks for being so responsive and kind!

anotherdev23 avatar Sep 01 '17 03:09 anotherdev23

@atfuentess glad you got it working :)

I'll leave it open for now until I decide which parts of this we might implement. We might add some bits of this in later.

scanny avatar Sep 01 '17 18:09 scanny