Here is a strange little class I wrote some time ago to render a string containing HTML into a bitmap image. It's one of those ideas that could come in handy some day, so I'll go ahead and share it.
public class HtmlHelper
{
public event EventHandler RenderComplete;
private WebBrowser browser;
private Bitmap image;
public Bitmap Image
{
get { return image; }
}
public HtmlHelper()
{
browser = new WebBrowser();
browser.DocumentCompleted +=
new WebBrowserDocumentCompletedEventHandler(
browser_DocumentCompleted
);
}
public void Render(
string html,
Size imageSize
)
{
browser.Size = imageSize;
browser.DocumentText = html;
}
void browser_DocumentCompleted(
object sender,
WebBrowserDocumentCompletedEventArgs e
)
{
image = new Bitmap(
browser.ClientRectangle.Width,
browser.ClientRectangle.Height
);
browser.DrawToBitmap(
image,
browser.ClientRectangle
);
if (RenderComplete != null)
RenderComplete(this, EventArgs.Empty);
}
}
As near as I can remember, the idea for using this class was something like this:
public class Test
{
private HtmlHelper helper;
public Test()
{
helper = new HtmlHelper();
helper.RenderComplete +=
new EventHandler(helper_RenderComplete);
helper.Render("this would be HTML", new Size(100, 100));
}
void helper_RenderComplete(object sender, EventArgs e)
{
Bitmap htmlImage = helper.Image;
// TODO : do something with the image here.
}
}
OK, now for an explanation of what it's doing. The HtmlHelper class contains an instance of the WebBrowser class. The browser is instantiated inside the HtmlHelper constructor, then the DocumentCompleted event is wired up to a private handler. Now, whenever the Render method is called by some bit of external code the result is that the HTML passed in to the method is loaded into the WebBrowser object. As soon as the browser completes the load operation it fires the DocumentCompleted event, which is handled by the browser_DocumentCompleted handler. That handler responds to the event by creating a blank bitmap and then drawing the client area of the WebBrowser control using the DrawToBitmap method. Once the HTML has been drawn to the bitmap, the RenderComplete event is called to notify the world that the HTML has been converted into an image.
Wierd huh? Oh well, it's a quick way to convert HTML to a bitmap. Hopefully someone will find a use for the code.
Have fun! 