[c#] Convert HTML string to image

I have a string variable which holds HTML markup. This HTML markup basically represents the email content.

Now I want to create an image from this string content which actually holds the HTML markup. I don't want to create the HTML file by writing this content into them. I just want to create an image file using this string.

Here's what I have:

string emailBody="<html><head></head><body><p>This is my text<p>...</body</html>"

How can I create an Image from this emailBody string content?

This question is related to c# html asp.net

The answer is


       <!--ForExport data in iamge -->
        <script type="text/javascript">
            function ConvertToImage(btnExport) {
                html2canvas($("#dvTable")[0]).then(function (canvas) {
                    var base64 = canvas.toDataURL();
                    $("[id*=hfImageData]").val(base64);
                    __doPostBack(btnExport.name, "");
                });
                return false;
            }
        </script>

        <!--ForExport data in iamge -->

        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
        <script src="../js/html2canvas.min.js"></script> 





<table>
                <tr>
                    <td valign="top">
                        <asp:Button ID="btnExport" Text="Download Back" runat="server" UseSubmitBehavior="false"
                            OnClick="ExportToImage" OnClientClick="return ConvertToImage(this)" />
                        <div id="dvTable" class="divsection2" style="width: 350px">
                            <asp:HiddenField ID="hfImageData" runat="server" />
                            <table width="100%">
                                <tr>
                                    <td>
                                        <br />

                                    </td>
                                </tr>
                                <tr>
                                    <td>
                                        <asp:Label ID="Labelgg" runat="server" CssClass="labans4" Text=""></asp:Label>
                                    </td>
                                </tr>

                            </table>
                        </div>
                    </td>
                </tr>
            </table>


         protected void ExportToImage(object sender, EventArgs e)
                {
                    string base64 = Request.Form[hfImageData.UniqueID].Split(',')[1];
                    byte[] bytes = Convert.FromBase64String(base64);
                    Response.Clear();
                    Response.ContentType = "image/png";
                    Response.AddHeader("Content-Disposition", "attachment; filename=name.png");
                    Response.Buffer = true;
                    Response.Cache.SetCacheability(HttpCacheability.NoCache);
                    Response.BinaryWrite(bytes);
                    Response.End();

                }

Try the following:

using System;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;

class Program
{
    static void Main(string[] args)
    {
        var source =  @"
        <!DOCTYPE html>
        <html>
            <body>
                <p>An image from W3Schools:</p>
                <img 
                    src=""http://www.w3schools.com/images/w3schools_green.jpg"" 
                    alt=""W3Schools.com"" 
                    width=""104"" 
                    height=""142"">
            </body>
        </html>";
        StartBrowser(source);
        Console.ReadLine();
    }

    private static void StartBrowser(string source)
    {
        var th = new Thread(() =>
        {
            var webBrowser = new WebBrowser();
            webBrowser.ScrollBarsEnabled = false;
            webBrowser.DocumentCompleted +=
                webBrowser_DocumentCompleted;
            webBrowser.DocumentText = source;
            Application.Run();
        });
        th.SetApartmentState(ApartmentState.STA);
        th.Start();
    }

    static void 
        webBrowser_DocumentCompleted(
        object sender, 
        WebBrowserDocumentCompletedEventArgs e)
    {
        var webBrowser = (WebBrowser)sender;
        using (Bitmap bitmap = 
            new Bitmap(
                webBrowser.Width, 
                webBrowser.Height))
        {
            webBrowser
                .DrawToBitmap(
                bitmap, 
                new System.Drawing
                    .Rectangle(0, 0, bitmap.Width, bitmap.Height));
            bitmap.Save(@"filename.jpg", 
                System.Drawing.Imaging.ImageFormat.Jpeg);
        }
    }
}

Note: Credits should go to Hans Passant for his excellent answer on the question WebBrowser Control in a new thread which inspired this solution.


Examples related to c#

How can I convert this one line of ActionScript to C#? Microsoft Advertising SDK doesn't deliverer ads How to use a global array in C#? How to correctly write async method? C# - insert values from file into two arrays Uploading into folder in FTP? Are these methods thread safe? dotnet ef not found in .NET Core 3 HTTP Error 500.30 - ANCM In-Process Start Failure Best way to "push" into C# array

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to asp.net

RegisterStartupScript from code behind not working when Update Panel is used You must add a reference to assembly 'netstandard, Version=2.0.0.0 No authenticationScheme was specified, and there was no DefaultChallengeScheme found with default authentification and custom authorization How to use log4net in Asp.net core 2.0 Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state How to create roles in ASP.NET Core and assign them to users? How to handle Uncaught (in promise) DOMException: The play() request was interrupted by a call to pause() ASP.NET Core Web API Authentication Could not load file or assembly 'CrystalDecisions.ReportAppServer.CommLayer, Version=13.0.2000.0 WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery