1. 程式人生 > >C# HTML生成PDF

C# HTML生成PDF

 protected void Page_Load(object sender, EventArgs e)
        {

            string RootDir = Server.MapPath(System.Web.HttpContext.Current.Request.ApplicationPath.ToString());//獲取程式根目錄
            string url = RootDir + "hh.html";
            HtmlToPdf(url, "c:/ddd.pdf");
            
        }



        /// <summary>
        /// HTML生成PDF
        /// </summary>
        /// <param name="url">地址</param>
        /// <param name="path">PDF存放路徑</param>
        public static bool HtmlToPdf(string url, string path)
        {
            try
            {
                if (string.IsNullOrEmpty(url) || string.IsNullOrEmpty(path))
                    return false;
                Process p = new Process();
                string str = System.Web.HttpContext.Current.Server.MapPath("wkhtmltopdf.exe");
                if (!System.IO.File.Exists(str))
                    return false;
                p.StartInfo.FileName = str;
                p.StartInfo.Arguments = " \"" + url + "\" " + path;
                p.StartInfo.UseShellExecute = false;
                p.StartInfo.RedirectStandardInput = true;
                p.StartInfo.RedirectStandardOutput = true;
                p.StartInfo.RedirectStandardError = true;
                p.StartInfo.CreateNoWindow = true;
                p.Start();
                System.Threading.Thread.Sleep(500);

                return true;
            }
            catch (Exception ex)
            {
                HttpContext.Current.Response.Write(ex);
            }
            return false;
        }

需要執行exe檔案

參考:

http://www.jingzhengli.cn/blog/cj/1030.html