gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 10:50:06 24 4
gpt4 key购买 nike

在通过 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)

最佳答案

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

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 中生成的模块的属性, 作为 shown in the Properties with arguments (named properties) section .这将使您能够访问与 Powerpoint IDL 关联的任何常量,包括支持自动完成的 IDE(一旦通过第一次访问 PowerPoint.Application 对象生成)。

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

枚举名称被添加到顶层生成的模块中,因此直接使用它们:

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 对象浏览器中找到类型库的简称; Steve Rindsberg's answer中的截图表明对于 PpSaveAsFileType枚举 PowerPoint .我相信在 documentation for the ppSaveAsFileType enum 中也使用了相同的名称;注意 (PowerPoint)添加到文档标题。

您还可以使用类型库的 GUID 以及版本号,但如果您必须手动输入,那这并不完全符合键盘的要求。

您可以使用 from comtypes.gen import PowerPoint; help(PowerPoint)如果您需要提醒或仅引用 Microsoft 文档,可以查看已定义的名称。

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

如果您找到任何使用 win32com 的代码示例相反,然后使用 win32com.client.constants属性直接转换为 comtypes.client.Constant(...)comtypes.gen.<module>属性。


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

关于python - 使用 comtypes 保存 PowerPoint 演示文稿时使用文件格式常量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52258446/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com