PowerPoint & Python: Editing PPT fails when an image is reached

跟風遠走 提交于 2019-12-12 02:14:35

问题


I am putting together a python script that will "clean up" a PowerPoint file's font-face, font-colors, font-size, etc. I found a snippet of code that does what I need it to do, however it seems to break as soon as it meets an image in a slide.

    import win32com.client, sys
Application = win32com.client.Dispatch("PowerPoint.Application")
Application.Visible = True
Presentation = Application.Presentations.Open(sys.argv[1])
for Slide in Presentation.Slides:
    for Shape in Slide.Shapes:
        Shape.TextFrame.TextRange.Font.Name = "Arial"
        Shape.TextFrame.TextRange.Font.Size = "12"
        Shape.TextFrame.TextRange.Font.Color.RGB = "000000"
Presentation.Save()
Application.Quit()

EDIT: Copy and pasted the wrong code... removed non-working if statement.

This all runs just fine, cleaning up silly looking fonts and colors until it hits its first image. Then it breaks and I am presented with this:

Traceback (most recent call last):
  File "c:/pptpy/convert.py", line 7, in <module>
    Shape.TextFrame.TextRange.Font.Name = "Arial"
  File "C:\Python33\lib\site-packages\win32com\client\dynamic.py", line 511, in __getattr__
    ret = self._oleobj_.Invoke(retEntry.dispid,0,invoke_type,1)
pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, None, 'The specified value is out of range.', None, 0, -2147024809), None)

If I remove all images (not shapes) from the file and run the script, it works great and I'm left with a decent powerpoint. The images are pretty important, however.

Details:

Python 3.3

PowerPoint 2007

Script to hopefully convert batches of 200-300 PPT(x) at a time, once finished.

If you need any more details, let me know! Thanks!


回答1:


While your code is not actually working replacing your if with a try catch works fine. This may not be a elegant method tough.

import win32com.client, sys
Application = win32com.client.Dispatch("PowerPoint.Application")
Application.Visible = True
Presentation = Application.Presentations.Open(sys.argv[1])
for Slide in Presentation.Slides:
    for Shape in Slide.Shapes:
        try:
            Shape.TextFrame.TextRange.Font.Name = "Arial"
            Shape.TextFrame.TextRange.Font.Size = "12"
            Shape.TextFrame.TextRange.Font.Color.RGB = "000000"
        except:
            pass
Presentation.Save()
Application.Quit()  

What probably happens to you is that the if is always true since an object qualifies as true. Try asking length of the object greater than 0 or something similar.




回答2:


You can surround the active code with something like:

If Shape.HasTextFrame Then
   If Shape.TextFrame.HasText Then
      ' do your stuff
   End If
End If


来源:https://stackoverflow.com/questions/16915067/powerpoint-python-editing-ppt-fails-when-an-image-is-reached

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!