WkHtmlToPdf 生成 PDF


1. 首先去http://wkhtmltopdf.org/downloads.html 下載最新版本的安裝包

2. 執行安裝完成

3. CMD 命令行運行wkhtmltopdf.exe程序生成PDF

C:\Program Files\wkhtmltopdf\bin>wkhtmltopdf.exe --orientation Landscape --javascript-delay 5000 c:\BPReport.html c:\BPReport_L.pdf
Loading pages (1/6)
Counting pages (2/6)
Resolving links (4/6)
Loading headers and footers (5/6)
Printing pages (6/6)
Done

參數:

--orientation Landscape 是橫向導出  

--javascript-delay 5000  是延時5秒導出,用於頁面異步加載數據時可以導出到PDF

 

代碼調用exe

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);


    } 
}

 

如果要在Web項目中導入Pechkin的話,有許多很雷的注意事項,以下是這幾天導入項目的經驗…

實作

1.首先在ASP.net MVC項目里,項目的建置平台目標維持預設的「Any CPU」即可,雖說WkHtmlToPdf.exe是32位應用程序,但之后布署在IIS上的相關32位設定並不是從Web項目設定的

如果要在Web項目中導入Pechkin的話,有許多很雷的注意事項,以下是這幾天導入項目的經驗…

實作

1.首先在ASP.net MVC項目里,項目的建置平台目標維持預設的「Any CPU」即可,雖說WkHtmlToPdf.exe是32位應用程序,但之后布署在IIS上的相關32位設定並不是從Web項目設定的

 


 

2.要加入Pechkin套件的話,不能從NuGet或官網(https://github.com/gmanny/Pechkin)下載使用

 
 

因為Pechkin原始作者釋出來的套件在Web項目中使用的話會有DLL檔案Lock住的問題,如果產過一次PDF檔,之后Web項目就再也Build不過

 


 

網絡上已有人釋出修正后的版本:https://github.com/tuespetre/Pechkin

建議直接下載這個:https://pechkinwebtest.codeplex.com/downloads/get/729855

 
3.將上述的載點檔案PechkinDLLs.zip下載解壓后,會有以下幾個檔

 
 

Web項目加入參考「Common.Logging.dll」、「Pechkin.dll」

 




 

然后把剩下的五個.dll復制到Web項目根目錄下,不然會無法產PDF檔

 


 

再對着那五個.dll設定屬性>復制到輸出目錄> 永遠復制

 


 

4..dll參考都准備完畢,接下來是程序代碼實作

注意點1:產生PDF對象的Url,須是Http開頭的絕對路徑URL,而不是直接用Url.Action()方法

注意點2:因為是另一條執行緒另一個工作階段發出Request產出PDF,所以Session不共享,如果要把需要登入才可以看得到的頁面產出PDF檔的話,要另外套不用登入也可以看得到的畫面給Pechkin呼叫

HomeController.cs

 
         

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using Pechkin;
using System.IO;

 
         

namespace WkHtmlToPdf
{
public partial class WebForm1 : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

 
         

}

 
         

protected void button1_Click(object sender, EventArgs e)
{
string url = "http://www.cnblogs.com";

var config = new GlobalConfig();
config //.SetPaperOrientation(true)//設置紙張方向為橫向
.SetMargins(new System.Drawing.Printing.Margins(0, 0, 0, 0));
using (IPechkin pechkin = Factory.Create(config))


{

 
         

ObjectConfig oc = new ObjectConfig();
oc.SetPrintBackground(true)
.SetLoadImages(true)
.SetScreenMediaType(true)
.SetPageUri(url)
.SetRunJavascript(true) //允許javaScript
.SetRenderDelay(5000);//延時5秒;
byte[] pdf = pechkin.Convert(oc);
File.WriteAllBytes("c:\\BPReport-news.pdf", pdf);
}

 
         

}
}
}

 

 

※注意此套件不支持Gif圖片

※如果執行過程中發生Common.Logging錯誤

Could not load file or assembly 'Common.Logging' or one of its dependencies.

 


 

要先看加入參考的Common.Logging.dll檔案版本(2.1.1.0)

 
 

再確保Web.config里的assemblyBinding區段設定也是一樣的檔案版本即可

 


 

6.接下來如果直接將網站布署到IIS上的話,會出現錯誤

無法加載檔案或組件 'Pechkin' 或其相依性的其中之一。 試圖加載格式錯誤的程序。

Could not load file or assembly ‘Pechkin’ or one of its dependencies. An attempt was made to load a program with an incorrect format.

 


 

這要看網站使用的是哪個應用程序集區,再設定啟用32位應用程序

 




 

※即使部署的機器操作系統是64位,有把應用程序集區「啟用32位應用程序」的話,網站也是可以正常執行。

到這邊,Pechkin在Web項目上的設定才算全部完成~


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM