HTML頁面產生PDF(c#)

來源:互聯網
上載者:User

Calling wkhtmltopdf to generate PDF from HTML 老外最多人加分的那篇做法,使用wkhtmtopdf(GPL協議)可以省很多程式碼, 首先到官網
找installer.exe下載

wkhtmltopdf,一個整合好了的exe檔案(C++編寫),基本的調用方法是, wkhtmltopdf.exe http://passport.yupsky.com/ac 
count/register e:\yupskyreg.pdf

,可以先在命令列測試一下,有其他的需要可以在命令列通過wkhtmltopdf --help查詢,如果是超長頁的花,可以用命令

wkhtmltopdf.exe http://passport.yupsky.com/ac 
count/register e:\yupskyreg.pdf  -H --outline (-H是添加預設標題,--outline是添加pdf的左側概要哦!)而且可以批量產生哦,中間用空格隔開

using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; /*要引用以下命名空間*/ using System.Diagnostics; using System.IO;public partial class _Default : System.Web.UI.Page {//Button的Click事件(把Url的網頁內容轉成PDF)     protected void btn_execute_Click(object sender, EventArgs e)     {        //因為Web 是多線程環境,避免甲產生的檔案被乙下載去,所以檔名都用唯一         string fileNameWithOutExtention = Guid.NewGuid().ToString();        //執行wkhtmltopdf.exe         Process p = System.Diagnostics.Process.Start(@"D:\wkhtmltopdf\wkhtmltopdf.exe", @"http://msdn.microsoft.com/zh-cn D:\" + fileNameWithOutExtention + ".pdf");        //若不加這一行,程式就會馬上執行下一句而抓不到檔案發生意外:System.IO.FileNotFoundException: 找不到檔案 ''。         p.WaitForExit();        //把檔案讀進檔案流         FileStream fs = new FileStream(@"D:\" + fileNameWithOutExtention + ".pdf", FileMode.Open);         byte[] file = new byte[fs.Length];         fs.Read(file, 0, file.Length);         fs.Close();        //Response給用戶端下載         Response.Clear();         Response.AddHeader("content-disposition", "attachment; filename=" + fileNameWithOutExtention + ".pdf");//強制下載         Response.ContentType = "application/octet-stream";         Response.BinaryWrite(file);    } }

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.