在 .NET 平臺上,咱們有多種方式能夠將一段 HTML 文本轉換爲一張圖片:HTML Renderer、SelectPdf 、Aspose.Html 等。html
在 WinForm 程序中,每個 System.Windows.Forms.Control
的派生類型均包含一個名爲 DrawToBitmap
的方法,該方法能夠將控件繪製到一張圖片上。WebBrowser 具有顯示 HTML 的功能,又由於其從 Control 類型派生,因此包含 DrawToBitmap
方法。咱們只需將要在 WebBrowser 上加載要展現的 HTML 並在其 DocumentCompleted
事件中繪製圖片便可:git
public static async Task<Image> HtmlToImage(String html, int width = 1024, int height = 768) { var taskCompletionSource = new TaskCompletionSource<Image>(); var thread = new Thread(() => { using var browser = new WebBrowser { Width = width, Height = height, ScrollBarsEnabled = false }; browser.DocumentCompleted += (s, e) => { var b = s as WebBrowser; if (b == null) { return; } var bmp = new Bitmap(b.Width, b.Height); b.DrawToBitmap(bmp, new Rectangle(0, 0, b.Width, b.Height)); taskCompletionSource.SetResult(bmp); Application.ExitThread(); }; browser.DocumentText = html; Application.Run(); }); thread.SetApartmentState(ApartmentState.STA); thread.Start(); return await taskCompletionSource.Task; }
以上代碼參考了: Stack Overflow ,筆者將其改造爲異步方法並增長了必要的釋放功能。在 LINQPad 中測試效果以下:github
筆者在實際工做中使用到了部分 CSS3 屬性,默認狀況下 WebBrowser 使用低版本的 IE 瀏覽器渲染網頁,這會致使部分網頁效果不生效,好比隔行變色效果。除了修改註冊表,咱們仍能夠經過在網頁中加入 meta
標籤的方式告知 WebBrowser 使用高版本的 IE 瀏覽器進行渲染,僅需將如下代碼複製至 HTML 的 head 標籤內便可:瀏覽器
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>