来自:http://www.dotblogs.com.tw/shadow/archive/2011/09/28/38072.aspx
網頁轉PDF檔做法很多(Convert HTML to PDF in .NET )
這邊紀錄一下老外最多人加分的那篇做法,使用wkhtmtopdf (採GPL授權)可以省很多程式碼
首先到官網http://code.google.com/p/wkhtmltopdf/downloads/list
找installer.exe下載,這邊Demo我是下載wkhtmltopdf-0.9.9-installer.exe
下載完後執行安裝它
選擇要安裝的路徑
安裝完成
(如果要解除安裝的話,就到剛剛安裝的資料夾下找uninstall.exe執行即可)
接著看它的原始使用方式
在安裝路徑下有個wkhtmltopdf.exe檔
到命令提示字元(開始→執行→cmd)
輸入
這邊就抓中國MSDN論壇網頁轉PDF為例
按下Enter轉換完成
打開剛剛轉換完成的PDF檔
該文字的地方就是文字,該圖片的地方就是圖片,該超連結的地方就是超連結
既然知道底層使用方式,那就可以使用
System.Diagnostics.Process.Start 方法 (String, String)
第一個參數傳執行檔路徑,第二個傳參數(URL和PDF檔的存放路徑)
如下:
protected
void
Button1_Click(
object
sender, EventArgs e)
此小工具不會像WinForm的WebBrowser控制項一樣會共用IE瀏覽器的Cookie
而且要抓的網頁來源不一定要URL,也可以像這樣直接抓本機上的Html檔轉PDF
protected
void
Button1_Click(
object
sender, EventArgs e)
System.Diagnostics.Process.Start(
@"D:\wkhtmltopdf\wkhtmltopdf.exe"
,
@"D:\index.html D:\myFileName.pdf"
);
只是抓本機的Html轉成PDF後,圖片會不見 這點要注意
相關討論:
如何得知 System.Diagnostics.Process.Start 完畢後的訊息?
網頁資料轉PDF檔
國外討論:
Calling wkhtmltopdf to generate PDF from HTML
另外GridView匯出PDF的話,請參考:
ASP.NET 輕鬆轉 GridView 資料轉檔到 PDF - 使用 iTextSharp
請注意使用iTextSharp預設不支援中文字和背景色
中文字的解決方案:GridView透過iTextSharp輸出PDF中文問題
2011.11.29 好人做到底
把ASP.net C#的Code補完
using
System.Collections.Generic;
using
System.Web.UI.WebControls;
using
System.Diagnostics;
public
partial
class
_Default : System.Web.UI.Page
protected
void
btn_execute_Click(
object
sender, EventArgs e)
string
fileNameWithOutExtention = Guid.NewGuid().ToString();
Process p = System.Diagnostics.Process.Start(
@"D:\wkhtmltopdf\wkhtmltopdf.exe"
,
@"http://msdn.microsoft.com/zh-cn D:\"
+ fileNameWithOutExtention + ".pdf");
FileStream fs =
new
FileStream(
@"D:\"
+ fileNameWithOutExtention + ".pdf", FileMode.Open);
byte
[] file =
new
byte
[fs.Length];
fs.Read(file, 0, file.Length);
Response.AddHeader(
"content-disposition"
,
"attachment; filename="
+fileNameWithOutExtention+
".pdf"
);
Response.ContentType =
"application/octet-stream"
;
Response.BinaryWrite(file);