HTML轉PDF - 使用Pechkin套件

剛好跟人討論到HTML轉PDF需求,便對工具進行簡單評估以備不時之需。

網路上比較多人推的是WkHtmlToPdf,如果是用.NET開發,已經有人包成NuGet套件,直接搜尋pechkin就可找到,它有兩個版本: Pechkin適用單執行緒,如要非同步執行請選用Pechkin.Synchronized。

安裝NuGet套件後,相關Unmanage DLL也會一併下載並加入專案,不用額外安裝HkHtmlToPdf就可開始寫程式,十分方便。但由於Unmanaged部分為32位元,記得要將專案目標平台切成x86。

參考Pechkin作者在GitHub的FAQ,我寫了一個簡單範例,分別將Google新聞首頁及自己產生的HTML轉成PDF:

排版顯示純文字
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Pechkin;
 
namespace Html2Pdf
{
    class Program
    {
        static void Main(string[] args)
        {
            var config = new GlobalConfig();
            var pechkin = new SimplePechkin(config);
            ObjectConfig oc = new ObjectConfig();
            oc.SetPrintBackground(true)
                .SetLoadImages(true)
                .SetPageUri("http://news.google.com.tw/");
            byte[] pdf = pechkin.Convert(oc);
            File.WriteAllBytes("d:\\temp\\google-news.pdf", pdf);
 
            string html = @"
<html><head><style>
body { background: #ccc; }
div { 
width: 200px; height: 100px; border: 1px solid red; border-radius: 5px;
margin: 20px; padding: 4px; text-align: center;
}
</style></head>
<body>
<div>Jeffrey</div>
<script>document.write('<span>Generated by JavaScript</span>');</script>
</body></html>
";
            pdf = pechkin.Convert(oc, html);
            File.WriteAllBytes("d:\\temp\\myhtml.pdf", pdf);
        }
 
    }
}

實測效果挺不錯,跟實際網站所看到的很接近: (但不完全相同)

在自製HTML測試中,我使用<script>docuemt.write(…)</script>在網頁中插入內容,在PDF中也正確顯示。

但在某些狀況下,產生的PDF會與實際網頁差異頗大(例如: 我的Blog首頁轉PDF後排版就亂了),有可能是網頁的某些Style寫法或複雜JavaScript超出WkHtmlToPdf預期,也有可能是元件的Bug,感覺眉角還很多,留待實際遇到時再深究。

posted @ 2015-10-14 17:24  三小  阅读(2736)  评论(0编辑  收藏  举报