C#使用iTextSharp添加PDF水印

使用的是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 = 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;

}

}

以上是 C#使用iTextSharp添加PDF水印 的全部内容, 来源链接: utcz.com/z/324965.html

回到顶部