Wednesday, 27 May 2015

Convert (Export) GridView to Image using HTML5 Canvas in ASP.Net using C# and VB.Net


Here Mudassar Ahmed Khan has explained how to convert (export) GridView to Image using HTML5 Canvas in ASP.Net using C# and VB.Net.
The html2canvas JavaScript library allows to capture screenshots and convert HTML to Image using HTML5 Canvas.
HTML5 Canvas has a function named toDataURL which allows to convert its contents to Image.

In this article I will explain how to convert (export) GridView to Image using HTML5 Canvas in ASP.Net using C# and VB.Net.
The Html2Canvas JavaScript library allows to capture screenshots and convert HTML to Image using HTML5 Canvas.
HTML5 Canvas has a function named toDataURL which allows to convert its contents to Image.
 
 
HTML Markup
The HTML Markup consists of an ASP.Net GridView, a Button with UseSubmitBehavior property set to false and a Hidden Field to send the generated Base64 string to server.
The UseSubmitBehavior property is set to false in order to call the click event handler using JavaScript.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
    <Columns>
        <asp:BoundField DataField="Id" HeaderText="Customer Id" ItemStyle-Width="90" />
        <asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-Width="120" />
        <asp:BoundField DataField="Country" HeaderText="Country" ItemStyle-Width="120" />
    </Columns>
</asp:GridView>
<br />
<asp:HiddenField ID="hfImageData" runat="server" />
<asp:Button ID="btnExport" Text="Export to Image" runat="server" UseSubmitBehavior="false" OnClick="ExportToImage" OnClientClick = "return ConvertToImage(this)" />
 
 
Namespaces
You will need to import the following namespace.
C#
using System.Data;
 
VB.Net
Imports System.Data
 
 
Binding the ASP.Net GridView control
I have created a dynamic DataTable with some dummy data and it is used to populate the GridView control in the Page Load event.
Note: You can learn more about this dynamic DataTable in my article Create DataTable dynamically and bind to GridView in ASP.Net
C#
protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        DataTable dt = new DataTable();
        dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Id"typeof(int)),
                            new DataColumn("Name"typeof(string)),
                            new DataColumn("Country",typeof(string)) });
        dt.Rows.Add(1, "John Hammond""United States");
        dt.Rows.Add(2, "Mudassar Khan""India");
        dt.Rows.Add(3, "Suzanne Mathews""France");
        dt.Rows.Add(4, "Robert Schidner""Russia");
        GridView1.DataSource = dt;
        GridView1.DataBind();
    }
}
 
VB.Net
Protected Sub Page_Load(sender As Object, e As EventArgsHandles Me.Load
    If Not Me.IsPostBack Then
        Dim dt As New DataTable()
        dt.Columns.AddRange(New DataColumn(2) {New DataColumn("Id"GetType(Integer)), New DataColumn("Name"GetType(String)), New DataColumn("Country"GetType(String))})
        dt.Rows.Add(1, "John Hammond""United States")
        dt.Rows.Add(2, "Mudassar Khan""India")
        dt.Rows.Add(3, "Suzanne Mathews""France")
        dt.Rows.Add(4, "Robert Schidner""Russia")
        GridView1.DataSource = dt
        GridView1.DataBind()
    End If
End Sub
 
 
Capturing Screenshot of GridView using Html2Canvas and HTML5
When the Export button is clicked, the JavaScript ConvertToImage function is executed which captures a screenshot of ASP.Net GridView using Html2Canvas libraryand then saves the Base64 string into the Hidden Field.
Finally the Server Side event of the Button is triggered using the ASP.Net __doPostBack method.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="http://cdn.rawgit.com/niklasvh/html2canvas/master/dist/html2canvas.min.js"></script>
<script type="text/javascript">
    function ConvertToImage(btnExport) {
        html2canvas($("[id*=GridView1]")[0]).then(function (canvas) {
            var base64 = canvas.toDataURL();
            $("[id*=hfImageData]").val(base64);
            __doPostBack(btnExport.name, "");
        });
        return false;
    }
</script>
 
 
Handing the Base64 string and exporting it as Image file
Inside the click event handler of the Button, the Base64 string is fetched from the Hidden Field and it is converted to an Array of Bytes.
Finally the array of bytes are written to the Response and downloaded as Image file.
C#
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=GridView.png");
    Response.Buffer = true;
    Response.Cache.SetCacheability(HttpCacheability.NoCache);
    Response.BinaryWrite(bytes);
    Response.End();
}
 
VB.Net
Protected Sub ExportToImage(sender As Object, e As EventArgs)
    Dim base64 As String = Request.Form(hfImageData.UniqueID).Split(",")(1)
    Dim bytes As Byte() = Convert.FromBase64String(base64)
    Response.Clear()
    Response.ContentType = "image/png"
    Response.AddHeader("Content-Disposition""attachment; filename=GridView.png")
    Response.Buffer = True
    Response.Cache.SetCacheability(HttpCacheability.NoCache)
    Response.BinaryWrite(bytes)
    Response.End()
End Sub
 
 
Screenshot
Convert (Export) GridView to Image using HTML5 Canvas in ASP.Net using C# and VB.Net
 
 
Browser Compatibility
The above code has been tested in the following browsers only in versions that support HTML5. 

Convert (Export) GridView to Image using HTML5 Canvas in ASP.Net using C# and VB.Net


Here Mudassar Ahmed Khan has explained how to convert (export) GridView to Image using HTML5 Canvas in ASP.Net using C# and VB.Net.
The html2canvas JavaScript library allows to capture screenshots and convert HTML to Image using HTML5 Canvas.
HTML5 Canvas has a function named toDataURL which allows to convert its contents to Image.

In this article I will explain how to convert (export) GridView to Image using HTML5 Canvas in ASP.Net using C# and VB.Net.
The Html2Canvas JavaScript library allows to capture screenshots and convert HTML to Image using HTML5 Canvas.
HTML5 Canvas has a function named toDataURL which allows to convert its contents to Image.
 
 
HTML Markup
The HTML Markup consists of an ASP.Net GridView, a Button with UseSubmitBehavior property set to false and a Hidden Field to send the generated Base64 string to server.
The UseSubmitBehavior property is set to false in order to call the click event handler using JavaScript.
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
    <Columns>
        <asp:BoundField DataField="Id" HeaderText="Customer Id" ItemStyle-Width="90" />
        <asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-Width="120" />
        <asp:BoundField DataField="Country" HeaderText="Country" ItemStyle-Width="120" />
    </Columns>
</asp:GridView>
<br />
<asp:HiddenField ID="hfImageData" runat="server" />
<asp:Button ID="btnExport" Text="Export to Image" runat="server" UseSubmitBehavior="false" OnClick="ExportToImage" OnClientClick = "return ConvertToImage(this)" />
 
 
Namespaces
You will need to import the following namespace.
C#
using System.Data;
 
VB.Net
Imports System.Data
 
 
Binding the ASP.Net GridView control
I have created a dynamic DataTable with some dummy data and it is used to populate the GridView control in the Page Load event.
Note: You can learn more about this dynamic DataTable in my article Create DataTable dynamically and bind to GridView in ASP.Net
C#
protected void Page_Load(object sender, EventArgs e)
{
    if (!this.IsPostBack)
    {
        DataTable dt = new DataTable();
        dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Id"typeof(int)),
                            new DataColumn("Name"typeof(string)),
                            new DataColumn("Country",typeof(string)) });
        dt.Rows.Add(1, "John Hammond""United States");
        dt.Rows.Add(2, "Mudassar Khan""India");
        dt.Rows.Add(3, "Suzanne Mathews""France");
        dt.Rows.Add(4, "Robert Schidner""Russia");
        GridView1.DataSource = dt;
        GridView1.DataBind();
    }
}
 
VB.Net
Protected Sub Page_Load(sender As Object, e As EventArgsHandles Me.Load
    If Not Me.IsPostBack Then
        Dim dt As New DataTable()
        dt.Columns.AddRange(New DataColumn(2) {New DataColumn("Id"GetType(Integer)), New DataColumn("Name"GetType(String)), New DataColumn("Country"GetType(String))})
        dt.Rows.Add(1, "John Hammond""United States")
        dt.Rows.Add(2, "Mudassar Khan""India")
        dt.Rows.Add(3, "Suzanne Mathews""France")
        dt.Rows.Add(4, "Robert Schidner""Russia")
        GridView1.DataSource = dt
        GridView1.DataBind()
    End If
End Sub
 
 
Capturing Screenshot of GridView using Html2Canvas and HTML5
When the Export button is clicked, the JavaScript ConvertToImage function is executed which captures a screenshot of ASP.Net GridView using Html2Canvas libraryand then saves the Base64 string into the Hidden Field.
Finally the Server Side event of the Button is triggered using the ASP.Net __doPostBack method.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="http://cdn.rawgit.com/niklasvh/html2canvas/master/dist/html2canvas.min.js"></script>
<script type="text/javascript">
    function ConvertToImage(btnExport) {
        html2canvas($("[id*=GridView1]")[0]).then(function (canvas) {
            var base64 = canvas.toDataURL();
            $("[id*=hfImageData]").val(base64);
            __doPostBack(btnExport.name, "");
        });
        return false;
    }
</script>
 
 
Handing the Base64 string and exporting it as Image file
Inside the click event handler of the Button, the Base64 string is fetched from the Hidden Field and it is converted to an Array of Bytes.
Finally the array of bytes are written to the Response and downloaded as Image file.
C#
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=GridView.png");
    Response.Buffer = true;
    Response.Cache.SetCacheability(HttpCacheability.NoCache);
    Response.BinaryWrite(bytes);
    Response.End();
}
 
VB.Net
Protected Sub ExportToImage(sender As Object, e As EventArgs)
    Dim base64 As String = Request.Form(hfImageData.UniqueID).Split(",")(1)
    Dim bytes As Byte() = Convert.FromBase64String(base64)
    Response.Clear()
    Response.ContentType = "image/png"
    Response.AddHeader("Content-Disposition""attachment; filename=GridView.png")
    Response.Buffer = True
    Response.Cache.SetCacheability(HttpCacheability.NoCache)
    Response.BinaryWrite(bytes)
    Response.End()
End Sub
 
 
Screenshot
Convert (Export) GridView to Image using HTML5 Canvas in ASP.Net using C# and VB.Net
 
 
Browser Compatibility
The above code has been tested in the following browsers only in versions that support HTML5.