purpose of life is joy

NAVIGATION - SEARCH

Tricks : Convert HTML Text to Image in ASP.NET

Normally, We can easily convert text into image thru .net system.drawing namespace and their methods. but converting the HTML to Image in asp.net is bit a tricky one.


Why it is so tricky? Good question. right?


Trickiness is lying in-terms of output. The outcome of the image exactly should matches whatever you see that in your browser. I.e. WYSIWYG.


Generally, In HTML content, we may apply the web-fonts styles to the texts, applying colors, and some more styles we should take care while convert HTML text into image. Hence, I have used the web browser control which is part of .net windows forms. By default, asp.net website will not reference the system.windows.forms namespace, we need to refer that manually.


Create a browser object and disable the scrollbars and script errors. Set the document text of the browser object to your HTML string. Done!


At the run-time, We have to wait till it gets rendered to the browser. for that we are using application do events methods. Then we need to take screenshot of that browser programmatically and save as image. That's it. Isn't simple now.


Below is the sample C# Image generator from HTML text

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Drawing;
using System.Windows.Forms;
using System.Drawing.Imaging;
namespace Digiflake
{
    public class ImageGenerator
    {
        public static void RenderHTML(string html, string outputPath, Rectangle crop)
        {

            WebBrowser wb = new WebBrowser();
            wb.ScrollBarsEnabled = false;
            wb.ScriptErrorsSuppressed = true;
            wb.DocumentText = html;
            wb.Refresh();
            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);
            }
        }
    }
}
blog comments powered by Disqus
Protected by Copyscape Web Plagiarism Check
DMCA.com