.Net iTextSharp 给Pdf添加图片水印

        /// <summary>
        /// 设置pdf图片水印
        /// </summary>
        /// <param name="imgPath">水印图片路径</param>
        /// <param name="filePath">需要添加水印的pdf文件</param>
        /// <param name="outfilePath">添加完成的pdf文件</param>
        /// <returns></returns>
        public static bool SetImgWaterMark(string fileDirPath,string filePath, out string outfilePath)
        {
            PdfReader pdfReader = null;
            PdfStamper pdfStamper = null;
            FileStream fileStream = null;
            try
            {
                string outputfilepath = "D:\\" + Guid.NewGuid().ToString() + ".pdf";
                pdfReader = new PdfReader(filePath);
                fileStream = new FileStream(outputfilepath, FileMode.Create);
                pdfStamper = new PdfStamper(pdfReader, fileStream);
                int total = pdfReader.NumberOfPages;
                Rectangle psize = pdfReader.GetPageSize(1);
                float width = psize.Width;
                float height = psize.Height;
                PdfContentByte content;
                //获取水印图片
               Image image = Image.GetInstance(imgPath);
                image.SetAbsolutePosition((width / 2)-300, (height / 2)-300);
                for (int i = 1; i <= total; i++)
                {
                    //content = pdfStamper.GetOverContent(i);//在内容上方加水印
                    content = pdfStamper.GetUnderContent(i);//在内容下方加水印
                    content.AddImage(image);
                }
                outfilePath = outputfilepath;
                return true;
            }
            catch (Exception ex)
            {
                outfilePath = "";
                return false;
            }
            finally
            {
                if (pdfStamper != null)
                {
                    pdfStamper.Close();
                }
                if (pdfReader != null)
                {
                    pdfReader.Close();
                }
                if (fileStream != null)
                {
                    fileStream.Close();
                    fileStream.Dispose();
                }
            }
        }

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值