使用iTextSharp來填充PDF模板文件


需求簡介:

    遇到了這樣一個需求:某公司需要為所有用戶的培訓生成一個培訓記錄,過程如下:

    (1)用戶在培訓完之后會進入到一個填寫信息的界面。

    (2)用戶填寫信息。

    (3)生成PDF格式的培訓記錄。

    (4)用戶下載並打印歸檔。

思路:

    因為每次培訓后生成的PDF文件內容都不完全一樣,但是格式卻是完全相同的,所以很容易讓人聯想到使用模板文件。每次只需要提取用戶輸入的有效信息,然后復制模板、填充模板、彈出下載即可。

解決過程:

    (1)制作模板:我先使用Microsoft Office 2010編輯模板文件,在保存的時候將文件保存為pdf文件。然后用Adobe Acrobat X編輯剛剛生成的PDF文件,把Textbox、Checkbox等域拖動到指定的位置,然后通過預覽功能調整各個域的位置和其中文字的字體、大小,完成后保存。模板完成!(我用Google搜索的時候也看到過用OpenOffice來完成模板的,不過沒點開看)

    (2)編程填充PDF文件:本人使用的編程語言是C#,所以使用對應的免費開源類庫iTextSharp來完成填充的功能。程序的執行過程是:先讀取網頁中的有效信息,然后打開模板文件填充到模板文件的域中間,最后另存為一個PDF文件。代碼見下文。

    (3)服務器端推送文件給瀏覽器下載。

遇到的問題:

    (1)首先遇到的問題是Checkbox的傳參問題。一開始本人是從一些英文網站查看的相關資料,里面在設置Checkbox使用的語句是:pdfFormFields.SetField(“male”, “Yes”); 試了很多遍,結果就是不行,Checkbox並沒有被勾選上。后來無奈了點開Checkbox屬性中的選項值一欄,發現它有一欄名為導出值,其中的值為“是”。我猜想我的模板由於使用中文版,其中參數的設置也發生了相應的變化,一試之下果然如此。pdfFormFields.SetField(“male”, “是”); 就是行得通。

    (2)顯示中文的問題。如果直接把中文字符串設置到PDF模板中去的話中文字符一個都不會顯示。Google了一下,應該是亞洲的文字都不能顯示,為此還需要兩個附加組件:iTextAsianCmaps.dll和iTextAsian.dll。這兩個組件可以在sourceforge上面下載。大家不妨參考:http://www.cnblogs.com/haogj/archive/2011/09/05/2167659.html

    (3)以為這就好了?差遠了!在輸入第一句BaseFont.AddToResourceSearch("iTextAsian.dll");的時候有錯誤?對了!目前iTextSharp最新的版本是5.4.4,也就是我當時使用的版本。估計版本的變遷使得方法的調用也出了問題,於是果斷換成了5.1.2的版本。

    (4)改完之后一路順暢地寫完了方法。試驗一下,又出錯!BaseFont bf = BaseFont.CreateFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);中的STSong-Light和UniGB-UCS2-H無法被識別!這個問題我直到最后都沒能解決(看了好幾篇帖子還是沒能解決,大家如果有成功的通知小弟一聲,謝謝啊!),退而求其次我只好使用TTF 字體。注:使用TTF 字體貌似是在PDF文件中嵌入字體文件,這使得PDF文件體積巨大,成了我的心病。

代碼:

    Anyway,代碼還是最重要的,以下的靜態類用來填充PDF模板:

   1: using System;
   2: using System.Collections.Generic;
   3: using System.Linq;
   4: using System.Web;
   5: using System.Diagnostics;
   6: using System.IO;
   7: using iTextSharp.text.pdf;
   8:  
   9: public class FillPdfTemplate
  10: {
  11:     public static void GetEnPdf(string templatePath, string newFilePath, Dictionary<string, string> parameters)
  12:     {
  13:         PdfReader pdfReader = new PdfReader(templatePath);
  14:         PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileStream(newFilePath,
  15: FileMode.Create));
  16:         //獲取域的集合;
  17:         AcroFields pdfFormFields = pdfStamper.AcroFields;
  18:         //為需要賦值的域設置值;
  19:         foreach (KeyValuePair<string, string> parameter in parameters)
  20:         {
  21:             pdfFormFields.SetField(parameter.Key, parameter.Value);
  22:         }
  23:         //這句很重要,如果為false那么生成的PDF文件還能編輯,一定要設為true;
  24:         pdfStamper.FormFlattening = true;
  25:         pdfStamper.Close();
  26:         pdfReader.Close();
  27:     }
  28:  
  29:     public static void GetChPdf(string templatePath, string newFilePath, string iTextAsianCmapsPath, Dictionary<string, string> parameters)
  30:     {
  31:         PdfReader pdfReader = new PdfReader(templatePath);
  32:         PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileStream(newFilePath, FileMode.Create));
  33:         //獲取域的集合;
  34:         AcroFields pdfFormFields = pdfStamper.AcroFields;
  35:  
  36:         BaseFont.AddToResourceSearch(iTextAsianCmapsPath);
  37:         //創建中文字體,第一個參數是中文字體的路徑,第二個參數表示文字方向水平,第三個貌似是字體嵌入PDF文件;
  38:         BaseFont baseFT = BaseFont.CreateFont(@"C:\Windows\Fonts\simsun.ttc,1", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
  39:         foreach (KeyValuePair<string, string> parameter in parameters)
  40:         {
  41:             //要輸入中文就要設置域的字體;
  42:             pdfFormFields.SetFieldProperty(parameter.Key, "textfont", baseFT, null);
  43:             //為需要賦值的域設置值;
  44:             pdfFormFields.SetField(parameter.Key, parameter.Value);
  45:         }
  46:         //這句很重要,如果為false那么生成的PDF文件還能編輯,一定要設為true;
  47:         pdfStamper.FormFlattening = true;
  48:         pdfStamper.Close();
  49:         pdfReader.Close();
  50:     }
  51: }
下面是參數的獲取和調用的過程和推送PDF文件下載的方法:
   1: protected void btnDownLoad_Click(object sender, EventArgs e)
   2: {
   3:     string position = Text1.Value;
   4:     string venue = Text2.Value;
   5:     string method = Text3.Value;
   6:     string date = Text4.Value;
   7:     string teacher = Text5.Value;
   8:     string content = TextArea1.Value;
   9:     string examination = Checkbox1.Checked ? "是" : "否";
  10:     string selfassessment = Checkbox2.Checked ? "是" : "否";
  11:     string certificate = Checkbox3.Checked ? "是" : "否";
  12:     string etc = Checkbox4.Checked ? "是" : "否";
  13:     string trainee = Text6.Value;
  14:  
  15:     Dictionary<string, string> dict = new Dictionary<string, string>();
  16:     dict.Add("TextPosition", position);
  17:     dict.Add("TextVenue", venue);
  18:     dict.Add("TextMethod", method);
  19:     dict.Add("TextDate", date);
  20:     dict.Add("TextTeacher", teacher);
  21:     dict.Add("TextContent", content);
  22:     dict.Add("TextTrainee", trainee);
  23:     dict.Add("CheckBoxExamination", examination);
  24:     dict.Add("CheckBoxSelf-assessment", selfassessment);
  25:     dict.Add("CheckBoxCertificate", certificate);
  26:     dict.Add("CheckBoxEtc", etc);
  27:  
  28:     string template = Server.MapPath("~/PDFTemplate/ch.pdf");
  29:     string newFile = Server.MapPath("~/PDFTemplate") + "\\" + Session["UserID"].ToString() + ".pdf";
  30:     string iTextAsianCmaps = Server.MapPath("~/Libs/iTextAsianCmaps.dll");
  31:     TrainingRecordToPDF.GetChPdf(template, newFile, iTextAsianCmaps, dict);
  32:  
  33:     OutFile(newFile);
  34: }
  35:  
  36: public void OutFile(string  filename)
  37: {
  38:     System.IO.FileInfo file = new System.IO.FileInfo(filename);
  39:     Response.Clear();
  40:     Response.Charset = "GB2312";
  41:     Response.ContentEncoding = System.Text.Encoding.UTF8;
  42:     Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(file.Name));
  43:     Response.AddHeader("Content-Length", file.Length.ToString());
  44:     Response.ContentType = "application/x-bittorrent";
  45:     Response.WriteFile(file.FullName);
  46:     Response.End();  
  47:  
  48: }


免責聲明!

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



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