PDF 根据模板生成PDF

  /// <summary>
        /// 根据模板生成PDF
        /// </summary>
        /// <param name="templetPdf">PDF模板</param>
        /// <param name="newPdf">新生成的PDF</param>
        /// <param name="dict">字典</param>
        public static void CreatePdfByTemplet(string templetPdf, string newPdf,
            Dictionary<string, object> dict)
        {
            iTextSharp.text.pdf.PdfReader pdfReader = new iTextSharp.text.pdf.PdfReader(templetPdf);
            FileStream fs = new FileStream(newPdf, FileMode.OpenOrCreate, FileAccess.ReadWrite);
            PdfStamper pdfStamper = new PdfStamper(pdfReader, fs);
            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\simhei.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);


            pdfFormFields.AddSubstitutionFont(simheiBase);
            foreach (var item in dict.Keys)
            {
                var value = dict[item];
                if (value != null)
                {
                    pdfStamper.AcroFields.SetField(item, value.ToString());

                }
            }
            pdfStamper.Close();
            pdfReader.Close();


        }

 <package id="iTextSharp" version="5.0.5" targetFramework="net472" /> 高版本的会报错 写法不一样

posted @ 2021-04-08 10:58  _York  阅读(24)  评论(0编辑  收藏  举报