C#编写 HTML生成PDF

前端之家收集整理的这篇文章主要介绍了C#编写 HTML生成PDF前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

下面是编程之家 jb51.cc 通过网络收集整理的代码片段。

编程之家小编现在分享给大家,也给大家做个参考。

        public JsonResult HtmlToPdf(string url)
        {
            bool success = true;
            string dwbh = url.Split('?')[1].Split('=')[1];
            //CommonBllHelper.CreateUserDir(dwbh);
            url = Request.Url.Host + "/html/" + url;
            string guid = DateTime.Now.ToString("yyyyMMddhhmmss");
            string pdfName = guid + ".pdf";
            //string path = Server.MapPath("~/kehu/" + dwbh + "/pdf/") + pdfName;
            string path = "D:\\Temp\\" + pdfName;
            try
            {
                if (string.IsNullOrEmpty(url) || string.IsNullOrEmpty(path))
                    success = false;
                string str = Server.MapPath("~\\tools\\wkhtmltopdf\\bin\\wkhtmltopdf.exe");
                Process p = System.Diagnostics.Process.Start(str,url + " " + path);
                p.WaitForExit();
                if (!System.IO.File.Exists(str))
                    success = false;
               if (System.IO.File.Exists(path))
                {
                    FileStream fs = new FileStream(path,FileMode.Open);
                    byte[] bytes = new byte[(int)fs.Length];
                    fs.Read(bytes,bytes.Length);
                    fs.Close();
                    if (Request.UserAgent != null)
                    {
                        string userAgent = Request.UserAgent.ToUpper();
                        if (userAgent.IndexOf("FIREFOX",StringComparison.Ordinal) <= 0)
                        {
                                 Response.AddHeader("Content-Disposition",
                                               "attachment;  filename=" + HttpUtility.UrlEncode(pdfName,Encoding.UTF8));
                        }
                        else
                        {
                            Response.AddHeader("Content-Disposition","attachment;  filename=" + pdfName);
                        }
                    }
                    Response.ContentEncoding = Encoding.UTF8;
                    Response.ContentType = "application/octet-stream";
                    //通知浏览器下载文件而不是打开
                   Response.BinaryWrite(bytes);
                    Response.Flush();
                    Response.End();
                    fs.Close();
                    System.IO.File.Delete(path);
                }
                else
                {
                    Response.Write("文件未找到,可能已经被删除");
                    Response.Flush();
                    Response.End();
                }
            }
            catch (Exception ex)
            {
                success = false;
            }
          var rlt = new { success = success };
       return Json(rlt,JsonRequestBehavior.AllowGet);
        }

以上是编程之家(jb51.cc)为你收集整理的全部代码内容,希望文章能够帮你解决所遇到的程序开发问题。

如果觉得编程之家网站内容还不错,欢迎将编程之家网站推荐给程序员好友。

猜你在找的C#相关文章