C#添加文字水印

使用的是iTextSharp添加PDF水印,由于是接口动态生成PDF,所以采用的是全部是内存流的形式,而且水印是平铺是。iTextSharp版本是5.5

 /// <summary>
/// 添加倾斜水印
/// </summary>
/// <param name="pdfStream">pdf文件流</param>
/// <param name="waterMarkName">水印字符串</param>
/// <param name="width">页面宽度</param>
/// <param name="height">页面高度</param>
public MemoryStream SetWaterMark(MemoryStream pdfStream, string waterMarkName, float width, float height)
{
try
{
int fontSize = ;//设置字体大小
int span = ;//设置垂直位移
MemoryStream outStream = new MemoryStream();
PdfReader pdfReader = new PdfReader(pdfStream);
PdfStamper pdfStamper = new PdfStamper(pdfReader, outStream);
pdfStamper.Writer.CloseStream = false;
int total = pdfReader.NumberOfPages + ;
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 = ;
string spanString = " ";//水平位移
for (int i = ; 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 = ; w < widthNumber; w++)
{
for (int h = ; h <= heightNumbert; h++)
{
int yleng = rise * h;
content.SetTextMatrix(w * panleWith, yleng);//x,y设置水印开始的绝对左边,以左下角为x,y轴的起点
for (int k = ; 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;
}
}
上一篇:Java中的Arrays类使用详解


下一篇:Css定位总结