1. 程式人生 > >ASP.NET指定頁面轉PDF、JPG(插件)

ASP.NET指定頁面轉PDF、JPG(插件)

isp asp type ref [] addheader 導出pdf length net

 //PDF文件導出
        public ActionResult pdfs() {
            
            //導出頁面的路徑(死路徑)
            string url = "http://localhost:1213/";
            //插件的路徑(轉換為pdfNE)
            string pdf = "C:/Program Files/wkhtmltopdf/bin/wkhtmltopdf.exe";

            //隨機生成一個文件名稱
            string filename = Guid.NewGuid().ToString();
            
//pdf格式 string pdfpath = filename + ".pdf"; Process p = System.Diagnostics.Process.Start(pdf, url + " \"" + Server.MapPath(pdfpath) + "\""); p.WaitForExit(); //下載 FileStream fs = new FileStream(Server.MapPath(pdfpath), FileMode.Open);
byte[] file = new byte[fs.Length]; fs.Read(file, 0, file.Length); fs.Close(); Response.Clear(); Response.AddHeader("content-disposition", "attachment; filename=" + filename + ".pdf");//以二進制流模式,強制下載 Response.ContentType = "application/octet-stream
"; Response.BinaryWrite(file); Response.Write("<script>window.location=‘Index.cshtml‘</script>"); return null; }
 //JPG文件導出
        public ActionResult jpgs()
        {
            //導出頁面的路徑
            string url = "http://localhost:1213/";
            //插件的路徑(轉換為jpg)
            string jpg = "C:/Program Files/wkhtmltopdf/bin/wkhtmltoimage.exe";

            //隨機生成一個文件名稱
            string filename = Guid.NewGuid().ToString();
            //jpg格式
            string pdfpath = filename + ".jpg";
            Process p = System.Diagnostics.Process.Start(jpg, url + " \"" + Server.MapPath(pdfpath) + "\"");
            p.WaitForExit();

            //下載
            FileStream fs = new FileStream(Server.MapPath(pdfpath), FileMode.Open);
            byte[] file = new byte[fs.Length];
            fs.Read(file, 0, file.Length);
            fs.Close();
            Response.Clear();
            Response.AddHeader("content-disposition", "attachment; filename=" + filename + ".jpg");//以二進制流模式,強制下載 
            Response.ContentType = "application/octet-stream";
            Response.BinaryWrite(file);
            Response.Write("<script>window.location=‘Index.cshtml‘</script>");
            return null;
        }
布局頁面代碼:
  <a>@Html.ActionLink("當前頁面導出PDF", "pdfs")</a>
  <a>@Html.ActionLink("當前頁面導出JPG", "jpgs")</a>

轉PDF、JPG插件(wkhtmltox-0.12.4_msvc2015-win64.exe)

ASP.NET指定頁面轉PDF、JPG(插件)