Convert Div Content To Image Using JavaScript in ASP.NET

ASPX

  1. <html>
    <head runat="server">
    <title></title>
  2. <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>  
  3. <script type="text/javascript" src="http://cdn.rawgit.com/niklasvh/html2canvas/master/dist/html2canvas.min.js"></script>  
  4. <script type="text/javascript">  
  5. function ConvertToImage(btnExport)  
  6. {  
  7.     debugger;  
  8.     html2canvas($("#dvTable")[0]).then(function(canvas)  
  9.     {  
  10.         debugger;  
  11.         var base64 = canvas.toDataURL();  
  12.         $("[id*=hfImageData]").val(base64);  
  13.         debugger;  
  14.         __doPostBack(btnExport.name, "");  

  15.     });  
  16.     return false;  
  17. }  
  18. </script>  
  19. </head>
    <body>
    <form id="form1" runat="server">
  20. <asp:HiddenField ID="hfImageData" runat="server" ClientIDMode="Static" />  
  21. <div id="dvTable" runat="server">  
  22.     <p>Nikhil</p>  
  23. </div>  
  24. <asp:Button ID="btnExport" Text="Export to Image" runat="server" UseSubmitBehavior="false" OnClick="ExportToImage" OnClientClick="return ConvertToImage(this)" />  
  25. </form>
    </body>
    </html>

ASPX.CS
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.UI;  
  6. using System.Web.UI.WebControls;  
  7. using System.Data;  
  8. using System.IO;  
  9. using System.Text;  
  10. namespace FACETS
    {
    public partial class Invoice : System.Web.UI.Page
    {

  11.    protected void ExportToImage(object sender, EventArgs e)  
  12.    {  
  13.     string base64 = Request.Form[hfImageData.UniqueID].Split(',')[1];  
  14.     byte[] bytes = Convert.FromBase64String(base64);  
  15.     Response.Clear();  
  16.     Response.ContentType = "image/png";  
  17.     Response.AddHeader("Content-Disposition""attachment; filename=HTML.png");  
  18.     Response.Buffer = true;  
  19.     Response.Cache.SetCacheability(HttpCacheability.NoCache);  
  20.     Response.BinaryWrite(bytes);  
  21.     MemoryStream storeStream = new MemoryStream();  
  22.     MemoryStream ms = new MemoryStream(bytes);  
  23.     //write to file  
  24.     FileStream file = new FileStream(Server.MapPath("~/Images/") + "HTML100.png", FileMode.Create, 
  25.     FileAccess.Write);  
  26.     ms.WriteTo(file);  
  27.     file.Close();  
  28.     ms.Close();  
  29.     Response.End();  
  30.    }  
  31. }
  32. }