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

16

我一直在尝试使用Python脚本将.pptx文件转换为.pdf文件,但已经尝试了几个小时,没有任何进展。

我的尝试:我尝试了1)这个脚本,它调用了windows32.client,和2)unoconv,但似乎都不适用于我。

遇到的问题:使用第一个选项中的脚本会出现错误(com_error: (-2147352567, 'Exception occurred.', (0, None, None, None, 0, -2147024894), None)),而在第二个选项中,尽管使用pip安装了unoconv,但Python似乎仍无法识别它。

我还看到一些推荐使用Pandoc,但我不知道如何在Python中使用它。

我正在使用的版本:Python 2.7.9,Windows 8.1


1
感谢您的建议。 - user238469
1
还可以尝试这篇文章。编写Python代码和VBA非常相似。您只需要学习一些对象模型中的对象,如果您已经足够高级以应对此类挑战,那么这不应该超过几个小时。http://stackoverflow.com/questions/25526335/vba-object-model-reference-documentation - AMR
1
@AMR:在comtypes这篇文章的帮助下,我解决了它。 - user238469
1
你应该把这个问题的答案写下来。很高兴你找到了解决方案! - AMR
1
这篇文章可以回答你的问题,因为它展示了如何对Word文件执行相同的操作:https://dev59.com/z2025IYBdhLWcg3wblY3 - mstuebner
显示剩余5条评论
9个回答

30

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

请注意,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()

2
数字32来自哪里?有没有可用的格式列表? - Oskar Persson
@OskarPersson 这个数字来自于 PpSaveAsFileType 枚举,完整列表在这里:https://learn.microsoft.com/en-us/office/vba/api/powerpoint.ppsaveasfiletype - kibibu

6

我正在使用这个解决方案,但我需要搜索所有的 .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和except是用来处理那些我无法阅读的文档,直到处理完最后一个文档才会退出代码。我建议每种格式都单独处理:先处理.pptx,然后再处理.ppt(或反之亦然)。


这样做是有效的,但如果文件名中包含点号(.)(file_v_1.3.pptx),则此方法会带来问题。解决方法是先重命名文件,然后在最后再次重命名。有没有更好的方法? - valenzio

3

我认为答案需要更新,因为comtypes已经不能使用了。

以下是可用的代码(已更新为原先被接受的答案):

import win32com.client

def PPTtoPDF(inputFileName, outputFileName, formatType = 32):
    powerpoint = win32com.client.DispatchEx("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()

2
请看以下代码片段。它使用unoconv,在UBUNTU 20.04上正常工作。
# requirements
# sudo apt install unoconv
# pip install tqdm
# pip install glob
import glob
import tqdm
path = "<INPUT FOLDER>"
extension = "pptx"
files = [f for f in glob.glob(path + "/**/*.{}".format(extension), recursive=True)]
for f in tqdm.tqdm(files):
    command = "unoconv -f pdf \"{}\"".format(f)
    os.system(command)

这段代码可以用于不同格式的转换。

原始代码段


当我运行这段代码片段时,似乎没有输出。我应该在哪里能找到创建的PDF文件? - Ger

1

我需要一种将PPTX文件保存为PDF和带有注释的PDF的方法。这是我的解决方案

from comtypes.client import CreateObject, Constants

def PPTtoPDF(inputFileName, outputFileName, formatType = 32):
    powerpoint = CreateObject('Powerpoint.Application')
    constants = Constants(powerpoint)
    powerpoint.Visible = 1

    if outputFileName[-3:] != 'pdf':
        outputFileName = outputFileName + ".pdf"
    deck = powerpoint.Presentations.Open(inputFileName)
    deck.SaveAs(outputFileName, constants.PpSaveAsPDF)
    deck.Close()
    powerpoint.Quit()


def PPTtoPDFNote(inputFileName, outputFileName, formatType = 32):
    powerpoint = CreateObject('Powerpoint.Application')
    constants = Constants(powerpoint)
    powerpoint.Visible = 1

    if outputFileName[-3:] != 'pdf':
        outputFileName = outputFileName + ".pdf"
    deck = powerpoint.Presentations.Open(inputFileName)
    deck.ExportAsFixedFormat(
        outputFileName,
        constants.ppFixedFormatTypePDF,
        constants.ppFixedFormatIntentPrint,
        False, # No frame
        constants.ppPrintHandoutHorizontalFirst,
        constants.ppPrintOutputNotesPages,
        constants.ppPrintAll
    )
    deck.Close()
    powerpoint.Quit()

使用它,
PPTtoPDF    ('.\\Test.pptx', '.\Test.pdf'          )
PPTtoPDFNote('.\\Test.pptx', '.\Test_with_Note.pdf')

注意:最好使用Windows平台进行操作,即使用comtypes,这样它就可以始终支持Microsoft Powerpoint中的新格式和功能。

1

试试这段代码,它在我这里可以工作

import os
import win32com.client as win32
import comtypes

#make sure to initial cometypes
comtypes.CoInitialize()


# Path to input PowerPoint document
input_path = 'path/to/input/document.pptx'

# Path to output PDF file
output_path = 'path/to/output/document.pdf'

# Open PowerPoint document and convert to PDF
powerpoint = win32.Dispatch('Powerpoint.Application')
presentation = powerpoint.Presentations.Open(input_path)
presentation.SaveAs(output_path , 32)
presentation.Close()
powerpoint.Quit()

0

为了在 Google Cloud Function 上将 .pptx/.docx 转换为 pdf,我参考了这个 GitHub 仓库https://github.com/zdenulo/gcp-docx2pdf/tree/master/cloud_function,他们使用 Google Drive API。 在这个仓库中,他们使用 docx 的 MIME 类型来将 .docx 文件转换为在 Google Drive 上的 .pdf 文件。你也可以使用其他 MIME 类型,例如 pptx 的 MIME 类型(参考:https://developers.google.com/drive/api/v3/mime-types) 来在 Google Drive 上进行文件转换。 其余的代码与 GitHub 仓库中所述相同。


0

unoconv 是一款非常好用的工具,它是用 Python 构建的。 关于您的问题,可能与安装后主 unoconv 文件中设置 Python 解释器的方式有关。

要使用 Python3 解释器运行它,请在 unoconv 文件(/usr/bin/unoconv)中将 #!/usr/bin/env python 替换为 #!/usr/bin/env python3#!/usr/bin/python3

一行命令:

sudo sed -i -e '1s:#!/usr/bin/env python$:#!/usr/bin/env python3:' /usr/bin/unoconv

你也可以将 /usr/bin/unoconv 符号链接到 /usr/local/bin/unoconv


0
这是对@user238469答案的优化。这个函数使用ExportAsFixedFormat方法将文件保存为pdf格式。
def PPTtoPDF(inputFileName, outputFileName):
    powerpoint = comtypes.client.CreateObject("Powerpoint.Application")
    powerpoint.Visible = 1

    if outputFileName[-3:] != 'pdf':
        outputFileName = outputFileName + ".pdf"
    
    outputWindowsPath = Path(outputFileName)
    if outputWindowsPath.exists():
        outputWindowsPath.unlink()
    deck = powerpoint.Presentations.Open(inputFileName)
    deck.ExportAsFixedFormat(outputFileName, 2, 1, 0)
    deck.Close()
    powerpoint.Quit()

检查新文件保存之前是否已存在pdf文件,可以避免出现以下错误:
_ctypes.COMError: (-2147467259, 'Unspecified error', (None, None, None, 0, None))

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