Convert HTML string to image

后端 未结 4 780
终归单人心
终归单人心 2020-11-27 13:00

I have a string variable which holds HTML markup. This HTML markup basically represents the email content.

Now I want to create an image from this string content whi

4条回答
  •  [愿得一人]
    2020-11-27 13:32

    Try the following:

    using System;
    using System.Drawing;
    using System.Threading;
    using System.Windows.Forms;
    
    class Program
    {
        static void Main(string[] args)
        {
            var source =  @"
            
            
                
                    

    An image from W3Schools:

    "; StartBrowser(source); Console.ReadLine(); } private static void StartBrowser(string source) { var th = new Thread(() => { var webBrowser = new WebBrowser(); webBrowser.ScrollBarsEnabled = false; webBrowser.DocumentCompleted += webBrowser_DocumentCompleted; webBrowser.DocumentText = source; Application.Run(); }); th.SetApartmentState(ApartmentState.STA); th.Start(); } static void webBrowser_DocumentCompleted( object sender, WebBrowserDocumentCompletedEventArgs e) { var webBrowser = (WebBrowser)sender; using (Bitmap bitmap = new Bitmap( webBrowser.Width, webBrowser.Height)) { webBrowser .DrawToBitmap( bitmap, new System.Drawing .Rectangle(0, 0, bitmap.Width, bitmap.Height)); bitmap.Save(@"filename.jpg", System.Drawing.Imaging.ImageFormat.Jpeg); } } }

    Note: Credits should go to Hans Passant for his excellent answer on the question WebBrowser Control in a new thread which inspired this solution.

提交回复
热议问题