itextsharp 利用模板批量打印PDF

来源:互联网 发布:微信封锁淘宝口令 编辑:程序博客网 时间:2024/06/07 00:23

1首先制作模板 利用 Adobe Acrobat 9 Pro 工具制作PDF模板,可百度下载 1点击 表单 =》添加或编辑域 2设置文本名称 



2在vs2013项目中 管理packages 包 搜素 iTextSharp 下载引用iTextSharp.5.5.11   ; 如果html to pdf 可以引用 itextsharp.xmlworker.5.5.11 


3编写核心类 


4编写模板单条打印pdf文件

        /// <summary>
        /// 根据模板单条打印pdf文件
        /// </summary>
        /// <param name="templatefile">模板路径</param>
        /// <param name="newFilePath">文件路径</param>
        /// <param name="para">Dictionary数据集</param>
        public void GetTemplateToPDF(string templatefile, string newFilePath, Dictionary<string, string> para)
        {
            PdfReader reader = new PdfReader(templatefile);
            PdfStamper pdfStamper = new PdfStamper(reader, new FileStream(newFilePath, FileMode.OpenOrCreate, FileAccess.Write));
            AcroFields pdfFormFields = pdfStamper.AcroFields;//获取域的集合 
            BaseFont baseFT = BaseFont.CreateFont(@"C:\Windows\Fonts\simsun.ttc,1", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            pdfFormFields.AddSubstitutionFont(baseFT);//设置域的字体;生成文件几十K
            foreach (KeyValuePair<string, string> parameter in para)
            {
                //pdfFormFields.SetFieldProperty(parameter.Key, "textfont", baseFT, null);//生成文件过大(4.5MB左右) 摒弃掉了
                //为需要赋值的域设置值;
                pdfFormFields.SetField(parameter.Key, parameter.Value);
            }
            pdfStamper.FormFlattening = true;//设置true PDF文件不能编辑
            pdfStamper.Close();
        }

5根据模板批量打印pdf文件

        /// <summary>
        /// 根据模板批量打印pdf文件
        /// </summary>
        /// <param name="templatefile">模板文件</param>
        /// <param name="newFilePath">文件路径</param>
        /// <param name="newFileName">文件名称</param>
        /// <param name="listpara">List数据集</param>
        public void GetTemplateToPDFByList(string templatefile, string newFilePath, string newFileName, List<Dictionary<string, string>> listpara)
        {
            String filename = newFilePath + "\\" + newFileName;
            Document document = new Document();
            PdfCopy copy = new PdfCopy(document, new FileStream(filename, FileMode.Create));
            document.Open();
            foreach (var item in listpara)
            {
                String tmppdffile = newFilePath + "\\tmp_" + newFileName;
                this.GetTemplateToPDF(templatefile, tmppdffile, item);
                PdfReader reader = new PdfReader(tmppdffile);
                //int n = reader.NumberOfPages;
                //模板有多页时 循环N
                document.NewPage();
                PdfImportedPage page = copy.GetImportedPage(reader, 1);
                copy.AddPage(page);
                reader.Close();
                if (File.Exists(newFilePath + "\\tmp_" + newFileName))
                {
                    File.Delete(newFilePath + "\\tmp_" + newFileName);
                }
            }
            document.Close();
        }

6根据1生成的模板 赋值  利用5批量打印方法 进行批量打印 最后一步将PDF文件输出

原创粉丝点击