TECHNOLOGIES
FORUMS
JOBS
BOOKS
EVENTS
INTERVIEWS
Live
MORE
LEARN
Training
CAREER
MEMBERS
VIDEOS
NEWS
BLOGS
Sign Up
Login
No unread comment.
View All Comments
No unread message.
View All Messages
No unread notification.
View All Notifications
C# Corner
Post
An Article
A Blog
A News
A Video
An EBook
An Interview Question
Ask Question
Convert Div Content To Image Using JavaScript in ASP.NET
Nikhil Sangani
Nov 05
2015
Code
13.7
k
0
2
facebook
twitter
linkedIn
Reddit
WhatsApp
Email
Bookmark
expand
ASPX
<html>
<head runat="server">
<title></title>
<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)
{
debugger;
html2canvas($(
"#dvTable"
)[0]).then(function(canvas)
{
debugger;
var base64 = canvas.toDataURL();
$(
"[id*=hfImageData]"
).val(base64);
debugger;
__doPostBack(btnExport.name,
""
);
});
return
false
;
}
</script>
</head>
<body>
<form id="form1" runat="server">
<asp:HiddenField ID=
"hfImageData"
runat=
"server"
ClientIDMode=
"Static"
/>
<div id=
"dvTable"
runat=
"server"
>
<p>Nikhil</p>
</div>
<asp:Button ID=
"btnExport"
Text=
"Export to Image"
runat=
"server"
UseSubmitBehavior=
"false"
OnClick=
"ExportToImage"
OnClientClick=
"return ConvertToImage(this)"
/>
</form>
</body>
</html>
ASPX.CS
using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Web;
using
System.Web.UI;
using
System.Web.UI.WebControls;
using
System.Data;
using
System.IO;
using
System.Text;
namespace FACETS
{
public partial class Invoice : System.Web.UI.Page
{
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=HTML.png"
);
Response.Buffer =
true
;
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.BinaryWrite(bytes);
MemoryStream storeStream =
new
MemoryStream();
MemoryStream ms =
new
MemoryStream(bytes);
//write to file
FileStream file =
new
FileStream(Server.MapPath(
"~/Images/"
) +
"HTML100.png"
, FileMode.Create,
FileAccess.Write);
ms.WriteTo(file);
file.Close();
ms.Close();
Response.End();
}
}
}
ASP.NET
JavaScript
Convert Div Content To Image