在工作中遇到个需求,需要给Word文档添加水印搞了一天才搞出来,所以在此记录一下:
重点用到了E-iceblue官网下载到的:Spire.dll
using Spire.Doc;
using Spire.Doc.Documents;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
namespace WayGo.GZ.Common
{
public class WordSetWaterMark
{
private string loadpath
{
get;
set;
}
private string filetype
{
get;
set;
}
/// <summary>
/// 流程正文添加水印
/// </summary>
/// <param name="wordpath">加载的文档路径</param>
/// <param name="waterword">添加水印文字</param>
/// <returns></returns>
public static bool WordSetWaterExecute(string wordpath, string waterword, string type)
{
try
{
if (type == "doc")
{
//word 添加水印
Document doc = new Document();
doc.LoadFromFile(wordpath);
TextWatermark txtWatermark = new TextWatermark();
txtWatermark.Text = waterword;
txtWatermark.FontSize = 30;
txtWatermark.Layout = WatermarkLayout.Diagonal;
doc.Watermark = txtWatermark;
Thread newThread = new Thread(new ParameterizedThreadStart(saveFileName));
newThread.SetApartmentState(ApartmentState.STA);//设置这个参数,指示应用程序的COM线程模型 是 单线程单元
newThread.Start(doc);
return true;
}
else
{
WordSetWaterMark model = new WordSetWaterMark();
model.filetype = type;
model.loadpath = wordpath;
Thread newThread = new Thread(new ParameterizedThreadStart(saveFileName));
newThread.SetApartmentState(ApartmentState.STA);//设置这个参数,指示应用程序的COM线程模型 是 单线程单元
newThread.Start(model);
return true;
}
}
catch (Exception e)
{
throw;
}
}
//打开保存路径
private static void saveFileName(object document)
{
Document doc = (Document)document;
SaveFileDialog sfd = new SaveFileDialog();
//设置文件类型
sfd.Filter = "(*.doc)|*.doc";
//设置默认文件类型显示顺序
sfd.FilterIndex = 1;
//保存对话框是否记忆上次打开的目录
sfd.RestoreDirectory = true;
//点了保存按钮进入
if (sfd.ShowDialog() == DialogResult.OK)
{
string localFilePath = sfd.FileName.ToString(); //获得文件路径
//添加水印保存
doc.SaveToFile(localFilePath);
}
}
//非doc 文件打开保存路径
private static void saveFileName1(object word)
{
WordSetWaterMark model = (WordSetWaterMark)word;
SaveFileDialog sfd = new SaveFileDialog();
//设置文件类型
sfd.Filter = "(*." + model.filetype + ")|*." + model.filetype;
//设置默认文件类型显示顺序
sfd.FilterIndex = 1;
//保存对话框是否记忆上次打开的目录
sfd.RestoreDirectory = true;
//点了保存按钮进入
if (sfd.ShowDialog() == DialogResult.OK)
{
string localFilePath = sfd.FileName.ToString(); //获得文件路径
FileStream RFile = new FileStream(model.loadpath, FileMode.Open, FileAccess.Read);
FileStream WFile = new FileStream(localFilePath, FileMode.Create, FileAccess.Write);
Byte[] buffer = new byte[RFile.Length];
while (true)
{
int r = RFile.Read(buffer, 0, buffer.Length);
if (r == 0)
{
break;
}
WFile.Write(buffer, 0, r);
}
RFile.Close();
WFile.Close();
}
}
}
}
测试:
string path="需要添加水印文件的绝对地址";
string waterword ="我是水印";
string type="doc";
//调用
WordSetWaterMark.WordSetWaterExecute(path, waterword , type);