安裝NuGet套件後,相關Unmanage DLL也會一併下載並加入專案,不用額外安裝HkHtmlToPdf就可開始寫程式,十分方便。但由於Unmanaged部分為32位元,記得要將專案目標平台切成x86。
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);
}
}
}
但在某些狀況下,產生的PDF會與實際網頁差異頗大(例如: 我的Blog首頁轉PDF後排版就亂了),有可能是網頁的某些Style寫法或複雜JavaScript超出WkHtmlToPdf預期,也有可能是元件的Bug,感覺眉角還很多,留待實際遇到時再深究。
