.Net iTextSharp 给Pdf添加图片水印

        /// 
        /// 设置pdf图片水印
        /// 
        /// 水印图片路径
        /// 需要添加水印的pdf文件
        /// 添加完成的pdf文件
        /// 
        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();
                }
            }
        }

 

你可能感兴趣的:(.Net,C#)