C#添加水印 C#使用iTextSharp添加PDF水印
恝置 人气:2想了解C#使用iTextSharp添加PDF水印的相关内容吗,恝置在本文为您仔细讲解C#添加水印的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:C#添加水印,iTextSharp添加PDF水印,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 = 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; } }
加载全部内容