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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM