首页 > 技术文章 > c# 在word文档与pdf中加入水印

lvdong-1986 2015-02-06 14:13 原文

需求:在word、pdf文档中要在指定位置加入水印,由于位置要灵活所以不能直接使用操作word和pdf来完成,需要先将其转换成图片,然后将水印图片与转换后的图片合成这样就可以任意指定水印的位置。最后将合成后的图片插入新的pdf中,因为word有页眉页脚所以不能最后插入word。

测试界面如下:

选择要添加水印的文档位置,选择输出路径,选择要转换的文档类型,最后点击“生成”,转换完成后提示“生成成功!”。

关键代码:

public static void AddBarcodeToPdf(string inputPath, string outputPath, string barcodePath, DocType docType,
int locationX, int locationY, int width, int height)
{
string docImgPath= Application.StartupPath+"\\DocImg\\";//转换成的文档图片存放的路径
if(!Directory.Exists(docImgPath))
{
Directory.CreateDirectory(docImgPath);
}
IDocToImage docToImage;//通过选择的文档类型实例化对应的对象
switch (docType)
{
case DocType.Word:
docToImage = WordToImage.Instance;
break;
case DocType.Pdf:
docToImage = PdfToImage.Instance;
break;
default:
docToImage = WordToImage.Instance;
break;

}
docToImage.ConvertDocToImage(inputPath, docImgPath);//将文档转换成图片的方法,该方法在源代码中不详述
string docBarcodeImgPath = Application.StartupPath + "\\DocBarcodeImg\\";//图片与水印图片合成后的图片存放路径
if (!Directory.Exists(docBarcodeImgPath))
{
Directory.CreateDirectory(docBarcodeImgPath);
}
string[] imagePaths = Directory.GetFiles(docImgPath);
CombineImage(imagePaths, barcodePath, docBarcodeImgPath,locationX, locationY, width, height);//图片与水印图片合成方法
imagePaths=Directory.GetFiles(docBarcodeImgPath);
InsertPictrueToPdf(imagePaths, outputPath);//将图片插入新的pdf中

}

具体代码地址:http://pan.baidu.com/s/1qW7H9LU

推荐阅读