iTextSharp简单生成pdf和操作pdf添加水印

转载 2016年08月30日 17:57:06

iTextSharp,a .NET PDF library 。iTextSharp.dll 下载地址 https://sourceforge.net/projects/itextsharp/

iText is a PDF library that allows you to CREATE, ADAPT, INSPECT and MAINTAIN documents in the Portable Document Format (PDF):
- Generate documents and reports based on data from an XML file or a database
- Create maps and books, exploiting numerous interactive features available in PDF
- Add bookmarks, page numbers, watermarks, and other features to existing PDF documents
- Split or concatenate pages from existing PDF files
- Fill out interactive forms
- Serve dynamically generated or manipulated PDF documents to a web browser

iText is used by Java, .NET, Android and GAE developers to enhance their applications with PDF functionality.
iTextSharp is the .NET port.

Several iText engineers are actively supporting the project on on StackOverflow: http://stackoverflow.com/questions/tagged/itext

IMPORTANT NOTICE: AS OF 2016-03-14, ITEXTSHARP DOWNLOADS AND SOURCE CODE WILL ONLY BE AVAILABLE ON GITHUB: http://github.com/itext


以下转自 http://www.cnblogs.com/LL-723/archive/2013/12/25/3490699.html (先引入itextsharp.dll , 5.5.9.0版大小是3.86M)

public class PDFSetWaterMark
    {
        /// <summary>
        /// 创建一个显示指定图片的pdf
        /// </summary>
        /// <param name="picPdfPath"></param>
        /// <param name="picPath"></param>
        /// <returns></returns>
        public static bool CreatePDFByPic(string picPdfPath,string picPath)
        {
            //新建一个文档
            Document doc = new Document();
            try
            {
                //建立一个书写器(Writer)与document对象关联
                PdfWriter.GetInstance(doc, new FileStream(picPdfPath, FileMode.Create, FileAccess.ReadWrite));
                //打开一个文档
                doc.Open();
                //向文档中添加内容
                Image img = Image.GetInstance(picPath);
                //img.SetAbsolutePosition();
                doc.Add(img);
                return true;
            }
            catch (Exception ex)
            {
                return false;
                throw ex;
            }
            finally
            {
                if (doc != null)
                {
                    doc.Close();
                }
            }

        }

        /// <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 PDFWatermark(string inputfilepath, string outputfilepath, string ModelPicName, float top, float left)
        {
            //throw new NotImplementedException();
            PdfReader pdfReader = null;
            PdfStamper pdfStamper = null;
            try
            {
                pdfReader = new PdfReader(inputfilepath);

                int numberOfPages = pdfReader.NumberOfPages;

                iTextSharp.text.Rectangle psize = pdfReader.GetPageSize(1);

                float width = psize.Width;

                float height = psize.Height;

                pdfStamper = new PdfStamper(pdfReader, new FileStream(outputfilepath, FileMode.Create));

                PdfContentByte waterMarkContent;

                iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(ModelPicName);

                image.GrayFill = 20;//透明度,灰色填充
                //image.Rotation//旋转
                //image.RotationDegrees//旋转角度
                //水印的位置 
                if (left < 0)
                {
                    left = width/2 - image.Width + left;
                }

                //image.SetAbsolutePosition(left, (height - image.Height) - top);
                image.SetAbsolutePosition(left, (height/2 - image.Height) - top);


                //每一页加水印,也可以设置某一页加水印 
                for (int i = 1; i <= numberOfPages; i++)
                {
                    //waterMarkContent = pdfStamper.GetUnderContent(i);//内容下层加水印
                    waterMarkContent = pdfStamper.GetOverContent(i);//内容上层加水印

                    waterMarkContent.AddImage(image);
                }
                //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 setWatermark(string inputfilepath, string outputfilepath,string waterMarkName)
        {
            PdfReader pdfReader = null;
            PdfStamper pdfStamper = null;
            try
            {
                pdfReader = new PdfReader(inputfilepath);
                pdfStamper = new PdfStamper(pdfReader, new FileStream(outputfilepath, FileMode.Create));
                int total = pdfReader.NumberOfPages + 1;
                iTextSharp.text.Rectangle psize = pdfReader.GetPageSize(1);
                float width = psize.Width;
                float height = psize.Height;
                PdfContentByte content;
                BaseFont font = BaseFont.CreateFont(@"C:\WINDOWS\Fonts\SIMFANG.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
                PdfGState gs = new PdfGState();
                for (int i = 1; i < total; i++) 
                {
                    content = pdfStamper.GetOverContent(i);//在内容上方加水印
                    //content = pdfStamper.GetUnderContent(i);//在内容下方加水印
                    //透明度
                    gs.FillOpacity = 0.3f;
                    content.SetGState(gs);
                    //content.SetGrayFill(0.3f);
                    //开始写入文本
                    content.BeginText();
                    content.SetColorFill(BaseColor.LIGHT_GRAY);
                    content.SetFontAndSize(font, 100);
                    content.SetTextMatrix(0, 0);
                    content.ShowTextAligned(Element.ALIGN_CENTER, waterMarkName, width / 2 - 50,height / 2 - 50, 55);
                    //content.SetColorFill(BaseColor.BLACK);
                    //content.SetFontAndSize(font, 8);
                    //content.ShowTextAligned(Element.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 setWatermark(string inputfilepath, string outputfilepath, string waterMarkName, string userPassWord, string ownerPassWord, int permission)
        {
            PdfReader pdfReader = null;
            PdfStamper pdfStamper = null;
            try
            {
                pdfReader = new PdfReader(inputfilepath);
                pdfStamper = new PdfStamper(pdfReader, new FileStream(outputfilepath, FileMode.Create));
                // 设置密码   
                //pdfStamper.SetEncryption(false,userPassWord, ownerPassWord, permission); 

                int total = pdfReader.NumberOfPages + 1;
                PdfContentByte content;
                BaseFont font = BaseFont.CreateFont(@"C:\WINDOWS\Fonts\SIMFANG.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.GetOverContent(i);//在内容上方加水印
                    //content = pdfStamper.GetUnderContent(i);//在内容下方加水印
                    
                    content.BeginText();
                    content.SetColorFill(BaseColor.DARK_GRAY);
                    content.SetFontAndSize(font, 50);
                    // 设置水印文字字体倾斜 开始 
                    if (j >= 15)
                    {
                        content.SetTextMatrix(200, 120);
                        for (int k = 0; k < j; k++)
                        {
                            content.SetTextRise(rise);
                            c = waterMarkName[k];
                            content.ShowText(c + "");
                            rise -= 20;
                        }
                    }
                    else
                    {
                        content.SetTextMatrix(180, 100);
                        for (int k = 0; k < j; k++)
                        {
                            content.SetTextRise(rise);
                            c = waterMarkName[k];
                            content.ShowText(c + "");
                            rise -= 18;
                        }
                    }
                    // 字体设置结束 
                    content.EndText();
                    // 画一个圆 
                    //content.Ellipse(250, 450, 350, 550);
                    //content.SetLineWidth(1f);
                    //content.Stroke(); 
                } 

            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {

                if (pdfStamper != null)
                    pdfStamper.Close();

                if (pdfReader != null)
                    pdfReader.Close();
            }
        }

    }

调用的例子:

string path = "E://3.pdf";
                HtmlToPDFUtil.HtmlToPdf(Request.Url.AbsoluteUri, path);
                //HtmlToPDFUtil.HtmlToPdf(sbUrlList.ToString(), path);
                PDFSetWaterMark.PDFWatermark(path, "E://3-1.pdf", Server.MapPath("/HtmlToPdf/Tools/sy.bmp"), 0, 0);
                PDFSetWaterMark.setWatermark("E://3-1.pdf", "E://3-2.pdf", "ssss");
                //PDFSetWaterMark.setWatermark("E://3-2.pdf", "E://3-3.pdf", "sssss", "", "", 1);



C# 给PDF文件添加水印

C# 给PDF文件添加水印
  • Eiceblue
  • Eiceblue
  • 2015年10月29日 16:22
  • 2777

ITextSharp 使用

ITextSharp是一个在C#平台下操作pdf的一个工具dll 但是,自从4.1.6版本之后的ITextSharp的license变成了AGPL,所以不能商用。所以说version 4.1.6就是...
  • cindoralla
  • cindoralla
  • 2016年03月21日 11:48
  • 4308

itextSharp研究心得

最近在工作中遇到一个问题,客户要求将系统中的表格全部导出成PDF格式。经过搜索,基本是三种思路: 直接用byte写PDF文件。(算你狠,霸王硬上弓)通过Com组件转换。以Adobe ...
  • layman1024
  • layman1024
  • 2017年07月07日 10:09
  • 361

C#使用itextsharp生成PDF文件

前言 前段时间公司需要实现一个PDF文件下载功能,涉及到页眉页脚,段落,图片的生成。遂使用itextsharp来实现这一功能,但是itextsharp功能强大,类库繁多,特别是5.0版本后关于页眉页...
  • c79651760
  • c79651760
  • 2017年02月22日 10:20
  • 1720

iTextSharp

  • 2013年12月09日 22:41
  • 6.99MB
  • 下载

C#使用iTextSharp为pdf添加文字

1.项目添加dll 下载地址 2.代码添加引用 using iTextSharp.text; using iTextSharp.text.pdf; 3. PdfR...
  • u013795673
  • u013795673
  • 2016年01月07日 09:14
  • 2903

基于iTextSharp(C#)创建PDF文件

基于iTextSharp控件(C#)创建PDF文件
  • Neil_Pan
  • Neil_Pan
  • 2016年07月01日 00:59
  • 1036

C#用iTextSharp导出PDF到页面

using iTextSharp.text; using iTextSharp.text.pdf;    //导出PDF  public ActionResult ImportFile(string ...
  • u011511086
  • u011511086
  • 2016年09月18日 15:26
  • 1577

c#使用itextsharp的实例

在编程中用到将一些报告生成pdf文件,用到了itextsharp
  • zhangjw152
  • zhangjw152
  • 2014年08月14日 16:00
  • 1540

用iText给pdf添加水印图片

/**     * 给pdf文件添加水印     * @param InPdfFile 要加水印的原pdf文件路径     * @param outPdfFile 加了水印后要输出的路径   ...
  • huiwenjie168
  • huiwenjie168
  • 2012年05月30日 16:59
  • 19096
内容举报
返回顶部
收藏助手
不良信息举报
您举报文章:iTextSharp简单生成pdf和操作pdf添加水印
举报原因:
原因补充:

(最多只允许输入30个字)