ASP.NET Core项目中基于模板生成并填充PDF的技术咨询
在ASP.NET Core中基于PDF模板填充字段并生成PDF
一、代码实现方案
你当前用的iTextSharp在.NET Core下有适配的NuGet包(iTextSharp.LGPLv2.Core),不过更推荐用iText7——它是iText的新版本,对.NET Core支持更完善,API也更清晰。
用iText7实现(推荐)
首先安装必要的NuGet包:iText.Kernel、iText.Forms(直接搜iText7也能找到套装包)。
然后是填充模板的核心代码:
using iText.Kernel.Pdf; using iText.Forms; using System.Collections.Generic; using System.IO; public void FillPdfTemplate(string templatePath, string outputPath, Dictionary<string, string> formData) { // 读取模板文件 using var reader = new PdfReader(templatePath); using var writer = new PdfWriter(outputPath); // 基于模板创建新PDF,保留原内容 using var pdfDoc = new PdfDocument(reader, writer); // 获取PDF表单对象 var form = PdfAcroForm.GetAcroForm(pdfDoc, true); if (form == null) return; // 遍历填充字段 foreach (var (fieldName, value) in formData) { var field = form.GetField(fieldName); if (field != null) { field.SetValue(value); // 可选:设置字段为只读,防止后续修改 field.SetReadOnly(true); } } // 可选:扁平化表单——把可编辑字段转成静态文本,避免被修改 form.FlattenFields(); } // 调用示例 var formData = new Dictionary<string, string> { {"UserName", "张三"}, {"UserAge", "28"}, {"UserAddress", "上海市浦东新区"} }; FillPdfTemplate(@"Templates/UserInfoTemplate.pdf", @"Output/FilledUserInfo.pdf", formData);
用iTextSharp实现(适配.NET Core)
如果坚持用iTextSharp,先安装iTextSharp.LGPLv2.Core包,代码如下:
using iTextSharp.text.pdf; using System.Collections.Generic; using System.IO; public void FillTemplateWithiTextSharp(string templatePath, string outputPath, Dictionary<string, string> formData) { var reader = new PdfReader(templatePath); var stamper = new PdfStamper(reader, new FileStream(outputPath, FileMode.Create)); var form = stamper.AcroFields; // 填充字段 foreach (var (fieldName, value) in formData) { if (form.Fields.ContainsKey(fieldName)) { form.SetField(fieldName, value); // 设置只读 form.SetFieldProperty(fieldName, "setfflags", PdfFormField.FF_READ_ONLY, null); } } // 扁平化表单 stamper.FormFlattening = true; stamper.Close(); reader.Close(); }
二、制作PDF模板的工具
除了你在用的Illustrator,这些工具更适合做带可填充字段的PDF模板:
- Adobe Acrobat Pro DC:最专业的选择,直接可视化添加文本框、下拉框、复选框等表单字段,导出的PDF可以直接被iText识别填充。如果用Illustrator做了布局,可以导入Acrobat里再加字段,比直接用Illustrator导出表单方便。
- LibreOffice Writer:免费开源,在Writer里插入表单控件(比如文本框),编辑好后导出为PDF时勾选“创建可填写表单”选项,就能生成可用的模板。
- Foxit PhantomPDF:Acrobat的替代工具,功能全面,价格比Acrobat低,同样支持可视化创建PDF表单。
- PDFescape:在线工具(注意敏感内容别用),不用安装软件,直接上传PDF添加表单字段,适合临时需求。
内容的提问来源于stack exchange,提问作者Mohamed Iben Lassoued
相关产品推荐
相关产品推荐

