Export Charts to Image File using AngularJS in ASP.Net

Last Reply 7 months ago By dharmendr

Posted 7 months ago

How to export chart to image in angularjs in asp.net

Posted 7 months ago

Hi rani,

AngularJS Charts: Implement HTML5 Canvas Charts using Chart.js in AngularJS

Using the above article i have created the example.

Now please take its reference and correct your code.

HTML

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/angularjs/1.3.9/angular.min.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.bundle.min.js"></script>
<script type="text/javascript">
    var app = angular.module('MyApp', [])
    app.controller('MyController', function ($scope, $http) {
        $scope.PopulateChart = function (chartType) {
            $http.post('VB.aspx/GetChartData', { headers: { 'Content-Type': 'application/json'} })
            .then(function (response) {
                var labels = response.data.d.Labels;
                var data = response.data.d.Datasets;
                var colors = response.data.d.Colors;
                var ctx = document.getElementById("dvCanvas").getContext('2d');
                var myChart = new Chart(ctx, {
                    type: chartType,
                    data: {
                        datasets: [{ data: data, backgroundColor: colors}],
                        labels: labels
                    },
                    options: { responsive: false }
                });
            });
        }
        $scope.ExportChart = function () {
            var base64 = document.getElementById("dvCanvas").toDataURL("image/jpg");
            $http.post('Default.aspx/Export', { base64: base64 }, { headers: { 'Content-Type': 'application/json'} })
        }
    });
</script>
<div ng-app="MyApp" ng-controller="MyController">
    <label for="ChartType">
        <input type="radio" name="ChartType" ng-click="PopulateChart('horizontalBar')" />Bar
        <input type="radio" name="ChartType" ng-click="PopulateChart('bar')" />Column
        <input type="radio" name="ChartType" ng-click="PopulateChart('pie')" />Pie
        <input type="radio" name="ChartType" ng-click="PopulateChart('doughnut')" />Doughnut
    </label>
    <button type="button" ng-click="ExportChart()">Export</button>
    <hr />
    <canvas id="dvCanvas" height="200" width="500"></canvas>
</div>

Namespaces

C#

using System.Data;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Services;

VB.Net

Imports System.Data
Imports System.IO
Imports System.Linq
Imports System.Web
Imports System.Web.Services

Code

C#

[WebMethod]
public static ChartData GetChartData()
{
    // Get your DataTable from DataBase.
    DataTable dt = new DataTable();
    dt.Columns.AddRange(new DataColumn[] { new DataColumn("City"), new DataColumn("Count", typeof(int)), new DataColumn("Color") });
    dt.Rows.Add("Albuquerque", 18, "#FFD700");
    dt.Rows.Add("Anchorage", 10, "#FAEBD7");
    dt.Rows.Add("Boise", 31, "#7FFFD4");
    dt.Rows.Add("Butte", 3, "#808080");
    dt.Rows.Add("Elgin", 5, "#F5F5DC");
    dt.Rows.Add("Eugene", 11, "#FFE4C4");

    string[] labels = (from p in dt.AsEnumerable()
                        select p.Field<string>("City")).ToArray();
    int[] datasets = (from p in dt.AsEnumerable()
                        select p.Field<int>("Count")).ToArray();
    string[] colors = (from p in dt.AsEnumerable()
                        select p.Field<string>("Color")).ToArray();

    ChartData chartData = new ChartData();
    chartData.Labels = labels;
    chartData.Datasets = datasets;
    chartData.Colors = colors;
    return chartData;
}

[WebMethod]
public static void Export(string base64)
{
    // Convert Base64 string to Byte Array.
    byte[] bytes = Convert.FromBase64String(base64.Split(',')[1]);
    // Save the Byte Array as Image File.
    string filePath = string.Format("~/Files/{0}.jpg", DateTime.Now.ToString("yyyyMMddHHmms"));
    File.WriteAllBytes(HttpContext.Current.Server.MapPath(filePath), bytes);
}

public class ChartData
{
    public string[] Labels { get; set; }
    public int[] Datasets { get; set; }
    public string[] Colors { get; set; }
}

VB.Net

<WebMethod()>
Public Shared Function GetChartData() As ChartData
    Dim dt As DataTable = New DataTable()
    dt.Columns.AddRange(New DataColumn() {New DataColumn("City"), New DataColumn("Count", GetType(Integer)), New DataColumn("Color")})
    dt.Rows.Add("Albuquerque", 18, "#FFD700")
    dt.Rows.Add("Anchorage", 10, "#FAEBD7")
    dt.Rows.Add("Boise", 31, "#7FFFD4")
    dt.Rows.Add("Butte", 3, "#808080")
    dt.Rows.Add("Elgin", 5, "#F5F5DC")
    dt.Rows.Add("Eugene", 11, "#FFE4C4")
    Dim labels As String() = (From p In dt.AsEnumerable() Select p.Field(Of String)("City")).ToArray()
    Dim datasets As Integer() = (From p In dt.AsEnumerable() Select p.Field(Of Integer)("Count")).ToArray()
    Dim colors As String() = (From p In dt.AsEnumerable() Select p.Field(Of String)("Color")).ToArray()
    Dim chartData As ChartData = New ChartData()
    chartData.Labels = labels
    chartData.Datasets = datasets
    chartData.Colors = colors
    Return chartData
End Function
<WebMethod()>
Public Shared Sub Export(ByVal base64 As String)
    ' Convert Base64 string to Byte Array.
    Dim bytes As Byte() = Convert.FromBase64String(base64.Split(","c)(1))
    ' Save the Byte Array as Image File.
    Dim filePath As String = String.Format("~/Files/{0}.jpg", DateTime.Now.ToString("yyyyMMddHHmms"))
    File.WriteAllBytes(HttpContext.Current.Server.MapPath(filePath), bytes)
End Sub
Public Class ChartData
    Public Property Labels As String()
    Public Property Datasets As Integer()
    Public Property Colors As String()
End Class

Screenshot

Saved Images