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项目上的设定才算全部完成~