使用comtypes.client将.pptx文件转换为.pdf时出错。

4

我想把一个.pptx文件转换为pdf文件。目前我有以下的代码:

PP_FORMAT_PDF = 32

def _convert_powerpoint2pdf(input_path, output_path):
    try:
        import comtypes
        import comtypes.client
    except ImportError as error:
        raise 
    else:
        powerpoint = slides = None
        try:
            comtypes.CoInitialize()
            powerpoint = comtypes.client.CreateObject('Powerpoint.Application')
            slides = powerpoint.Presentations.Open(input_path)
            slides.SaveAs(output_path, FileFormat=PP_FORMAT_PDF)
        except WindowsError as error:
            raise
        except comtypes.COMError as error:
            raise IOError(error)
        finally:
            slides and slides.Close()
            powerpoint and powerpoint.Quit()
            comtypes.CoUninitialize()

错误:

Traceback (most recent call last):
  File "C:/Users/Mathias/git/pdfconv/tests\test_converter.py", line 89, in test_convert_presentation2pdf_pptx
    pdfconv.converter.convert_presentation2pdf(input_path, output_path)
  File "c:\users\mathias\git\pdfconv\pdfconv\converter.py", line 116, in convert_presentation2pdf
    _convert_powerpoint2pdf(input_path, output_path)
  File "c:\users\mathias\git\pdfconv\pdfconv\converter.py", line 179, in _convert_powerpoint2pdf
    slides.SaveAs(output_path, FileFormat=PP_FORMAT_PDF)
_ctypes.COMError: (-2147467259, 'Unbekannter Fehler', (u'Presentation (unknown member) : PowerPoint kann ^0 auf ^1 nicht speichern.', u'Microsoft PowerPoint 2013', u'', 0, None))

几乎相同的代码在Word和Excel中都能正常工作。有人知道我做错了什么吗?
1个回答

1

考虑使用以下详细解决方案:如何使用Python将.pptx转换为.pdf

上述资源中的解决方案(今天对我有效)为:

import comtypes.client

def PPTtoPDF(inputFileName, outputFileName, formatType = 32):
    powerpoint = comtypes.client.CreateObject("Powerpoint.Application")
    powerpoint.Visible = 1

    if outputFileName[-3:] != 'pdf':
        outputFileName = outputFileName + ".pdf"
    deck = powerpoint.Presentations.Open(inputFileName)
    deck.SaveAs(outputFileName, formatType) # formatType = 32 for ppt to pdf
    deck.Close()
    powerpoint.Quit()

谢谢分享,但是这个代码可以在循环中工作吗?我正在尝试通过在for循环内重复使用上面的代码来创建2个或更多不同PPT的PDF文件,但是代码只适用于第一个ppt到pdf的转换。之后,我会收到一个错误“COMError:(-111111,None,('Presentation(unknown member):Object does not exist。','Microsoft PowerPoint','',0,None))” - Scinana
我使用这个解决方案时遇到了相同的错误:“_ctypes.COMError:(-2147467259,'未指定错误',('Presentation(unknown member):PowerPoint无法将^0保存在^1中。','Microsoft PowerPoint','',0,None))” - David Valenzuela Urrutia

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接