当演示PowerPoint文档或是将PowerPoint文档分享给他人的时候,我们可能想要给它添加上文本水印(如公司名称)和图片水印(如公司Logo),来让别人明确的知道该文档的版权相关信息。其实在Microsoft PowerPoint中是没有文本水印和图片水印的概念的,但我们可以通过一些方法来达到水印的效果。这篇文章将介绍如何使用C#和Free Spire.Presentation组件给PowerPoint文档添加文本水印和图片水印。

原PowerPoint文档截图:

说明
在使用以下代码前,需要在visual studio中创建一个C#应用程序,下载Free Spire.Presentation, 从安装文件夹下引用Spire.Presentation.dll到工程中(安装后,安装文件夹下有很多demo示例,可以帮助我们快速上手。如果不需要参考demo,也可以直接通过NuGet Package Manager搜索Free Spire.Presentation,点击安装,会将dll文件自动引用到程序中)。

第一部分 添加文本水印
通过在幻灯片母版添加形状,给形状填充文本和锁定形状的方式,可以达到给每一张幻灯片添加文本水印的效果。如果只想给指定幻灯片添加水印,就不用幻灯片母版,直接通过presentation.Slides[index]获取指定的幻灯片,然后用同样的方式就可以了。

//加载PowerPoint文档Presentation presentation = new Presentation();presentation.LoadFromFile("Input.pptx");RectangleF rect = new RectangleF(340, 150, 300, 200);//添加文本水印到幻灯片母版foreach (IMasterSlide masterSlide in presentation.Masters){ //添加矩形到幻灯片母版的指定位置 IAutoShape shape = masterSlide.Shapes.AppendShape(Spire.Presentation.ShapeType.Rectangle, rect); //添加文本到矩形 shape.TextFrame.Text = "E-iceblue"; //设置文本的颜色和字体大小 TextRange textRange = shape.TextFrame.TextRange; textRange.Fill.FillType = Spire.Presentation.Drawing.FillFormatType.Solid; textRange.Fill.SolidColor.Color = Color.FromArgb(120, Color.Gray); textRange.FontHeight = 55; //设置矩形的填充类型为无填充 shape.Fill.FillType = FillFormatType.None; //设置矩形的旋转角度 shape.Rotation = -45; //锁定矩形使其不能被选择 shape.Locking.SelectionProtection = true; //设置矩形的边框为无边框 shape.Line.FillType = FillFormatType.None;}//保存文档presentation.SaveToFile("TextWatermark.pptx", Spire.Presentation.FileFormat.Pptx2010);System.Diagnostics.Process.Start("TextWatermark.pptx");

文本水印效果:

第二部分 添加图片水印
通过给幻灯片母版添加图片,设置图片的透明度和锁定图片的方式,可以达到给每一张幻灯片添加图片水印的效果。当然也可以只给指定的幻灯片添加图片水印。

//加载PowerPoint文档Presentation presentation = new Presentation();presentation.LoadFromFile("Input.pptx");RectangleF rect = new RectangleF(340, 150, 200, 200);//添加图片水印到幻灯片母版foreach (IMasterSlide masterSlide in presentation.Masters){ //添加图片到幻灯片母版的指定位置 IEmbedImage image = masterSlide.Shapes.AppendEmbedImage(ShapeType.Rectangle, @"logo.png", rect); //设置图片的透明度 image.PictureFill.Picture.Transparency = 70; //锁定图片使其不能被选择 image.ShapeLocking.SelectionProtection = true; //设置图片的边框为无边框 image.Line.FillType = FillFormatType.None;}//保存文档presentation.SaveToFile("ImageWatermark.pptx", FileFormat.Pptx2010);System.Diagnostics.Process.Start("ImageWatermark.pptx");

图片水印效果:

总结
由于篇幅问题,这篇文章主要只介绍了水印功能,实际上除了添加水印以外,Free Spire.Presentation组件还支持转换PowerPoint文档到其他格式、文档加密解密、添加超链接、合并和拆分文档,文本替换、插入、提取视频和音频、动画设置、创建和编辑表格、创建和编辑图表、打印powerpoint等功能,如果你对它感兴趣,不妨自己试一试。