1. 程式人生 > >C# 如何給PowerPoint文檔添加文本水印和圖片水印

C# 如何給PowerPoint文檔添加文本水印和圖片水印

C# PowerPoint 文本水印 圖片水印

當演示PowerPoint文檔或是將PowerPoint文檔分享給他人的時候,我們可能想要給它添加上文本水印(如公司名稱)和圖片水印(如公司Logo),來讓別人明確的知道該文檔的版權相關信息。其實在Microsoft PowerPoint中其實是沒有文本水印和圖片水印的概念的,但我們可以通過一些方法來達到水印的效果。這篇文章將介紹如何使用C#和Free Spire.Presentation組件和C#給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等功能,如果你對它感興趣,不妨自己試一試。

C# 如何給PowerPoint文檔添加文本水印和圖片水印