这篇文章主要为大家详细介绍了C#使用iTextSharp添加PDF水印的相关资料,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
使用的是iTextSharp添加PDF水印,由于是接口动态生成PDF,所以采用的是全部是内存流的形式,而且水印是平铺是。iTextSharp版本是5.5。///
/// 添加倾斜水印
///
/// pdf文件流
/// 水印字符串
/// 页面宽度
/// 页面高度
public MemoryStream SetWaterMark(MemoryStream pdfStream, string waterMarkName, float width, float height)
{
try
{
int fontSize = 50;//设置字体大小
int span = 40;//设置垂直位移
MemoryStream outStream = new MemoryStream();
PdfReader pdfReader = new PdfReader(pdfStream);
PdfStamper pdfStamper = new PdfStamper(pdfReader, outStream);
pdfStamper.Writer.CloseStream = false;
int total = pdfReader.NumberOfPages + 1;
PdfContentByte content;
BaseFont font = BaseFont.CreateFont(@"C:\WINDOWS\Fonts\STCAIYUN.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);//华文云彩字体
PdfGState gs = new PdfGState();
gs.FillOpacity = 0.15f;//透明度
int waterMarkNameLenth = waterMarkName.Length;
char c;
int rise = 0;
string spanString = " ";//水平位移
for (int i = 1; i < total; i++)
{
rise = waterMarkNameLenth * span;
content = pdfStamper.GetOverContent(i);//在内容上方加水印
//content = pdfStamper.GetUnderContent(i);//在内容下方加水印
content.SetGState(gs);
content.BeginText();
content.SetColorFill(BaseColor.GREEN);
content.SetFontAndSize(font, fontSize);
int heightNumbert = (int)Math.Ceiling((decimal)height / (decimal)rise);//垂直重复的次数,进一发
int panleWith = (fontSize + span) * waterMarkNameLenth;
int widthNumber = (int)Math.Ceiling((decimal)width / (decimal)panleWith);//水平重复次数
// 设置水印文字字体倾斜 开始
for (int w = 0; w < widthNumber; w++)
{
for (int h = 1; h <= heightNumbert; h++)
{
int yleng = rise * h;
content.SetTextMatrix(w * panleWith, yleng);//x,y设置水印开始的绝对左边,以左下角为x,y轴的起点
for (int k = 0; k < waterMarkNameLenth; k++)
{
content.SetTextRise(yleng);//指定的y轴值处添加
c = waterMarkName[k];
content.ShowText(c + spanString);
yleng -= span;
}
}
}
content.EndText();
}
if (pdfStamper != null)
pdfStamper.Close();
if (pdfReader != null)
pdfReader.Close();
return outStream;
}
catch (Exception ex)
{
throw ex;
}
}