/// <summary>
/// 设置Pdf水印
/// </summary>
/// <param name="filePath">pdf所在的文件完整路径</param>
/// <param name="outfilePath">生成水印的pdf文件完整路径</param>
/// <returns></returns>
public static bool SetWaterMark(string filePath, out string outfilePath)
{
PdfReader pdfReader = null;
PdfStamper pdfStamper = null;
FileStream fileStream = null;
try
{
string removePath = filePath.Substring(filePath.LastIndexOf("\\"));
string outputfilepath = filePath.Substring(0, filePath.Length - removePath.Length) + "\\" + Guid.NewGuid().ToString() + ".pdf";
pdfReader = new PdfReader(filePath);
fileStream = new FileStream(outputfilepath, FileMode.Create);
pdfStamper = new PdfStamper(pdfReader, fileStream);
int total = pdfReader.NumberOfPages + 1;
Rectangle psize = pdfReader.GetPageSize(1);
float width = psize.Width;
float height = psize.Height;
PdfContentByte content;
BaseFont font = BaseFont.CreateFont(@"C:\WINDOWS\Fonts\SIMFANG.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
PdfGState gs = new PdfGState();
for (int i = 1; i < total; i++)
{
//content = pdfStamper.GetOverContent(i);//在内容上方加水印
content = pdfStamper.GetUnderContent(i);//在内容下方加水印
//透明度
gs.FillOpacity = 0.3f;
content.SetGState(gs);
//content.SetGrayFill(0.3f);
//开始写入文本
content.BeginText();
content.SetColorFill(BaseColor.Black);
content.SetFontAndSize(font, 100);
content.SetTextMatrix(0, 0);
content.ShowTextAligned(Element.ALIGN_CENTER, "水印测试", width / 2 - 50, height / 2 - 50, 55);
content.EndText();
}
outfilePath = outputfilepath;
return true;
}
catch (Exception ex)
{
outfilePath = "";
return false;
}
finally
{
if (pdfStamper != null)
{
pdfStamper.Close();
}
if (pdfReader != null)
{
pdfReader.Close();
}
if (fileStream != null)
{
fileStream.Close();
fileStream.Dispose();
}
}
}