Converting HTML text to image using C#

Hi,

This post talks about converting HTML text to image. That is, saving as image, the html text as rendered in the browser!! (Unable to put it in proper words!! :@ )

The code uses an external dll (HtmlRenderer) that needs to be added in out project. HtmlRenderer namespace provides a class “HtmlRender” that provides an overloaded method “Render“. This method saves renders the html text and saves the outcome as an image.

The following code shows the usage of the method.

namespace HtmlToBmpImageDemo
{
     class Program
     {
         static void Main(string[] args)
         {
               Bitmap m_Bitmap = new Bitmap(400, 600);
               PointF point = new PointF(0, 0);
               SizeF maxSize = new System.Drawing.SizeF(500, 500);
               HtmlRenderer.HtmlRender.Render(Graphics.FromImage(m_Bitmap), 
                                              "<html><body><p>This is a shitty html code</p>"
                                              + "<p>This is another html line</p></body>", 
                                               point, maxSize);
               
               m_Bitmap.Save(@"C:\Test.bmp");
         }
     }
}

The problem with this method is that if we include images in the HTML mark up text, the corresponding image doesn’t show the image in the created image (hope you understand the previous line!). There is yet another method of taking a screenshot of rendered html by opening a browser process in the background and then taking a screen shot of that. But I wanted a more lighter and simpler process and found this.

Hope this helps and please do let me know if there is any method of displaying images and then taking a screen shot of that rendered HTML.

Advertisements

About Amogh Natu

Technology enthusiast, Associate Consultant @ Microsoft, music lover, love my guitar, Microsoft.NET, ASP.NET, C#.NET Professional.
This entry was posted in .NET, C#, General and tagged , , , , . Bookmark the permalink.

3 Responses to Converting HTML text to image using C#

  1. Arthur says:

    I have made improvements supporting image generation in HTML Renderer (since 1.4.11.0)
    The code is simpler and supports displaying images (although it was also possible before but required more work).
    For more details see: https://htmlrenderer.codeplex.com/wikipage?title=Image%20generation

  2. Pingback: Generate image from HTML using HTML Renderer « The Art of Dev

Your comments or opinions.....

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s