Search code examples
pythonperformanceoptimizationpowerpointwin32com

Saving a presentation through PowerPoint and Win32COM takes too long


I want to merge slides from multiple PowerPoint files into a single output file.

I have a folder filled with PowerPoint files that each only contain one slide. My current code creates a new presentation, copies the slides from the input files and pastes them into the output file.

I first tried this with python-pptx, but the few StackOverflow posts on this topic suggest that this is not or pretty much impossible, especially because I need to keep the layout, images, fonts, ... intact.

With some help from another SO post (I unfortunately do not know the source), I wrote a function that solves this problem:

def __mergePresentations(inputFileNames, outputFileName):
    Application = win32com.client.Dispatch("PowerPoint.Application")
    outputPresentation = Application.Presentations.Add()
    outputPresentation.SaveAs(outputFileName) # Save presentation to allow better modification

    print("Filling presentation...")
    for file in inputFileNames:
        print(f"- Copying {str(file)}")
        currentPresentation = Application.Presentations.Open(file)
        currentPresentation.Slides.Range(range(1, 2)).copy() # Only copy the first slide
        Application.Presentations(outputFileName).Windows(1).Activate()
        outputPresentation.Application.CommandBars.ExecuteMso("PasteSourceFormatting")
        currentPresentation.Close()

    print("Saving presentation...")
    outputPresentation.Save()
    print("Closing presentation...")
    outputPresentation.Close()
    Application.Quit()
    print("Presentation has been successfully saved.")
    return

Problem:

This code works, but for some reason, the program sometimes takes more than 30 seconds to save/quit. I know that Win32com can be pretty slow, but this makes the program almost unusable in its designated environment.

I am using PowerPoint on Office 365 and the program runs on Python 3.9. The code prints "Presentation has been successfully saved" instantly, but takes forever to return.

Did I forget any arguments to save the file properly? Can this be related to my environment?

Thanks!


Solution

  • For anyone else having this issue: Skip Application.Quit() and rather quit by calling os.system('taskkill /F /IM POWERPNT.EXE').

    This happens immediately and has the same functionality as Application.Quit() (as far as I could tell from testing).