如何使用 Python 创建 PowerPoint 演示文稿

在这篇简单的文章中,我们将展示如何使用 Python 创建 PowerPoint Presentation ,按照详细步骤设置环境并在您的端运行示例。您可以使用 Python 创建 PowerPoint 并可以在任何演示文稿查看器中查看,包括 MS PowerPoint。示例代码可以在任何配置了 Python 的 .NET Core 支持平台中使用。

使用 C# 创建 PowerPoint 演示文稿的步骤

  1. 在您的应用程序中配置 通过 .NET 为 Python 设置 Aspose.Slides 的环境
  2. 在 Python 文件中导入 aspose.pydrawing 和 aspose.slides
  3. 使用 Presentation 类对象生成一个空的演示文稿
  4. 使用 add_empty_slide 方法在幻灯片集合中添加空白幻灯片
  5. 使用 add_auto_shape 方法在幻灯片中插入一个矩形形状
  6. 使用 add_text_frame 方法添加文本框架并应用不同的文本属性
  7. 使用 Python Powerpoint 演示文稿中的 Save 方法生成并保存在磁盘上

为了生成定制的 PPTX Python API,请遵循上述步骤。该过程涉及使用 Presentation 类创建一个空演示文稿,然后在幻灯片集合中添加一张空白幻灯片。通过向形状添加文本框架并设置文本属性,然后将生成的演示文稿保存在磁盘上,创建了一个矩形自动形状,其中填充了一些文本。

使用 Python 创建 PowerPoint 的代码

import aspose.pydrawing as drawing
import aspose.slides as slides
# Applying the linence for Aspose.Slides
slidesLicense = slides.License()
slidesLicense.set_license("Aspose.Total.lic")
# Generate an empty presentation using Presentation class object
with slides.Presentation() as presentationObj:
# Insert a Blank slide inside the slides collection
slide = presentationObj.slides.add_empty_slide(presentationObj.layout_slides.get_by_type(slides.SlideLayoutType.BLANK))
# Add a Rectangle autoshape inside the newly added slide
autoShape = slide.shapes.add_auto_shape(slides.ShapeType.RECTANGLE, 50, 150, 300, 0)
# Fill the auto shape with color
autoShape.fill_format.fill_type = slides.FillType.SOLID
autoShape.fill_format.solid_fill_color.color = drawing.Color.green;
# Add a text frame to insert some text inside the shape
txtFrame = autoShape.add_text_frame("Welcome to Aspose Knowledgebase examples")
# Apply the text related properties
portionFormat = txtFrame.paragraphs[0].portions[0].portion_format
portionFormat.fill_format.fill_type = slides.FillType.SOLID
portionFormat.fill_format.solid_fill_color.color= drawing.Color.red
portionFormat.font_bold = slides.NullableBool.TRUE
portionFormat.font_italic = slides.NullableBool.TRUE
portionFormat.font_height = 14
# Save the generated presentation on the disk
presentationObj.save("NewPresentation.pptx", slides.export.SaveFormat.PPTX)

通过使用上述 Python Presentation 中的示例,已在磁盘上创建了 PPTX 格式。 SaveFormat 枚举器还提供了以 PPT、PPS、PPSX、ODP、POT 和 POTX 格式保存演示文稿的选项。通过使用 PortionFormat 和 ParagraphFormat 类中可用的不同属性,可以进一步自定义幻灯片形状内的文本,包括设置段落项目符号、文本缩进、边距、下划线和突出显示文本。

在此示例中,我们已经看到,为了创建 PPTX 演示文稿,可以使用基于 Python 的 API,而无需依赖 MS PowerPoint。如果您有兴趣将演示文稿转换为 PDF,请参阅 如何使用 Python 将演示文稿转换为 PDF 上的文章。

 简体中文