一般情況下,在Word中新增文字水印僅支援新增一個文字字樣的水印,但在複雜的辦公環境中,由於對不同檔案的設計要求,需要在Word檔案中新增平鋪水印效果,即檔案中的水印文字以多行多列分佈的形式存在。本文將介紹如何來實現該水印效果的方法,下面是詳細步驟及方法。
1.可以在Visual Studio中開啟 【解決方案資源管理器】,滑鼠右鍵點選 【參照】,【管理NuGet包】,然後搜尋 【Free Spire.Doc】,點選【安裝】。等待程式安裝完成。
2.將以下內容複製到PM控制檯安裝:
Install-Package FreeSpire.Doc -Version 10.2
可通過手動 下載包 到本地,然後解壓,找到BIN資料夾下的Spire.Doc.dll。然後在Visual Studio中開啟「解決方案資源管理器」,滑鼠右鍵點選「參照」,「新增參照」,將本地路徑BIN資料夾下的dll檔案新增參照至程式。
在Word中新增多行文字水印時,實現的方法是通過在頁首中新增形狀藝術字,並通過多次複製形狀來模擬實現多行文字水印效果。以下是實現水印新增的主要程式碼步驟:
C#
using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; namespace MultiLineTextWatermark { class Program { static void Main(string[] args) { //載入Word檔案 Document doc = new Document(); doc.LoadFromFile("test.docx"); //建立形狀,並設定大小、水印文字、位置及樣式 ShapeObject shape = new ShapeObject(doc, ShapeType.TextPlainText); shape.Width = 60; shape.Height =15; shape.VerticalPosition = 25; shape.HorizontalPosition = 20; shape.Rotation = 320; shape.WordArt.Text = "草稿副本"; shape.WordArt.FontFamily = "宋體"; shape.FillColor = System.Drawing.Color.Red; shape.StrokeColor = System.Drawing.Color.Red; //遍歷所有section for (int n = 0; n < doc.Sections.Count; n++) { Section section = doc.Sections[n]; //獲取頁首 HeaderFooter header = section.HeadersFooters.Header; //新增段落到頁首 Paragraph paragraph1 = header.AddParagraph(); for (int i = 0; i < 5; i++) { for (int j = 0; j < 6; j++) { //複製形狀並設定多行多列位置 shape = (ShapeObject)shape.Clone(); shape.VerticalPosition = 50 + 150 * i; shape.HorizontalPosition = 20 + 160 * j; //新增形狀到段落 paragraph1.ChildObjects.Add(shape); } } } //儲存檔案 doc.SaveToFile("result.docx", FileFormat.Docx2013); System.Diagnostics.Process.Start("result.docx"); } } }
VB.NET
Imports Spire.Doc Imports Spire.Doc.Documents Imports Spire.Doc.Fields Namespace MultiLineTextWatermark Class Program Private Shared Sub Main(args As String()) '載入Word檔案 Dim doc As New Document() doc.LoadFromFile("test.docx") '建立形狀,並設定大小、水印文字、位置及樣式 Dim shape As New ShapeObject(doc, ShapeType.TextPlainText) shape.Width = 60 shape.Height = 15 shape.VerticalPosition = 25 shape.HorizontalPosition = 20 shape.Rotation = 320 shape.WordArt.Text = "草稿副本" shape.WordArt.FontFamily = "宋體" shape.FillColor = System.Drawing.Color.Red shape.StrokeColor = System.Drawing.Color.Red '遍歷所有section For n As Integer = 0 To doc.Sections.Count - 1 Dim section As Section = doc.Sections(n) '獲取頁首 Dim header As HeaderFooter = section.HeadersFooters.Header '新增段落到頁首 Dim paragraph1 As Paragraph = header.AddParagraph() For i As Integer = 0 To 4 For j As Integer = 0 To 5 '複製形狀並設定多行多列位置 shape = DirectCast(shape.Clone(), ShapeObject) shape.VerticalPosition = 50 + 150 * i shape.HorizontalPosition = 20 + 160 * j '新增形狀到段落 paragraph1.ChildObjects.Add(shape) Next Next Next '儲存檔案 doc.SaveToFile("result.docx", FileFormat.Docx2013) System.Diagnostics.Process.Start("result.docx") End Sub End Class End Namespace
水印效果:
—END—