在PowerPoint演示文稿中插入文本水印是保护版权并确保文档内容真实性的有效方式。利用Python,开发者通过简单的代码添加水印到PowerPoint幻灯片中,进行批量处理,允许精确控制水印的位置和外观,便于集成到更大的应用程序中。本文将演示如何使用Python插入文字水印到PowerPoint演示文稿。
本文所使用的方法需要用到Spire.Presentation for Python,PyPI:pip install spire.presentation
。
用Python添加文字水印到演示文稿
我们可以通过在幻灯片中添加带有选中保护的透明文本框,并在其中插入水印文字,来实现在PowerPoint演示文稿文字水印的添加。以下是操作步骤:
- 导入必要的类:
Presentation
,FileFormat
,RectangleF
,ShapeType
,FillFormatType
,Color
。 - 定义输入输出文件路径:
input_file
,output_file
。 - 加载PPT文档:
Presentation()
,LoadFromFile()
。 - 计算水印位置:
SlideSize.Size.Width
,SlideSize.Size.Height
。 - 添加矩形水印:
Shapes.AppendShape()
,RectangleF()
。 - 设置矩形样式:
FillType
,LineColor.Color
,Rotation
,SelectionProtection
,Line.FillType
。 - 添加文本至矩形:
TextFrame.Text
。 - 设置文本样式:
FillType
,SolidColor.Color
,FontHeight
。 - 保存与关闭文档:
SaveToFile()
,Dispose()
。
代码示例
from spire.presentation import Presentation, FileFormat, RectangleF, ShapeType, FillFormatType, Color
# 定义输入输出文件路径
input_file = "Sample.pptx"
output_file = "output/SingleTextWatermark.pptx"
# 创建并加载PPT文档
presentation = Presentation()
presentation.LoadFromFile(input_file)
# 计算水印位置
slide_width = presentation.SlideSize.Size.Width
slide_height = presentation.SlideSize.Size.Height
watermark_width = 336.4
watermark_height = 110.8
left = (slide_width - watermark_width) / 2
top = (slide_height - watermark_height) / 2
# 添加矩形形状作为水印
rect = RectangleF(left, top, watermark_width, watermark_height)
shape = presentation.Slides[0].Shapes.AppendShape(ShapeType.Rectangle, rect)
# 设置矩形样式
shape.Fill.FillType = FillFormatType.none
shape.ShapeStyle.LineColor.Color