這篇文章主要為大家詳細介紹了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; } }