wkhtmltopdf参数设置和下载PDF

来源:互联网 发布:js 鼠标自动隐藏 编辑:程序博客网 时间:2024/06/04 20:38
string fileName = Guid.NewGuid().ToString();            string url = Request.Url.ToString();            string savepath = System.Web.HttpContext.Current.Server.MapPath("~/upfile/") + fileName + ".pdf";            try            {                if (!string.IsNullOrEmpty(url) || !string.IsNullOrEmpty(savepath))                {                    Process p = new Process();                    string dllstr = @"D:\wkhtmltopdf\wkhtmltopdf.exe";                    StringBuilder paramsBuilder = new StringBuilder();                    paramsBuilder.Append("--print-media-type ");                    paramsBuilder.Append("--disable-smart-shrinking ");                    paramsBuilder.Append("--margin-top 0mm --margin-bottom 0mm --margin-right 0mm --margin-left 0mm ");                    //paramsBuilder.Append("--page-size A4 ");//当使用页面参数时,宽高参数无效                    paramsBuilder.Append("--page-width 310mm ");                    paramsBuilder.Append("--page-height 310mm ");                    paramsBuilder.Append("--no-background ");                    paramsBuilder.AppendFormat("\"{0}\" \"{1}\"",url, savepath);                    if (System.IO.File.Exists(dllstr))                    {                        ProcessStartInfo psi = new ProcessStartInfo();                        psi.FileName = dllstr;                        psi.Arguments = paramsBuilder.ToString();                        psi.UseShellExecute = false;                        psi.RedirectStandardOutput = true;                        psi.RedirectStandardError = true;                        psi.RedirectStandardInput = true;                        psi.CreateNoWindow = true;                        p.StartInfo = psi;                        p.Start();                        p.WaitForExit();                        try                        {                            FileStream fs = new FileStream(savepath, FileMode.Open);                            byte[] file = new byte[fs.Length];                            fs.Read(file, 0, file.Length);                            fs.Close();                            System.Web.HttpContext.Current.Response.Clear();                            System.Web.HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=" + fileName + ".pdf");//強制下載                            System.Web.HttpContext.Current.Response.ContentType = "application/octet-stream";                            System.Web.HttpContext.Current.Response.BinaryWrite(file);                        }                        catch (Exception e)                        {                            throw e;                        }                    }                }            }            catch (Exception e)            {                throw e;            }

0 0
原创粉丝点击