C# Convert html page to image

* Add references to System.Windows.Forms and System.Drawing

public class HtmlRenderer
{
  public static void Render(string inputUrl, string outputPath, Rectangle crop)
  {    
    WebBrowser wb = new WebBrowser();
    wb.ScrollBarsEnabled = false;
    wb.ScriptErrorsSuppressed = true;
    wb.Navigate(inputUrl);
    while (wb.ReadyState != WebBrowserReadyState.Complete)
    {
      Application.DoEvents();
    }
    wb.Width = wb.Document.Body.ScrollRectangle.Width;
    wb.Height = wb.Document.Body.ScrollRectangle.Height;
    using (Bitmap bitmap = new Bitmap(wb.Width, wb.Height))
    {
      wb.DrawToBitmap(bitmap, new Rectangle(0, 0, wb.Width, wb.Height));
      wb.Dispose();
      Rectangle rect = new Rectangle(crop.Left, crop.Top, wb.Width - crop.Width - crop.Left, wb.Height - crop.Height - crop.Top);
      Bitmap cropped = bitmap.Clone(rect, bitmap.PixelFormat);
      cropped.Save(outputPath, ImageFormat.Png);
    }
  }
}

You need to run it from the thread in Single Threaded Apartment

[STAThread]
static void Main(string[] args)
{
    HtmlRenderer.Render(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Test.htm"), "Test.png",new Rectangle(0, 0, 0, 0));
}

or

static void Main(string[] args)
{
    var t = new Thread(() => HtmlRenderer.Render(Path.Combine(AppDomain.CurrentDomain.BaseDirectory,"Test.htm"), "Test.png", new Rectangle(0, 0, 0, 0)));
    t.SetApartmentState(ApartmentState.STA);
    t.Start();
}

Comments

  1. Sometimes a simple program can make you understand the things in an easy way. I have done the same thing but with more part of coding. This is quit simple, mine looks more complicated. I think there is need for me to concentrate more on this simplest part.

    ReplyDelete
  2. Hi, It giving me Out of mammary ex

    ReplyDelete
  3. I can only assume that your html page is quite big. I've only used this code with small html tables that I wanted to embed into the email.

    ReplyDelete
  4. Why not go for more easier solution to use wkhtmltoimage. It is opensource and free.

    you can also find the implementation here
    http://www.dotnetobject.com/Thread-Html-to-image-conversion-c

    ReplyDelete
  5. Great infomation.I newly working on converting HTML to Image in C# ,evey glad to find you code works smoothly for me.However ,
    I got a similiar sample project from MSDN, http://code.msdn.microsoft.com/Add-Converting-HTML-to-a1decbbd ,which demonstrated a different way. Share with you guys.

    ReplyDelete

Post a Comment

Popular posts from this blog

Parse XML to dynamic object in C#

C# Crop white space from around the image