[ASP.net MVC] 在Web專案上使用Pechkin套件將網頁轉成PDF檔

[ASP.net MVC] 在Web專案上使用Pechkin套件將網頁轉成PDF檔

前言

Pechkin套件可以將網頁Html轉成PDF檔,底層仍是WkHtmlToPdf(見另一篇文章的使用方式:[C#] 網頁Html轉PDF檔(一行程式碼解決))

而Pechkin只是把它包成.dll檔方便在.net程式碼中使用

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

 

 

實作

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

image

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

image

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

image

 

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

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

 

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

image

Web專案加入參考「Common.Logging.dll」、「Pechkin.dll」

image

image

然後把剩下的五個.dll複製到Web專案根目錄下,不然會無法產PDF檔

image

再對著那五個.dll設定屬性>複製到輸出目錄> 永遠複製

image

 

4..dll參考都準備完畢,接下來是程式碼實作

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

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

HomeController.cs

using Pechkin;
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MvcApplicationPechkin.Controllers
{
    public class HomeController : Controller
    {
        /// <summary>
        /// 首頁(Demo頁)
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ActionResult Index()
        {
            return View();
        }
        /// <summary>
        /// 將網頁轉成pdf檔後,輸出給用戶端下載
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult DownloadPdf()
        {
            
           
            //對象是yahoo首頁,使用http開頭的絕對路徑URL
            string url = "http://tw.yahoo.com/";


            using (IPechkin pechkin = Factory.Create(new GlobalConfig()))
            {
                 

                ObjectConfig oc = new ObjectConfig();
                oc.SetPrintBackground(true)
                    .SetLoadImages(true)
                    .SetScreenMediaType(true)
                    .SetPageUri(url);



                byte[] pdf = pechkin.Convert(oc);
                return File(pdf, "application/pdf", "ExportPdf.pdf");
            }
        
        }
    }
}

View

Index.cshtml

@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
   @using(Html.BeginForm("DownloadPdf","Home",FormMethod.Post))
   {
   
    <input type="submit" value="submit" />
   }
</body>
</html>

 

 

5.執行結果

(點擊submit,出現另存檔案)

image

(網頁轉成PDF檔結果)

image

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

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

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

image

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

image

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

image

 

 

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位元應用程式

image

image

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

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

 

本文範例檔

 

 

 

其他參考文章:

C# – Convert HTML to PDF using Pechkin (WkHtmlToPdf)  ※我是靠著這篇解救的(Y)

Create PDF from html using C#, Nustache,Mustache and Pechkin

2014.2.21 追記自己寫的另一篇文章:[ASP.net MVC] 將HTML轉成PDF檔案,使用iTextSharp套件的XMLWorkerHelper (附上解決顯示中文問題)