C#根据PDF模板生成内容
/// <summary> /// 指定pdf模板为其文本域赋值 /// </summary> /// <param name="pdfTemplate">pdf模板路径</param> /// <param name="tempFilePath">pdf导出路径</param> /// <param name="parameters">pdf模板域键值</param> public static void PutText(string pdfTemplate, string tempFilePath, Dictionary<string, string> parameters) { PdfReader pdfReader = null; PdfStamper pdfStamper = null; try { if (File.Exists(tempFilePath)) { File.Delete(tempFilePath); } pdfReader = new PdfReader(pdfTemplate); pdfStamper = new PdfStamper(pdfReader, new FileStream(tempFilePath, FileMode.OpenOrCreate)); AcroFields pdfFormFields = pdfStamper.AcroFields; pdfStamper.FormFlattening = true; BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); BaseFont simheiBase = BaseFont.CreateFont(@"C:\Windows\Fonts\simfang.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED); //BaseFont baseFont = BaseFont.CreateFont("C:\\WINDOWS\\FONTS\\STSONG.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); pdfFormFields.AddSubstitutionFont(simheiBase); foreach (KeyValuePair<string, string> parameter in parameters) { if (pdfFormFields.Fields[parameter.Key] != null) { pdfFormFields.SetField(parameter.Key, parameter.Value); } } } catch (Exception ex) { //throw; LoggerHelper._.Error(ex.ToString()); } finally { pdfStamper.Close(); pdfReader.Close(); pdfStamper = null; pdfReader = null; } }
需引用 iTextSharp 程序集
需使用工具编辑模板Adobe Acrobat DC(安装包:adobe acrobat X pro)准备表单