使用 ItextSharp HTML生成Pdf(C#)


以前生成pdf的時候。因為生成的pdf數據是固定的,所以先做好pdf模板,動態的數據可以先用占位符

生成的時候。找到占位符坐標。把數據填充進去

 

優點:先做好模板。生成的pdf 表格、文、內容會好看一些

缺點:只能用作固定的數據生成。如果所有的數據都是動態從數據庫查詢的,就不適用

       每次都需要找占位符的具體坐標

 

后來因為數據都是動態生成,這種需求沒有辦法達到,找了一些資料,html生成 pdf

優點:操作數據方便,把頁面寫好。幫組類 解析子路徑獲取該頁面的html,然后將html代碼生成到pdf

缺點:html需要些行內樣式,不能定義寬度 (一開始做的時候。div我給定義個寬度。導出的數據一直都是空的 )

關鍵代碼:

 if (System.IO.Directory.Exists(Server.MapPath(SystemConst.FILEPATH_PDF)) == false) { System.IO.Directory.CreateDirectory(Server.MapPath(SystemConst.FILEPATH_PDF)); }
            //路徑
            var path = Server.MapPath(string.Format(SystemConst.FILEPATH_PDF + "{0}.pdf", model.UName.GetHashCode()));
            //存在則刪除
            if (System.IO.File.Exists(path) == true) { System.IO.File.Delete(path); }

            var doc = new Document();
            var writer = PdfWriter.GetInstance(doc, new FileStream(path, FileMode.Create));
            //打開文檔
            doc.Open();
            //解析子路徑獲取該頁面的html
            X.Component.Tools.WebClient wc = new Component.Tools.WebClient();
            wc.Encoding = System.Text.Encoding.GetEncoding("utf-8");
            //跳轉到該頁面去獲取html值
            string strUrl = Url.Action("Report", "QuestionnairesMgr", new { id = model.ID, flag = 0, cid = Request.QueryString["cid"] }, "http");
            //給頁面添加cookies值(避免需要驗證是否登錄)
            wc.CookieContainer.Add(new Uri(strUrl), new Cookie("_t", X.Component.Tools.CookieHelper.GetCookieValue("_t")));
            string htmlDoc = wc.GetHtml(strUrl);
            AddHtml(doc, writer, htmlDoc);

            #region 將圖片插入pdf中
            //string chartimg = "http://localhost:8090/Assets/userfiles/imagescharts/" + string.Format("report-charts-{0}.png", id);
            //Image img = iTextSharp.text.Image.GetInstance(chartimg);
            //doc.Add(img);
            #endregion

            //關閉文檔
            doc.Close();
            //輸出文件
            return File(path, SystemConst.MIME_PDF, model.UName + ".pdf");
    /// <summary>
    /// 將html代碼生成到pdf
    /// </summary>
    /// <param name="doc"></param>
    /// <param name="writer"></param>
    /// <param name="_str"></param>
    private void AddHtml(Document doc, PdfWriter writer, string _str)
    {
        byte[] array = System.Text.Encoding.UTF8.GetBytes(_str);
        MemoryStream stream = new MemoryStream(array);
        XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, stream, (Stream)null, System.Text.Encoding.UTF8, new SongFontFactory());
    }


    /// <summary>
    /// 重寫iTextSharp字體(僅僅使用宋體)
    /// </summary>
    public class SongFontFactory : IFontProvider
    {
        public Font GetFont(String fontname, String encoding, Boolean embedded, float size, int style, BaseColor color)
        {

            BaseFont bf3 = BaseFont.CreateFont(@"c:\windows\fonts\simsun.ttc,1", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
            Font fontContent = new Font(bf3, size, style, color);
            return fontContent;

        }
        public Boolean IsRegistered(String fontname)
        {
            return false;
        }
    }


    #endregion

 

需要用到的dll:

itextsharp.dll

itextsharp.xmlworker.dll

需要用的到幫組類:

WebClient.cs


免責聲明!

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



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