02
Jul
2022
2022
Convert HTML String To Image In C#
So, for exporting your html to a image we have to use WebBrowser class available in Asp.Net mvc. So we will first create html that we want to export as image. You can copy the method from the code below
using System; using System.Drawing; using System.Windows.Forms; using System.Threading;
public void CreateHtmlToImage() { var source = @"<!DOCTYPE html> <html> <head><meta http-equiv='X-UA-Compatible' content='IE=Edge' /> <style> table { font-family: arial, sans-serif; border-collapse: collapse; width: 100%; } td, th { border: 1px solid #dddddd; text-align: left; padding: 8px; } tr:nth-child(even) { background-color: #dddddd; } </style> </head> <body style='width:1000px'> <h2>HTML Table</h2> <table style='width:1000px'> <tr> <th>Company</th> <th>Contact</th> </tr> <tr> <td>Alfreds Futterkiste</td> <td>Maria Anders</td> </tr> <tr> <td>Centro comercial Moctezuma</td> <td>Francisco Chang</td> </tr> <tr> <td>Ernst Handel</td> <td>Roland Mendel</td> </tr> <tr> <td>Island Trading</td> <td>Helen Bennett</td> </tr> <tr> <td>Laughing Bacchus Winecellars</td> <td>Yoshi Tannamuri</td> </tr> <tr> <td>Magazzini Alimentari Riuniti</td> <td>Giovanni Rovelli</td> </tr> </table> </body> </html>"; var filename = @"F://Image.jpg"; var th = new Thread(() => { var webBrowser = new WebBrowser(); webBrowser.ScrollBarsEnabled = false; webBrowser.IsWebBrowserContextMenuEnabled = true; webBrowser.AllowNavigation = true; webBrowser.DocumentCompleted += webBrowserDocumentCompleted; webBrowser.DocumentText = source; webBrowser.Name = filename; webBrowser.Width = 1000; Application.Run(); }); th.SetApartmentState(ApartmentState.STA); th.Start(); Task.Run(() => th); Task.WaitAll(); }
So, after you use this on your controller , you have to add this in your controller.This is Completed event which will be fired one your html output is ready to be saved as image. It will save the bitmap image on the location which is passed as filename. So, now execute the code and you will see , your html is saved as image in the specified location.
static void webBrowserDocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) { var webBrowser = (WebBrowser)sender; int scrollWidth = webBrowser.Document.Body.ScrollRectangle.Width; int scrollHeight = webBrowser.Document.Body.ScrollRectangle.Height; using (Bitmap bitmap = new Bitmap(scrollWidth, scrollHeight)) { webBrowser.DrawToBitmap(bitmap, new System.Drawing.Rectangle(0, 0, bitmap.Width, bitmap.Height)); bitmap.Save(webBrowser.Name, System.Drawing.Imaging.ImageFormat.Jpeg); } }
This, is the image output that we got in our case. So this is how you can convert html string to image in c# asp.net.