c# itextsharp根據模板導出pdf報表
阿新 • • 發佈:2018-06-26
generic fill div mode con emp cto IE aid
一、前言
PDF文件在目前來說是比較流行的電子文檔格式,在.Net framework 中身並不包含可以和pdf打交道的方法,也沒有很好操作PDF的類庫,所以我們需要對pdf進行編輯,加密,模板打印等操作不得不去找可用的第三方組件,這裏就可以選擇使用ITextSharp來實現,這個程序是JAVA工具IText的.Net版本。
準備:
1、pdf編輯工具 中文幫助文檔
2、 itextsharp.dll 點擊下載
簡單的操作直接查看幫助文件,此處先省略 後續考慮補充
二、itextsharp 使用
2.1 pdf模板
本次講的是根據pdf模板導出數據,首先創建模板,我這裏使用的工具是Adobe Acrobat 視圖——工具——準備表單,可以在需要賦值的地方放上一個文本框,把名字改成要用的名字。
這是編輯好後的效果
2.2 新建項目
添加引用
新建了一個導出數據測試窗體 load事件以及測試數據,
![技術分享圖片](/img/jia.gif)
/// <summary> /// 模擬數據 /// </summary> DataTable dt; private void frmDemo1_Load(object sender, EventArgs e) { #region 模擬數據 dt = new DataTable(); dt.Columns.Add(View Code"number", typeof(string)); dt.Columns.Add("name", typeof(string)); dt.Columns.Add("yw", typeof(string)); dt.Columns.Add("sx", typeof(string)); dt.Columns.Add("yy", typeof(string)); dt.Columns.Add("pd", typeof(string)); dt.Columns.Add("pe", typeof(string)); dt.Columns.Add("remark", typeof(string)); DataRow dr = dt.NewRow(); dr["number"] = "1"; dr["name"] = "小明"; dr["yw"] = "95"; dr["sx"] = "90"; dr["yy"] = "75"; dr["pd"] = "80"; dr["pe"] = "90"; dt.Rows.Add(dr); dr = dt.NewRow(); dr["number"] = "2"; dr["name"] = "小紅"; dr["yw"] = "100"; dr["sx"] = "90"; dr["yy"] = "85"; dr["pd"] = "100"; dr["pe"] = "90"; dt.Rows.Add(dr); dr = dt.NewRow(); dr["number"] = "3"; dr["name"] = "小芳"; dr["yw"] = "95"; dr["sx"] = "95"; dr["yy"] = "90"; dr["pd"] = "90"; dr["pe"] = "90"; dt.Rows.Add(dr); dataGridView1.DataSource = dt; #endregion }
封裝了一個 導出Pdf幫助類
using iTextSharp.text.pdf; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace itextsharpDemo { /// <summary> /// PDF導出類 /// </summary> public class PdfLeadingHelper { /// <summary> /// 根據路徑獲取模板 /// </summary> /// <param name="pdfTemplate"></param> /// <returns></returns> public static Dictionary<string, string> ReadForm(string pdfTemplate) { Dictionary<string, string> dic = new Dictionary<string, string>(); PdfReader pdfReader = null; try { pdfReader = new PdfReader(pdfTemplate); AcroFields pdfFormFields = pdfReader.AcroFields; foreach (var de in pdfFormFields.Fields) { dic.Add(de.Key, ""); } } catch (Exception ex) { dic = null; //記錄日誌 註釋 // LogHelper.Logger(LogLevel.Error, "pdf導出類發生異常:根據路徑獲取模板時異常" + ex.ToString(), ex); } finally { if (pdfReader != null) { pdfReader.Close(); } } return dic; } /// /// 向pdf模版填充內容,並生成新的文件 /// /// 模版路徑 /// 生成文件保存路徑 /// 標簽字典(即模版中需要填充的控件列表) public static bool FillForm(string pdfTemplate, string newFile, Dictionary<string, string> dic) { bool rsBool = true; PdfReader pdfReader = null; PdfStamper pdfStamper = null; try { pdfReader = new PdfReader(pdfTemplate); pdfStamper = new PdfStamper(pdfReader, new FileStream( newFile, FileMode.Create)); AcroFields pdfFormFields = pdfStamper.AcroFields; //設置支持中文字體 BaseFont baseFont = BaseFont.CreateFont("C:\\WINDOWS\\FONTS\\STSONG.TTF", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); pdfFormFields.AddSubstitutionFont(baseFont); foreach (var de in dic) { pdfFormFields.SetField(de.Key, de.Value + ""); } pdfStamper.FormFlattening = true; } catch (Exception ex) { //記錄日誌 註釋 // LogHelper.Logger(LogLevel.Error, "pdf導出類發生異常:向pdf模版填充內容,並生成新的文件時異常"+ex.ToString(), ex); rsBool = false; } finally { if (pdfStamper != null) { pdfStamper.Close(); } if (pdfReader != null) { pdfReader.Close(); } } return rsBool; } } }
導出按鈕事件
private void button1_Click(object sender, EventArgs e) { //dic 獲取學生成績表 Pdf導出模板 string templetPath = System.Environment.CurrentDirectory + @"\學生成績表.pdf"; Dictionary<string, string> dic = PdfLeadingHelper.ReadForm(templetPath); #region 賦值 dic dic["className"] = textBox1.Text; for (int i = 1; i <= dt.Rows.Count; i++) { if (dic.ContainsKey("number_" + i)) { dic["number_" + i] = dt.Rows[i-1]["number"] +""; dic["name_" + i] = dt.Rows[i-1]["name"] + ""; dic["yw_" + i] = dt.Rows[i-1]["yw"] + ""; dic["sx_" + i] = dt.Rows[i-1]["sx"] + ""; dic["yy_" + i] = dt.Rows[i-1]["yy"] + ""; dic["pd_" + i] = dt.Rows[i-1]["pd"] + ""; dic["pe_" + i] = dt.Rows[i-1]["pe"] + ""; dic["remark_" + i] = dt.Rows[i-1]["remark"] + ""; } } #endregion //保存 SaveFileDialog dlg = new SaveFileDialog(); dlg.FileName = "成績單"; dlg.DefaultExt = ".pdf"; dlg.Filter = "Text documents (.pdf)|*.pdf"; if (dlg.ShowDialog() == DialogResult.OK) { bool rsBool = PdfLeadingHelper.FillForm(templetPath, dlg.FileName, dic); if (rsBool) { MessageBox.Show("導出成功!!"); } } }
先獲取pdf模板變量,Dictionary<string, string> dic 鍵值對類型
賦值對應dic
保存成新pdf
這樣一個小案例就完成了。
c# itextsharp根據模板導出pdf報表