http://www.it165.net/pro/html/201309/7208.html(轉)
前言
Pechkin套件可以將網頁Html轉成PDF檔,底層仍是WkHtmlToPdf(見另一篇文章的使用方式:網頁Html轉PDF文件(一行程序代碼解決)
而Pechkin只是把它包成.dll檔方便在.net程序代碼中使用
如果要在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
01.
using
Pechkin;
02.
03.
using
System;
04.
using
System.Collections.Generic;
05.
using
System.Linq;
06.
using
System.Web;
07.
using
System.Web.Mvc;
08.
09.
namespace
MvcApplicationPechkin.Controllers
10.
{
11.
public
class
HomeController : Controller
12.
{
13.
/// <summary>
14.
/// 首頁(Demo頁)
15.
/// </summary>
16.
/// <returns></returns>
17.
[HttpGet]
18.
public
ActionResult Index()
19.
{
20.
return
View();
21.
}
22.
/// <summary>
23.
/// 將網頁轉成pdf檔后,輸出給客戶端下載
24.
/// </summary>
25.
/// <returns></returns>
26.
[HttpPost]
27.
public
ActionResult DownloadPdf()
28.
{
29.
30.
31.
//對象是yahoo首頁,使用http開頭的絕對路徑URL
32.
string
url =
"http://tw.yahoo.com/"
;
33.
34.
35.
using
(IPechkin pechkin = Factory.Create(
new
GlobalConfig()))
36.
{
37.
38.
39.
ObjectConfig oc =
new
ObjectConfig();
40.
oc.SetPrintBackground(
true
)
41.
.SetLoadImages(
true
)
42.
.SetScreenMediaType(
true
)
43.
.SetPageUri(url);
44.
45.
46.
47.
byte
[] pdf = pechkin.Convert(oc);
48.
return
File(pdf,
"application/pdf"
,
"ExportPdf.pdf"
);
49.
}
50.
51.
}
52.
}
53.
}
View
Index.cshtml
01.
@{
02.
Layout = null;
03.
}
04.
05.
<!DOCTYPE html>
06.
07.
<
html
>
08.
<
head
>
09.
<
meta
name
=
"viewport"
content
=
"width=device-width"
/>
10.
<
title
>Index</
title
>
11.
</
head
>
12.
<
body
>
13.
@using(Html.BeginForm("DownloadPdf","Home",FormMethod.Post))
14.
{
15.
16.
<
input
type
=
"submit"
value
=
"submit"
/>
17.
}
18.
</
body
>
19.
</
html
>
5.執行結果
(點擊submit,出現另存檔案)

(網頁轉成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項目上的設定才算全部完成~