/// <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)准備表單