使用 comtypes 保存 PowerPoint 演示文稿时使用文件格式常量

Using file format constants when saving PowerPoint presentation with comtypes

在通过 comtypes 保存 Powerpoint 演示文稿时,如何访问可用作文件格式的常量?

在下面的示例中,32 用作格式,但我想使用列出的常量 here) 或至少找到一个包含每个常量值的记录列表。

对于 Word,list 还包含每个常量的值。

import comtypes.client

powerpoint = comtypes.client.CreateObject("Powerpoint.Application")
pres = powerpoint.Presentations.Open(input_path)
pres.SaveAs(output_path, 32)

假设您有 PowerPoint 副本,启动它,按 ALT+F11 打开 VBA 编辑器,按 F2 打开对象浏览器,然后搜索另存为以获取此列表。单击任何常量名称可在对话框底部查看常量的值。

这是来自 Microsoft 的列表,其中包含每个常量的值:

https://docs.microsoft.com/en-us/office/vba/api/powerpoint.ppsaveasfiletype

您可以访问与通过 comtypes.client.Constants() class 加载的 COM object 关联的所有枚举名称;将它传递给您创建的 PowerPoint.Application COM object:

from comtypes.client import Constants, CreateObject

powerpoint = CreateObject("Powerpoint.Application")
pp_constants = Constants(powerpoint)

pres = powerpoint.Presentations.Open(input_path)
pres.SaveAs(output_path, pp_constants.ppSaveAsPDF)

Constants 实例加载底层类型库并将属性查找动态转换为类型库访问。由于某些不明确的原因,它没有包含在 comtypes 文档中,即使 it was added nearly 10 years ago now

另一种选择是访问 generated type library, as shown in the Properties with arguments (named properties) section 中生成的模块的属性。这将使您能够访问与 Powerpoint IDL 关联的任何常量,包括支持自动完成的 IDE(一旦通过第一次访问 PowerPoint.Application object 生成)。

如果类型信息在正在创建的 object 上公开,则当您使用 CreateObject() 时,该模块会自动生成; 'Powerpoint.Application' 绝对是这种情况,因为您没有明确设置接口。自动接口选择只有在类型信息可用时才有效。

枚举名称被添加到顶层生成的模块中,所以直接使用那些:

import comtypes.client

powerpoint = comtypes.client.CreateObject("Powerpoint.Application")

# only import the generated namespace after the com object has been created
# at least once. The generated module is cached for future runs.
from comtypes.gen import PowerPoint

pres = powerpoint.Presentations.Open(input_path)
pres.SaveAs(output_path, PowerPoint.ppSaveAsPDF)

可以在 VBA Object 浏览器中找到类型库的简称; Steve Rindsberg's answer shows that for the PpSaveAsFileType enum that's PowerPoint. I believe the same name is also used in the documentation for the ppSaveAsFileType enum 中的屏幕截图;请注意文档标题中的 (PowerPoint) 添加内容。

您也可以使用类型库的 GUID 和版本号,但如果您必须手动输入,那键盘就不太好用了。

如果需要提醒,您可以使用 from comtypes.gen import PowerPoint; help(PowerPoint) 查看定义了哪些名称,或者仅参考 Microsoft 文档。

这两种方法都避免了使用幻数; 类型库定义本身 为您提供了符号名称。

如果您发现任何使用 win32com 的代码示例,那么对 win32com.client.constants 属性的任何使用都会直接转换为 comtypes.client.Constant(...)comtypes.gen.<module> 属性。


我无法访问 Windows 设置来实际测试其中的任何一个,我是从阅读文档和 comtypes 的源代码中推断信息的。