Click here to Skip to main content
15,891,951 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
Dear Friends,

How can i convert my html code to image(bmp or jpg) in c# web applications.

here i am converting my grid view as html code using html render.

sample code:
C#
DataTable dt = new DataTable("RunnerUp");
            DataColumn dc1 = new DataColumn("Name", typeof(string));
            DataColumn dc2 = new DataColumn("Points", typeof(int));
            dt.Columns.Add(dc1);
            dt.Columns.Add(dc2);
            DataRow dr1 = dt.NewRow();
            dr1[0] = "Vulpes";
            dr1[1] = 235;
            DataRow dr2 = dt.NewRow();
            dr2[0] = "SP Nayak";
            dr2[1] = 135;
            DataRow dr3 = dt.NewRow();
            dr3[0] = "Krishna";
            dr3[1] = 40;
            dt.Rows.Add(dr1);
            dt.Rows.Add(dr2);
            dt.Rows.Add(dr3);
            GridView1.DataSource = dt;
            GridView1.DataBind();


            StringWriter stringWrite = new System.IO.StringWriter();
            HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
            string content;

           
            GridView1.RenderControl(htmlWrite);
            

            content = stringWrite.ToString();
            
            Bitmap m_Bitmap = new Bitmap(800, 400);

            PointF point = new PointF(0, 0);

            SizeF maxSize = new System.Drawing.SizeF(800, 800);

            CssData css = null;
            HtmlRender.Render(Graphics.FromImage(m_Bitmap), "<html><head></head><body>" + content + "</body></html>", point, maxSize, css);

            m_Bitmap.Save(@"D:\Thumbnail1.bmp");



here i am not getting colors,styles and width of the grid view headers
Kindly Provide me the solution.
Posted
Updated 6-Oct-13 17:57pm
v5
Comments
Prasad Khandekar 4-Oct-13 6:17am    
Hello Kishore,

The reason you are not getting colors, styles and widths is because if you look at the generated HTML that you are pasing to the HTML Rendered does not contain that information. I suggest you also add the styelsheet rules in the generated html, make sure all images are referenced via relative paths and that the path does exists under your applications root folder.

Please also have a look at https://github.com/ArthurHub/HTML-Renderer/blob/master/Source/Demo/DemoForm.cs.

Regards,

Regards,
D-Kishore 4-Oct-13 7:30am    
Yes Prasad, i understood what you are saying.
in the above code we are using CssData as null, How can I pass css styles here.
I am not getting any idea how to provide css styles here.

If possible can give me any example

take a look at
http://html2canvas.hertzen.com/examples.html[^]
this convert html into canvas and then convert canvas to base 64 image using
var image = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");
 
Share this answer
 
XML
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="gridtoImage.aspx.cs" Inherits="examples_gridtoImage" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
    <style type="text/css">
        .gridview
    {
        border:1px solid black;
        width:100%;
    }


    .gridview tr th
    {
       background:#1b9f7a;
       color:#fff;
       height:25px;
       font-weight:bold;
    }

    .gridview tr,
    .gridview tr td,
    .gridview tr th
    {
        padding:2px;

    }

  .gridview tr:nth-child(even)
  {
      background:#CCC;
      color:#333;
      }

  .gridview tr:nth-child(odd)
  {
      background:#FFF;
       color:#333;
  }


  .gridview tr:nth-child(even):hover
  {
      background:#999;
       color:#333;
  }

  .gridview tr:nth-child(odd):hover
  {
      background:#333;
       color:#fff;
  }
    </style>
    <script type="text/javascript" src="../build/html2canvas.js"></script>
    <script type="text/javascript">
        function CONVERT() {
            html2canvas(document.getElementById('gv'), {
                onrendered: function (canvas) {
                    // document.body.appendChild(canvas);
                    var image = canvas.toDataURL("image/png").replace("image/png", "image/octet-stream");
                    im.src = image;
                }
            });
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div id="gv">
        <asp:GridView ID="GridView1" runat="server" CssClass="gridview">
        </asp:GridView>
    </div>
    <br />
    <input type="button" value="save as image" onclick="CONVERT()"/>
    <img id="im" />
    </form>
</body>
</html>
 
Share this answer
 
Comments
D-Kishore 17-Oct-13 0:40am    
Hi pankaj,

Here I have a doubt, If it GridView1.Visible=False,I am unable to generate the image-Why because if the Grid in invisible state the html can not be generated.

In my case we have mutltiple grids like grid1,grid2 and grid3.
In the page load we are binding all the grids, here grid1.visible=true, grid2.visible=false and grid3.visible=false.

Here we need to export all three grids to different images.grid1 is getting image but rest 2 grids not commming.
Is there any possible way to to generate image if the grid is invisible
//aspx page
XML
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="convertHTMLTOImage.aspx.cs" Inherits="convertHTMLTOImage" %>

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" >

</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:TextBox ID="txtWebsiteAddress" runat="server" Text="www.google.com" />
        <asp:Button ID="btnCreateThumbnailImage" runat="server" Text="Create Thumbnail Image" OnClick="CreateThumbnailImage" /></td>
        <asp:TextBox ID="txtWidth" runat="server" Text="200" />
        <asp:TextBox ID="txtHeight" runat="server" Text="200" />
        <asp:Image ID="imgThumbnailImage" runat="server" Visible="false" />
    </div>
    </form>
</body>
</html>



//code behind
C#
using System;
using System.Collections.Generic;
using System.Linq;
using System.Drawing;
using System.Threading;
using System.Windows.Forms;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class convertHTMLTOImage : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
   
   protected void CreateThumbnailImage(object sender, EventArgs e)
        {
            string url = string.Format("http://{0}", txtWebsiteAddress.Text);
            int width = Int32.Parse(txtWidth.Text);
            int height = Int32.Parse(txtHeight.Text);
            Thumbnail thumbnail = new Thumbnail(url, 800, 600, width, height);
            Bitmap image = thumbnail.GenerateThumbnail();
            image.Save(Server.MapPath("~") + "/Thumbnail.bmp");
            imgThumbnailImage.ImageUrl = "~/Thumbnail.bmp";
            imgThumbnailImage.Visible = true;
        }     
   
}
public class Thumbnail
{
    public string Url { get; set; }
    public Bitmap ThumbnailImage { get; set; }
    public int Width { get; set; }
    public int Height { get; set; }
    public int BrowserWidth { get; set; }
    public int BrowserHeight { get; set; }

    public Thumbnail(string Url, int BrowserWidth, int BrowserHeight, int ThumbnailWidth, int ThumbnailHeight)
    {
        this.Url = Url;
        this.BrowserWidth = BrowserWidth;
        this.BrowserHeight = BrowserHeight;
        this.Height = ThumbnailHeight;
        this.Width = ThumbnailWidth;
    }
    public Bitmap GenerateThumbnail()
    {
        Thread thread = new Thread(new ThreadStart(GenerateThumbnailInteral));
        thread.SetApartmentState(ApartmentState.STA);
        thread.Start();
        thread.Join();
        return ThumbnailImage;
    }
    private void GenerateThumbnailInteral()
    {
        WebBrowser webBrowser = new WebBrowser();
        webBrowser.ScrollBarsEnabled = false;
        webBrowser.Navigate(this.Url);
        webBrowser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(WebBrowser_DocumentCompleted);
        while (webBrowser.ReadyState != WebBrowserReadyState.Complete) Application.DoEvents();
        webBrowser.Dispose();
    }
    private void WebBrowser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
    {
        WebBrowser webBrowser = (WebBrowser)sender;
        webBrowser.ClientSize = new Size(this.BrowserWidth, this.BrowserHeight);
        webBrowser.ScrollBarsEnabled = false;
        this.ThumbnailImage = new Bitmap(webBrowser.Bounds.Width, webBrowser.Bounds.Height);
        webBrowser.BringToFront();
        webBrowser.DrawToBitmap(ThumbnailImage, webBrowser.Bounds);
        this.ThumbnailImage = (Bitmap)ThumbnailImage.GetThumbnailImage(Width, Height, null, IntPtr.Zero);
    }
}
 
Share this answer
 
v2
Comments
D-Kishore 4-Oct-13 5:39am    
here we need to provide the Url to get the image.Its fine.

In my case i need to save gridview as image.
 
Share this answer
 
Comments
D-Kishore 6-Oct-13 23:20pm    
Hi pankaj, this is for win forms.
But here I am working with web forms.
why you want to convert it image. i think the best way is to just export the grid to excel with css.

C#
string css=@"<style>
.header{background-color:black;color:white;}
.row{background-color:#cccccc;color:black;}
.altrow{backround-color:#ffffff;color:black;}
</style>";
Response.Clear();
        Response.Buffer = true;
        Response.ContentType = "application/ms-excel";
        Response.AddHeader("content-disposition", "attachment;filename=MyFiles.xls");
        Response.Charset = "";
        this.EnableViewState = false;
        System.IO.StringWriter sw = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(sw);
       
        GridView1.RenderControl(htw);
Repponse.Write(css);
 Response.Write(sw.ToString());
        Response.End();
 
Share this answer
 
Comments
D-Kishore 7-Oct-13 0:45am    
My requirement is to add grid view to power point 2007.
For this I need to convert first grid view to image then second I am pushing the image to ppt.

If you have any ideas please let me know.
Zafar A khan 7-Oct-13 0:59am    
you can use GDI+ to convert it.
you can draw all the strings/columns data to bitmap
I found this perfect and simple solution for this on google.
http://www.converthtmltoimage.com/Convert-html-to-image-in-asp.net.html
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900