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

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 = &quot;fiter value&quot;;

		$.ajax({
				type: &quot;POST&quot;,
				url: &quot;Default.aspx/GetReportData&quot;,
				data: '{name: &quot;' + filterByName + '&quot; }',
				contentType: &quot;application/json; charset=utf-8&quot;,
				dataType: &quot;json&quot;,
				success: function (response) {
						var reportData = JSON.parse(response.d);
						var reportObj = document.getElementById(&quot;canvas&quot;);
						window.myRadar = new Chart(reportObj.getContext(&quot;2d&quot;)).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(&quot;canvas&quot;).toDataURL(&quot;image/png&quot;);
		image = image.replace('data:image/png;base64,', '');

		$.ajax({
				type: 'POST',
				url: '/Default.aspx/SaveReport',
				data: '{ &quot;imageData&quot; : &quot;' + image + '&quot; }',
				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(&quot;SavedReports&quot;) + &quot;\\report.png&quot;;

		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.

In questo articolo verrà illustrato come è possibile utilizzare la libreria Chart.js per costruire sorprendenti report in HTML5 utilizzando jQuery e ASP.NET e come è possibile salvare l’immagine del report generato.

Chart.js utilizza l’elemento <canvas> di HTML5, che è supportato da tutti i moderni browser, e da la possibilità di visualizzare i dati in 6 modi diversi, in modo animato, con diverse opzioni di personalizzazione ed estensioni interattive.

Nell’esempio seguente verrà utilizzato il grafico di tipo Radar che darà in output la seguente immagine:

HTML5 ChartJS Radar Report

I dati necessari al report vengono richiesti al server con una chiamata jQuery AJAX ad un Web Method esposto mediante .NET con la seguente funziona Javascript:

function GetReport()
{
		var filterByName = &quot;fiter value&quot;;

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

Il Web Method lato server, restituisce i dati serializzati in formato JSON:

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

Infine, viene data la possibilità di salvare il report come immagine (png) con la seguente funzione lato client:

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

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

e con il seguente Web Method lato server:

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

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

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

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

Scarica l’esempio completo di HTML5 Chart JS on ASP.NET and jQuery with export canvas image sviluppato con Visual Studio 2013.

Lascia un commento

Il tuo indirizzo email non sarà pubblicato. I campi obbligatori sono contrassegnati *