C#使用iTextSharp添加PDF水印

作者:袖梨 2022-06-25

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

 代码如下 复制代码

///

    /// 添加倾斜水印

    ///

    /// pdf文件流

    /// 水印字符串

    /// 页面宽度

    /// 页面高度

    publicMemoryStream SetWaterMark(MemoryStream pdfStream,stringwaterMarkName,floatwidth,floatheight)

    {

      try

      {

        intfontSize = 50;//设置字体大小

        intspan = 40;//设置垂直位移

        MemoryStream outStream =newMemoryStream();

        PdfReader pdfReader =newPdfReader(pdfStream);

        PdfStamper pdfStamper =newPdfStamper(pdfReader, outStream);

        pdfStamper.Writer.CloseStream =false;

        inttotal = pdfReader.NumberOfPages + 1;

        PdfContentByte content;

        BaseFont font = BaseFont.CreateFont(@"C:WINDOWSFontsSTCAIYUN.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);//华文云彩字体

        PdfGState gs =newPdfGState();

        gs.FillOpacity = 0.15f;//透明度

        intwaterMarkNameLenth = waterMarkName.Length;

        charc;

        intrise = 0;

        stringspanString =" ";//水平位移

        for(inti = 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);

          intheightNumbert = (int)Math.Ceiling((decimal)height / (decimal)rise);//垂直重复的次数,进一发

          intpanleWith = (fontSize + span) * waterMarkNameLenth;

          intwidthNumber = (int)Math.Ceiling((decimal)width / (decimal)panleWith);//水平重复次数

           

          // 设置水印文字字体倾斜 开始

          for(intw = 0; w < widthNumber; w++)

          {

            for(inth = 1; h <= heightNumbert; h++)

            {

              intyleng = rise * h;

              content.SetTextMatrix(w * panleWith, yleng);//x,y设置水印开始的绝对左边,以左下角为x,y轴的起点

              for(intk = 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();

 

        returnoutStream;

      }

      catch(Exception ex)

      {

        throwex;

      }

    }


相关文章

精彩推荐