使用 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

转载于:https://www.cnblogs.com/vanteking/p/4900410.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值