Monday, 2 April 2012

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();
}

5 comments:

Terry Warner said...

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.

Beautiful Mind said...

Hi, It giving me Out of mammary ex

madeinstein said...

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.

fun freez said...

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

alex smith said...

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.

Post a Comment