java html 转 pdf 能转 图片和表格_Web

java html 转 pdf 能转 图片和表格_Web_02

java html 转 pdf 能转 图片和表格_System_03

這邊紀錄一下老外最多人加分的那篇做法,使用wkhtmtopdf(採GPL授權)可以省很多程式碼

找installer.exe下載,這邊Demo我是下載wkhtmltopdf-0.9.9-installer.exe

下載完後執行安裝它

java html 转 pdf 能转 图片和表格_Web_04

java html 转 pdf 能转 图片和表格_Web_05

選擇要安裝的路徑

java html 转 pdf 能转 图片和表格_html转换pdf jsp 简单_06

安裝完成

java html 转 pdf 能转 图片和表格_html_07

(如果要解除安裝的話,就到剛剛安裝的資料夾下找uninstall.exe執行即可)

接著看它的原始使用方式

在安裝路徑下有個wkhtmltopdf.exe檔

到命令提示字元(開始→執行→cmd)

輸入

java html 转 pdf 能转 图片和表格_html_08

這邊就抓中國MSDN論壇網頁轉PDF為例

按下Enter轉換完成

java html 转 pdf 能转 图片和表格_html_09

打開剛剛轉換完成的PDF檔

java html 转 pdf 能转 图片和表格_System_10

該文字的地方就是文字,該圖片的地方就是圖片,該超連結的地方就是超連結

既然知道底層使用方式,那就可以使用

第一個參數傳執行檔路徑,第二個傳參數(URL和PDF檔的存放路徑)

如下:

protected void Button1_Click(object sender, EventArgs e)
{
//因為是兩個argument,所以記得要空格
System.Diagnostics.Process.Start(@"D:\wkhtmltopdf\wkhtmltopdf.exe",);
}

此小工具不會像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後,圖片會不見這點要注意

相關討論:

國外討論:

另外GridView匯出PDF的話,請參考:

請注意使用iTextSharp預設不支援中文字和背景色

2011.11.29 好人做到底

把ASP.net C#的Code補完

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",+ 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);
}
}

2013.9.20 追記:

今天才發現此程式已經被包裝成.dll,可以在.net程式碼叫用:參考HTML轉PDF - 使用Pechkin套件 by 黑暗執行緒

然後根據之前同事經驗,直接使用wkhtmltopdf.exe產PDF,可能在64位元作業系統上產不出來。