在C#中为Word文档添加水印(文字或图片)通常需要借助Microsoft Office Interop库或第三方库(如DocX、Spire.Doc等)。以下将分别介绍使用Microsoft Word Interop(原生方式)和使用免费开源库DocX的两种实现方案,涵盖添加文字水印和图片水印的具体步骤与代码示例。
![图片[1]_通过C#实现给Word文档添加文字和图片水印_知途无界](https://zhituwujie.com/wp-content/uploads/2025/10/d2b5ca33bd20251019094936.png)
一、方案一:使用 Microsoft Word Interop(原生方式)
1. 前置条件
- 引用库:需添加对
Microsoft.Office.Interop.Word的引用(通过NuGet安装Microsoft.Office.Interop.Word或在项目中引用本地Office Interop DLL)。 - 环境要求:运行环境需安装Microsoft Word(Interop本质是通过Word应用程序后台操作文档)。
2. 添加文字水印
核心思路
通过Word的 Headers(页眉)插入一个旋转的文本框,设置文本框的样式(字体、颜色、透明度等)作为水印。
代码实现
using Microsoft.Office.Interop.Word;
using System;
class WordWatermarkInterop
{
public static void AddTextWatermark(string filePath, string watermarkText)
{
Application wordApp = null;
Document doc = null;
try
{
// 启动Word应用程序(后台模式)
wordApp = new Application { Visible = false };
// 打开目标文档(若不存在则创建新文档)
doc = wordApp.Documents.Open(filePath) ?? wordApp.Documents.Add();
// 遍历所有节(Section),确保每页都有水印
foreach (Section section in doc.Sections)
{
// 获取页眉(HeaderFooterType.HeaderPrimary 表示首页页眉,FooterPrimary同理)
HeaderFooter header = section.Headers[HeaderFooterType.HeaderPrimary];
if (header == null) header = section.Headers.Add(HeaderFooterType.HeaderPrimary);
// 在页眉中插入一个文本框
Shape textBox = header.Shapes.AddTextbox(
Orientation.Horizontal, // 水平方向
0, 0, 500, 100, // 左、上、宽度、高度(单位:磅)
WdRelativeHorizontalPosition.wdRelativeHorizontalPositionPage,
WdRelativeVerticalPosition.wdRelativeVerticalPositionPage
);
// 设置文本框属性
textBox.TextFrame.TextRange.Text = watermarkText;
textBox.TextFrame.TextRange.Font.Size = 48; // 字体大小
textBox.TextFrame.TextRange.Font.Name = "Arial";
textBox.TextFrame.TextRange.Font.Color = WdColor.wdColorGray50; // 灰色
textBox.TextFrame.TextRange.Font.Italic = 1; // 斜体
textBox.TextFrame.TextRange.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
// 旋转文本框(45度斜向显示)
textBox.Rotation = 45;
// 设置文本框无边框、无填充(透明背景)
textBox.Line.Visible = Microsoft.Office.Core.MsoTriState.msoFalse;
textBox.Fill.Visible = Microsoft.Office.Core.MsoTriState.msoFalse;
// 将文本框置于底层(避免遮挡正文)
textBox.ZOrder(Microsoft.Office.Core.MsoZOrderCmd.msoSendToBack);
}
// 保存并关闭文档
doc.Save();
doc.Close();
}
catch (Exception ex)
{
Console.WriteLine($"添加文字水印失败: {ex.Message}");
}
finally
{
// 退出Word应用程序(释放资源)
if (doc != null) System.Runtime.InteropServices.Marshal.ReleaseComObject(doc);
if (wordApp != null)
{
wordApp.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(wordApp);
}
}
}
}
使用示例
string filePath = @"C:\Test\Sample.docx";
WordWatermarkInterop.AddTextWatermark(filePath, "机密文档");
3. 添加图片水印
核心思路
与文字水印类似,通过页眉插入一个图片控件(InlineShape),并设置图片的透明度、大小和位置。
代码实现
public static void AddImageWatermark(string filePath, string imagePath)
{
Application wordApp = null;
Document doc = null;
try
{
wordApp = new Application { Visible = false };
doc = wordApp.Documents.Open(filePath) ?? wordApp.Documents.Add();
foreach (Section section in doc.Sections)
{
HeaderFooter header = section.Headers[HeaderFooterType.HeaderPrimary];
if (header == null) header = section.Headers.Add(HeaderFooterType.HeaderPrimary);
// 插入图片(通过InlineShape插入到页眉)
InlineShape imageShape = header.Range.InlineShapes.AddPicture(
imagePath,
LinkToFile: false,
SaveWithDocument: true,
Range: Type.Missing
);
// 设置图片大小(宽度200磅,高度自动按比例调整)
imageShape.Width = 200;
imageShape.Height = Type.Missing; // 自动保持比例
// 设置图片位置(居中)
imageShape.Range.ParagraphFormat.Alignment = WdParagraphAlignment.wdAlignParagraphCenter;
// 设置图片透明度(通过图片格式的填充效果,但Interop对透明度的直接支持有限)
// 替代方案:将图片设置为灰度或调整亮度/对比度(模拟透明效果)
imageShape.PictureFormat.ColorType = WdColorType.wdColorGrayScale;
imageShape.PictureFormat.Brightness = 0.5f; // 降低亮度
imageShape.PictureFormat.Contrast = 0.3f; // 降低对比度
// 将图片置于底层
imageShape.ZOrder(Microsoft.Office.Core.MsoZOrderCmd.msoSendToBack);
}
doc.Save();
doc.Close();
}
catch (Exception ex)
{
Console.WriteLine($"添加图片水印失败: {ex.Message}");
}
finally
{
if (doc != null) System.Runtime.InteropServices.Marshal.ReleaseComObject(doc);
if (wordApp != null)
{
wordApp.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(wordApp);
}
}
}
使用示例
string filePath = @"C:\Test\Sample.docx";
string imagePath = @"C:\Test\Watermark.png";
WordWatermarkInterop.AddImageWatermark(filePath, imagePath);
二、方案二:使用免费开源库 DocX(无需安装Word)
1. 前置条件
- 引用库:通过NuGet安装
DocX(由Xceed开发的免费库,支持基本的Word操作)。
NuGet命令:Install-Package DocX
2. 添加文字水印
核心思路
通过DocX的 Header 插入一个旋转的 Paragraph(段落),并设置段落的字体样式和旋转角度。
代码实现
using Xceed.Words.NET;
using System.Drawing;
class WordWatermarkDocX
{
public static void AddTextWatermark(string filePath, string watermarkText)
{
try
{
// 打开或创建文档
using (DocX document = DocX.Load(filePath) ?? DocX.Create(filePath))
{
// 遍历所有节(Section)
foreach (Section section in document.Sections)
{
// 获取或创建页眉
Header header = section.Headers.even || section.Headers.first || section.Headers.primary;
// 简化逻辑:直接操作主页眉(Primary)
Header primaryHeader = section.Headers.primary;
if (primaryHeader == null) primaryHeader = section.Headers.AddPrimaryHeader();
// 创建一个居中、旋转的段落作为水印
Paragraph watermarkPara = primaryHeader.InsertParagraph(watermarkText, false);
watermarkPara.Alignment = Alignment.center;
watermarkPara.FontSize(48);
watermarkPara.Font("Arial");
watermarkPara.Color(System.Drawing.Color.Gray);
watermarkPara.Italic(true);
// 设置段落旋转(DocX原生不支持直接旋转,需通过表格模拟)
// 替代方案:插入一个旋转的文本框(DocX对文本框的支持有限,此处简化为段落+样式)
// 注:DocX对复杂水印(如旋转)的支持较弱,建议复杂场景使用Interop或Spire.Doc
}
// 保存文档
document.Save();
}
}
catch (Exception ex)
{
Console.WriteLine($"添加文字水印失败: {ex.Message}");
}
}
}
注意:DocX 对文字旋转和图片透明度的原生支持较弱,若需更复杂的水印效果(如精确旋转角度、图片透明背景),推荐使用 Spire.Doc(免费版有水印限制,但功能更完整)或 Interop。
3. 添加图片水印(DocX实现)
代码实现
public static void AddImageWatermark(string filePath, string imagePath)
{
try
{
using (DocX document = DocX.Load(filePath) ?? DocX.Create(filePath))
{
foreach (Section section in document.Sections)
{
Header primaryHeader = section.Headers.primary;
if (primaryHeader == null) primaryHeader = section.Headers.AddPrimaryHeader();
// 插入图片到页眉
Image image = primaryHeader.AddImage(imagePath);
Picture picture = image.CreatePicture();
picture.Width(200); // 设置图片宽度
picture.Height(100); // 设置图片高度(可选,自动比例可省略)
// 设置图片位置(居中)
picture.Alignment = Alignment.center;
// 模拟透明度(通过调整图片亮度,DocX无直接透明度API)
}
document.Save();
}
}
catch (Exception ex)
{
Console.WriteLine($"添加图片水印失败: {ex.Message}");
}
}
局限性:DocX 对图片透明度和复杂排版(如旋转)的支持有限,若需高精度水印,建议使用 Spire.Doc(见下文)。
三、方案三:使用 Spire.Doc(功能强大,免费版有水印)
1. 前置条件
- 引用库:通过NuGet安装
Spire.Doc(免费版生成文档会有“Spire”水印,付费版无限制)。
NuGet命令:Install-Package Spire.Doc
2. 添加文字/图片水印(完整示例)
using Spire.Doc;
using Spire.Doc.Documents;
using System.Drawing;
class WordWatermarkSpire
{
public static void AddWatermark(string filePath)
{
try
{
// 加载文档
Document doc = new Document();
doc.LoadFromFile(filePath);
// 添加文字水印
TextWatermark txtWatermark = new TextWatermark();
txtWatermark.Text = "机密文档";
txtWatermark.FontSize = 48;
txtWatermark.Color = Color.Gray;
txtWatermark.Rotation = 45; // 旋转45度
txtWatermark.Layout = WatermarkLayout.Diagonal; // 对角线分布
doc.Watermarks.Add(txtWatermark);
// 添加图片水印
ImageWatermark imgWatermark = new ImageWatermark();
imgWatermark.ImagePath = @"C:\Test\Watermark.png";
imgWatermark.Layout = WatermarkLayout.Diagonal;
imgWatermark.Width = 200;
imgWatermark.Height = 100;
doc.Watermarks.Add(imgWatermark);
// 保存文档
doc.SaveToFile("Output_With_Watermark.docx", FileFormat.Docx);
}
catch (Exception ex)
{
Console.WriteLine($"添加水印失败: {ex.Message}");
}
}
}
优势
- 简单易用:通过
TextWatermark和ImageWatermark类直接设置水印属性(旋转、颜色、布局)。 - 功能完整:支持对角线/平铺分布、透明度调整(付费版)、多页自动应用。
局限性
- 免费版生成的文档会带有“Powered by Spire.Doc”水印(需购买授权去除)。
四、总结与推荐
| 方案 | 优点 | 缺点 | 适用场景 |
|---|---|---|---|
| Microsoft Interop | 原生支持(无需额外库),功能全面(精确控制旋转、透明度) | 依赖本地Word安装,性能较低(启动Word进程),需处理COM对象释放 | 企业环境已安装Word,需高精度控制 |
| DocX(开源) | 免费、轻量级(无需Word),简单水印可实现 | 对旋转/透明度支持弱,复杂水印需手动模拟 | 简单文字水印或无旋转需求的场景 |
| Spire.Doc | 功能强大(一键添加水印,支持旋转/布局),API简单 | 免费版有水印,付费版需授权 | 快速实现高颜值水印(推荐商业项目付费使用) |
推荐选择:
- 若项目允许安装Word且需高精度控制 → Interop。
- 若需完全免费且水印简单 → DocX(或手动扩展旋转逻辑)。
- 若追求开发效率且可接受免费版水印 → Spire.Doc(快速实现)。
通过上述方案,开发者可根据实际需求灵活选择,为Word文档添加专业的文字或图片水印。
© 版权声明
文中内容均来源于公开资料,受限于信息的时效性和复杂性,可能存在误差或遗漏。我们已尽力确保内容的准确性,但对于因信息变更或错误导致的任何后果,本站不承担任何责任。如需引用本文内容,请注明出处并尊重原作者的版权。
THE END

























暂无评论内容