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.

3 thoughts on “Converting HTML text to image using C#

Leave a Reply