利用iTextSharp组件给PDF文档添加图片水印,文字水印

最近在做关于PDF文档添加水印的功能,折腾了好久,终于好了。以下做个记录:

首先会用到iTextSharp组件,大家可以去官网下载,同时我也会在本文中附加进来。

代码中添加引用为:
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using iTextSharp.text.pdf;
using System.IO;
using iTextSharp.text; 
创建一个显示指定图片的pdf
/// <summary>
        /// 创建一个显示指定图片的pdf
        /// </summary>
        /// <param name="picPdfPath"></param>
        /// <param name="picPath"></param>
        /// <returns></returns>
        public static bool CreatePDFByPicstring picPdfPath,string picPath)
        {
            //新建一个文档
            Document doc = new Document);
            try
            {
                //建立一个书写器Writer)与document对象关联
                PdfWriter.GetInstancedoc, new FileStreampicPdfPath, FileMode.Create, FileAccess.ReadWrite));
                //打开一个文档
                doc.Open);
                //向文档中添加内容
                Image img = Image.GetInstancepicPath);
                //img.SetAbsolutePosition);
                doc.Addimg);
                return true;
            }
            catch Exception ex)
            {
                return false;
                throw ex;
            }
            finally
            {
                if doc != null)
                {
                    doc.Close);
                }
            }
 
        }

为PDF文档添加图片水印

/// <summary>
        /// 加图片水印
        /// </summary>
        /// <param name="inputfilepath"></param>
        /// <param name="outputfilepath"></param>
        /// <param name="ModelPicName"></param>
        /// <param name="top"></param>
        /// <param name="left"></param>
        /// <returns></returns>
        public static bool PDFWatermarkstring inputfilepath, string outputfilepath, string ModelPicName, float top, float left)
        {
            //throw new NotImplementedException);
            PdfReader pdfReader = null;
            PdfStamper pdfStamper = null;
            try
            {
                pdfReader = new PdfReaderinputfilepath);
 
                int numberOfPages = pdfReader.NumberOfPages;
 
                iTextSharp.text.Rectangle psize = pdfReader.GetPageSize1);
 
                float width = psize.Width;
 
                float height = psize.Height;
 
                pdfStamper = new PdfStamperpdfReader, new FileStreamoutputfilepath, FileMode.Create));
 
                PdfContentByte waterMarkContent;
 
                iTextSharp.text.Image image = iTextSharp.text.Image.GetInstanceModelPicName);
 
                image.GrayFill = 20;//透明度,灰色填充
                //image.Rotation//旋转
                //image.RotationDegrees//旋转角度
                //水印的位置 
                if left < 0)
                {
                    left = width/2 - image.Width + left;
                }
 
                //image.SetAbsolutePositionleft, height - image.Height) - top);
                image.SetAbsolutePositionleft, height/2 - image.Height) - top);
 
 
                //每一页加水印,也可以设置某一页加水印 
                for int i = 1; i <= numberOfPages; i++)
                {
                    //waterMarkContent = pdfStamper.GetUnderContenti);//内容下层加水印
                    waterMarkContent = pdfStamper.GetOverContenti);//内容上层加水印
 
                    waterMarkContent.AddImageimage);
                }
                //strMsg = "success";
                return true;
            }
            catch Exception ex)
            {
                throw ex;
                 
            }
            finally
            {
 
                if pdfStamper != null)
                    pdfStamper.Close);
 
                if pdfReader != null)
                    pdfReader.Close);
            }
        }

添加普通偏转角度文字水印

/// <summary>
        /// 添加普通偏转角度文字水印
        /// </summary>
        /// <param name="inputfilepath"></param>
        /// <param name="outputfilepath"></param>
        /// <param name="waterMarkName"></param>
        /// <param name="permission"></param>
        public static void setWatermarkstring inputfilepath, string outputfilepath,string waterMarkName)
        {
            PdfReader pdfReader = null;
            PdfStamper pdfStamper = null;
//获取所用权 PdfReader.unethicalreading = true; try { pdfReader = new PdfReaderinputfilepath); pdfStamper = new PdfStamperpdfReader, new FileStreamoutputfilepath, FileMode.Create)); int total = pdfReader.NumberOfPages + 1; iTextSharp.text.Rectangle psize = pdfReader.GetPageSize1); float width = psize.Width; float height = psize.Height; PdfContentByte content; BaseFont font = BaseFont.CreateFont@"C:WINDOWSFontsSIMFANG.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED); PdfGState gs = new PdfGState); for int i = 1; i < total; i++) { content = pdfStamper.GetOverContenti);//在内容上方加水印 //content = pdfStamper.GetUnderContenti);//在内容下方加水印 //透明度 gs.FillOpacity = 0.3f; content.SetGStategs); //content.SetGrayFill0.3f); //开始写入文本 content.BeginText); content.SetColorFillBaseColor.LIGHT_GRAY); content.SetFontAndSizefont, 100); content.SetTextMatrix0, 0); content.ShowTextAlignedElement.ALIGN_CENTER, waterMarkName, width / 2 - 50,height / 2 - 50, 55); //content.SetColorFillBaseColor.BLACK); //content.SetFontAndSizefont, 8); //content.ShowTextAlignedElement.ALIGN_CENTER, waterMarkName, 0, 0, 0); content.EndText); } }catch Exception ex) { throw ex; } finally { if pdfStamper != null) pdfStamper.Close); if pdfReader != null) pdfReader.Close); } }

 添加倾斜水印

/// <summary>
        /// 添加倾斜水印
        /// </summary>
        /// <param name="inputfilepath"></param>
        /// <param name="outputfilepath"></param>
        /// <param name="waterMarkName"></param>
        /// <param name="userPassWord"></param>
        /// <param name="ownerPassWord"></param>
        /// <param name="permission"></param>
        public static void setWatermarkstring inputfilepath, string outputfilepath, string waterMarkName, string userPassWord, string ownerPassWord, int permission)
        {
            PdfReader pdfReader = null;
            PdfStamper pdfStamper = null;
            try
            {
                pdfReader = new PdfReaderinputfilepath);
                pdfStamper = new PdfStamperpdfReader, new FileStreamoutputfilepath, FileMode.Create));
                // 设置密码   
                //pdfStamper.SetEncryptionfalse,userPassWord, ownerPassWord, permission); 
 
                int total = pdfReader.NumberOfPages + 1;
                PdfContentByte content;
                BaseFont font = BaseFont.CreateFont@"C:WINDOWSFontsSIMFANG.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
                PdfGState gs = new PdfGState);
                gs.FillOpacity = 0.2f;//透明度
 
                int j = waterMarkName.Length;
                char c;
                int rise = 0;
                for int i = 1; i < total; i++)
                {
                    rise = 500;
                    content = pdfStamper.GetOverContenti);//在内容上方加水印
                    //content = pdfStamper.GetUnderContenti);//在内容下方加水印
                     
                    content.BeginText);
                    content.SetColorFillBaseColor.DARK_GRAY);
                    content.SetFontAndSizefont, 50);
                    // 设置水印文字字体倾斜 开始 
                    if j >= 15)
                    {
                        content.SetTextMatrix200, 120);
                        for int k = 0; k < j; k++)
                        {
                            content.SetTextRiserise);
                            c = waterMarkName[k];
                            content.ShowTextc + "");
                            rise -= 20;
                        }
                    }
                    else
                    {
                        content.SetTextMatrix180, 100);
                        for int k = 0; k < j; k++)
                        {
                            content.SetTextRiserise);
                            c = waterMarkName[k];
                            content.ShowTextc + "");
                            rise -= 18;
                        }
                    }
                    // 字体设置结束 
                    content.EndText);
                    // 画一个圆 
                    //content.Ellipse250, 450, 350, 550);
                    //content.SetLineWidth1f);
                    //content.Stroke); 
                } 
 
            }
            catch Exception ex)
            {
                throw ex;
            }
            finally
            {
 
                if pdfStamper != null)
                    pdfStamper.Close);
 
                if pdfReader != null)
                    pdfReader.Close);
            }
        }

调用方法的例子:

string path = "D://my.pdf";
               HtmlToPDFUtil.HtmlToPdfRequest.Url.AbsoluteUri, path);
               //HtmlToPDFUtil.HtmlToPdfsbUrlList.ToString), path);
               PDFSetWaterMark.PDFWatermarkpath, "D://my.pdf", Server.MapPath"/HtmlToPdf/Tools/sy.bmp"), 0, 0);
               PDFSetWaterMark.setWatermark"D://my.pdf", "D://my2.pdf", "TEST");
               //PDFSetWaterMark.setWatermark"D://my.pdf", "D://my2.pdf", "TEST", "", "", 1);

Published by

风君子

独自遨游何稽首 揭天掀地慰生平

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注