如何使用 Python 将 .pptx 转换为 .pdf

新手上路,请多包涵

几个小时以来,我一直在寻找通过 Python 脚本将 .pptx 文件转换为 .pdf 文件的方法,但似乎没有任何效果。

我试过什么: 我试过 1) 这个调用 windows32.client 的脚本,和 2) unoconv ,但它们似乎都不适合我。

遇到的问题: 使用第一个选项中的脚本会引发错误( com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2147024894), None) ),而在第二个选项中,Python 似乎无法识别 unoconv 即使在使用 pip 安装后也是如此。

我也看到了一些推荐的 Pandoc ,但我不明白如何将它用于 Python。

我使用的版本: Python 2.7.9、Windows 8.1

原文由 user238469 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 917
2 个回答

我在 这篇文章这个问题 的答案的帮助下找到了答案。

请注意, comtypes 仅适用于 Windows 。其他平台将不支持此功能。

 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()

原文由 user238469 发布,翻译遵循 CC BY-SA 4.0 许可协议

我正在使用此解决方案,但我需要搜索所有 .pptx、.ppt,然后将它们全部转换为 .pdf(python 3.7.5)。希望它有效…

 import os
import win32com.client

ppttoPDF = 32

for root, dirs, files in os.walk(r'your directory here'):
    for f in files:

        if f.endswith(".pptx"):
            try:
                print(f)
                in_file=os.path.join(root,f)
                powerpoint = win32com.client.Dispatch("Powerpoint.Application")
                deck = powerpoint.Presentations.Open(in_file)
                deck.SaveAs(os.path.join(root,f[:-5]), ppttoPDF) # formatType = 32 for ppt to pdf
                deck.Close()
                powerpoint.Quit()
                print('done')
                os.remove(os.path.join(root,f))
                pass
            except:
                print('could not open')
                # os.remove(os.path.join(root,f))
        elif f.endswith(".ppt"):
            try:
                print(f)
                in_file=os.path.join(root,f)
                powerpoint = win32com.client.Dispatch("Powerpoint.Application")
                deck = powerpoint.Presentations.Open(in_file)
                deck.SaveAs(os.path.join(root,f[:-4]), ppttoPDF) # formatType = 32 for ppt to pdf
                deck.Close()
                powerpoint.Quit()
                print('done')
                os.remove(os.path.join(root,f))
                pass
            except:
                print('could not open')
                # os.remove(os.path.join(root,f))
        else:
            pass

try and except 是针对那些我无法阅读的文档,直到最后一个文档才会退出代码。我建议将每种格式放在一边:首先是 .pptx,然后是 .ppt(或反之亦然)。

原文由 John Paul Lemmon 发布,翻译遵循 CC BY-SA 4.0 许可协议

推荐问题