• HTML轉PDF


    剛好跟人討論到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 { 
     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,感覺眉角還很多,留待實際遇到時再深究。

  • 相关阅读:
    CF1080D Olya and magical square
    CF1062D Fun with Integers
    leetcode378 Kth Smallest Element in a Sorted Matrix
    hdoj薛猫猫杯程序设计网络赛1003 球球大作战
    hihocoder1068 RMQ-ST算法
    hihocoder1032 最长回文子串
    hihocoder1394 网络流四·最小路径覆盖
    hihocoder1398 网络流五·最大权闭合子图
    【bzoj4562】HAOI2016食物链
    【bzoj1026】windy数
  • 原文地址:https://www.cnblogs.com/lsgsanxiao/p/4878077.html
Copyright © 2020-2023  润新知