post icon

HTML5 Chart JS on ASP.NET and jQuery with export canvas image

This post will show how to use the Chart.js library to build amazing HTML5 report with jQuery and ASP.NET and how to save the rendered report image.

Chart.js uses the HTML5 <canvas> element, supported in all modern browsers, and visualize your data in 6 different ways, each of them animated, with a lot of customisation options and interactivity extensions.

In the following example we will use the Radar chart type that will output the following image:

HTML5 ChartJS Radar Report

The report required data are requested to the server with a call to a Web Method by jQuery AJAX and exposed through .NET.
The client side Javascript function is the following:

function GetReport()
{
		var filterByName = "fiter value";

		$.ajax({
				type: "POST",
				url: "Default.aspx/GetReportData",
				data: '{name: "' + filterByName + '" }',
				contentType: "application/json; charset=utf-8",
				dataType: "json",
				success: function (response) {
						var reportData = JSON.parse(response.d);
						var reportObj = document.getElementById("canvas");
						window.myRadar = new Chart(reportObj.getContext("2d")).Radar(reportData, {
								responsive: true
						});
				},
				error: function (msg) {
						alert(msg);
				}
		});
} 

The server side Web Method returns data serialized in JSON format with the following code snippet:

[WebMethod]
public static string GetReportData(string name)
{
		var result = GetDataFromDatabase();
		return new JavaScriptSerializer().Serialize(result);
}

Finally, there is the possibility to save the rendered image with the following client side function:

function SaveReport() {
		var image = document.getElementById("canvas").toDataURL("image/png");
		image = image.replace('data:image/png;base64,', '');

		$.ajax({
				type: 'POST',
				url: '/Default.aspx/SaveReport',
				data: '{ "imageData" : "' + image + '" }',
				contentType: 'application/json; charset=utf-8',
				dataType: 'json',
				success: function (msg) {
						alert('Image saved!');
				}
		});
}

and the following server side Web Method:

[WebMethod]
public static void SaveReport(string imageData)
{
		//Server.MapPath
		string path = HttpContext.Current.Server.MapPath("SavedReports") + "\\report.png";

		FileStream fs = new FileStream(path, FileMode.Create);
		BinaryWriter bw = new BinaryWriter(fs);

		byte[] data = Convert.FromBase64String(imageData);

		bw.Write(data);
		bw.Close();
}

Download the entire example of HTML5 Chart JS on ASP.NET and jQuery with export canvas image developed with Visual Studio 2013.

No comments yet.

Leave a comment

Leave a Reply

Are you human? Time limit is exhausted. Please reload CAPTCHA.