-->

How to export google charts as image file in asp.net using jquery.


Introduction

In this post, I am explain how to export google charts as image file in asp.net using jquery.
Reporting plays an important role in many information systems and Export option is most important part of reporting. So, users want to be able to export the charts to email them to colleagues or for embedding in presentations. With this example we can easily do this and allow your users to export the google charts as images (PNG).

Part 2 : How to export google charts as image to server disk file in asp.net.

Steps :

Step - 1 : Create New Project.

Go to File > New > Project > Select asp.net MVC4 web application > Entry Application Name > Click OK > Select Basic Application > Select view engine Razor > OK

Step-2: Add a Database.

Go to Solution Explorer > Right Click on App_Data folder > Add > New item > Select SQL Server Database Under Data > Enter Database name > Add.

Step-3: Create table for fetch data.

Open Database > Right Click on Table > Add New Table > Add Columns > Save > Enter table name > Ok.
In this example, I have used one tables as below

Step-4: Add Entity Data Model.

Go to Solution Explorer > Right Click on Project name form Solution Explorer > Add > New item > Select ADO.net Entity Data Model under data > Enter model name > Add.
A popup window will come (Entity Data Model Wizard) > Select Generate from database > Next >
Chose your data connection > select your database > next > Select tables > enter Model Namespace > Finish.

Step-5: Create a Controller .

Go to Solution Explorer > Right Click on Controllers folder form Solution Explorer > Add > Controller > Enter Controller name > Select Templete "empty MVC Controller"> Add.

Here I have created a controller "HomeController"

Step-6: Add new action into your controller for Get View

Here I have added "Index" Action into "Home" Controller. Please write this following code

public ActionResult GoogleChartColumn()
{
    return View();
}
        

Step-7: Add view for your Action & design for show google chart.

Right Click on Action Method (here right click on Index action) > Add View... > Enter View Name > Select View Engine (Razor) >Add.
View (Html Code)
@{
   ViewBag.Title = "GoogleChartColumn";
}

<h2>Google Chart</h2>
<div style="max-width:800px">
    <div id="chart_div">

    </div>
    <a id="export" href="#" style="display:none" download="FileName">Export as Image</a>
</div>
         

Step-8: Add js code for fetch data and render google chart.

@* Add script for fetch data as json format  render google chart *@
@section scripts{
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>
    <script>
        google.load('visualization', "1", { packages: ["corechart"] });
        var chartData; 
        //Load Data

        
        $.ajax({
            url: '/Home/GetSalesData',
            dataType: 'json',
            type: 'GET',
            success: function (d) {
                chartData = d;
            },
            error: function () {
                alert('Error! Please try again.');
            }
        }).done(function () {
            drawChart();
        });

        //Draw Chart

        function drawChart() {
            var data = google.visualization.arrayToDataTable(chartData);
            var options = { title: "Company Sales Report", pointSize: 5, 'chartArea': { 'width': '60%', 'height': '80%', left: 120, top: 30 } };
            var columnChart = new google.visualization.ColumnChart(document.getElementById('chart_div'));

            google.visualization.events.addListener(columnChart, 'ready', function () {
                var exportData = columnChart.getImageURI();
                $('#export').attr({ 'href': exportData, 'download': 'Company Sales Report' }).show();

            });
            columnChart.draw(data, options);
        }
    </script>
}
        
Complete View (Html Page)
@{
    ViewBag.Title = "GoogleChartColumn";
}

<h2>Google Chart</h2>
<div style="max-width:800px">
    <div id="chart_div">

    </div>
    <a id="export" href="#" style="display:none" download="FileName">Export as Image</a>
</div>

@* Add script for fetch data as json format  render google chart *@
@section scripts{
    <script type="text/javascript" src="https://www.google.com/jsapi"></script>    
    <script>
<script type="text/javascript" src="https://www.google.com/jsapi?autoload= 
{'modules':[{'name':'visualization','version':'1.1','packages':
['corechart']}]}"></script>
        google.load('visualization', "1", { packages: ["corechart"] });
        var chartData; 
        //Load Data

        
        $.ajax({
            url: '/Home/GetSalesData',
            dataType: 'json',
            type: 'GET',
            success: function (d) {
                chartData = d;
            },
            error: function () {
                alert('Error! Please try again.');
            }
        }).done(function () {
            drawChart();
        });

        //Draw Chart

        function drawChart() {
            var data = google.visualization.arrayToDataTable(chartData);
            var options = { title: "Company Sales Report", pointSize: 5, 'chartArea': { 'width': '60%', 'height': '80%', left: 120, top: 30 } };
            var columnChart = new google.visualization.ColumnChart(document.getElementById('chart_div'));

            google.visualization.events.addListener(columnChart, 'ready', function () {
                var exportData = columnChart.getImageURI();
                $('#export').attr({ 'href': exportData, 'download': 'Company Sales Report' }).show();

            });
            columnChart.draw(data, options);
        }
    </script>
}
        

Step-9: Add another action into your controller for Get Sales data

Here I have added "SalesDataYearWise" Action into "Home" Controller. Please write this following code

public JsonResult GetSalesData()
{
    using (MyDatabaseEntities dc = new MyDatabaseEntities())
    {
        var v = (from a in dc.SalesRecords
                    group a by a.SalesDate.Year into g
                    select new
                    {
                        Year = g.Key,
                        Electronics = g.Sum(a=>a.Electronics),
                        BookAndMedia = g.Sum(a=>a.BookAndMedia),
                        HomeAndKitchen = g.Sum(a=>a.HomeAndKitchen)
                    });
        if (v != null)
        {
            var chartData = new object[v.Count() + 1];
            chartData[0] = new object[]{
                "Year",
                "Electronics",
                "Book and Media",
                "Home and Kitchen"
            };
            int j = 0;
            foreach (var i in v)
            {
                j++;
                chartData[j] = new object[] {i.Year.ToString(), i.Electronics, i.BookAndMedia, i.HomeAndKitchen };

            }
            return new JsonResult { Data = chartData, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
        }

    }
    return new JsonResult { Data = null, JsonRequestBehavior = JsonRequestBehavior.AllowGet };
}
        

Step-10: Run Application.



Hello ! My name is Sourav Mondal. I am a software developer working in Microsoft .NET technologies since 2010.

I like to share my working experience, research and knowledge through my site.

I love developing applications in Microsoft Technologies including Asp.Net webforms, mvc, winforms, c#.net, sql server, entity framework, Ajax, Jquery, web api, web service and more.