asp.net如何调用Itext编辑pdf模板

转载自:http://blog.csdn.net/polo_longsan/article/details/39254867

这个虽然是java但是原理基本相同

asp.net代码如下

调用:

using iTextSharp.text;
using iTextSharp.text.pdf;
        public void Index()
        {

            //获取中文字体,第三个参数表示为是否潜入字体,但只要是编码字体就都会嵌入。
         BaseFont baseFont = BaseFont.CreateFont(@"C:\Windows\Fonts\simsun.ttc,1", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
          //  BaseFont baseFont = BaseFont.CreateFont("STSong-Light", "UniGB-UCS2-H",
          //          BaseFont.NOT_EMBEDDED);    
            //读取模板文件
            PdfReader reader = new PdfReader(@"C:\Users\shxy\Desktop\test2.pdf");
 
            //创建文件流用来保存填充模板后的文件
            System.IO.MemoryStream stream = new System.IO.MemoryStream();
 
            PdfStamper stamp = new PdfStamper(reader, stream);
            //设置表单字体,在高版本有用,高版本加入这句话就不会插入字体,低版本无用
            stamp.AcroFields.AddSubstitutionFont(baseFont);
 
            AcroFields form = stamp.AcroFields;

            form.SetField("Name", "石义");
            form.SetField("test", "Name");
            form.SetField("Payment", "1");
            form.SetField("test2", "1");
            
            //表单文本框是否锁定
            stamp.FormFlattening = false;
 
            Dictionary<string, string> para = new Dictionary<string, string>();
           // para.Add("Name", "abc");
            //填充表单,para为表单的一个(属性-值)字典
            //foreach (KeyValuePair<string, string> parameter in para)
            //{
            //    //要输入中文就要设置域的字体;
            //    form.SetFieldProperty(parameter.Key, "textfont", baseFont, null);
            //    //为需要赋值的域设置值;
            //    form.SetField(parameter.Key, parameter.Value);
            //}
      
            //按顺序关闭io流
 
            stamp.Close();
            reader.Close();
            //生成文件

            Response.Clear();
            Response.AppendHeader("Content-Disposition", "attachment;filename=pdftest.pdf");
            Response.ContentType = "application/octet-stream";
            Response.OutputStream.Write(stream.GetBuffer(), 0, stream.GetBuffer().Length);
            Response.OutputStream.Flush();
            Response.OutputStream.Close();
            Response.Flush();
            Response.End();


            //FileResult fileResult = new FileContentResult(stream.ToArray(), "application/pdf");
            //fileResult.FileDownloadName = "4.pdf";
            //return fileResult;

        }

过程中遇到的问题:

贴出的代码是中文版的无需关心了 ,主要取决字体,过程中遇到模板的单选和多选,传入的参数需要根据你pdf模板的实际值来判定,如果只是猜估计很难。


我采用的是Adobe Acrobat 9 Pro网上有破解版。

之后的思路是做一个模板上传,参数配比,能达到自己生成模板数据自动填充打印。

猜你喜欢

转载自blog.csdn.net/shixianyiyu5277/article/details/79508199