• 使用 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:windowsfontssimsun.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

  • 相关阅读:
    attr 修改IMG src
    64转2
    :eq
    DOM0和D0M2级事件
    c's's透明度
    span标签 宽度无效解决方案
    CSS 点击事件
    input点击后的 默认边框去除
    js
    CSS 的 ID 和 Class 有什么区别,如何正确使用它们。
  • 原文地址:https://www.cnblogs.com/vanteking/p/4900410.html
Copyright © 2020-2023  润新知