-->

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


Introduction

In this post, I am explain how to export google charts as image to server disk file in asp.net.
In the previous example How to export google charts as image file in asp.net using jquery. , we have seen how to export google charts as image at the client side, In this example I will explain Saving exported google chart on server disk.

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" onclick="ExportImageToServer()" >Export as Image to Server</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;
        var exportData;
        //Load Data
        $.ajax({
            url: '/Home/GetSalesData',
            dataType: 'json',
            type: 'GET',
            success: function (d) {
                chartData = d;
                console.log(chartData);
            },
            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 ()
            {
                exportData = columnChart.getImageURI();
                $('#export').show();
            });
            columnChart.draw(data, options);
        }

        function ExportImageToServer() {
            var string = exportData;
            var image = string.replace('data:image/png;base64,', '');
            $.ajax({
                type: "POST",
                url: "/home/ExportReport",
                data: '{"imageData":"' + image + '"}',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (d) {
                    alert(d);
                },
                error: function () {
                    alert('Error! Please try again.');
                }
            });
        }
    </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" onclick="ExportImageToServer()" >Export as Image to Server</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>
        google.load('visualization', "1", { packages: ["corechart"] });
        var chartData;
        var exportData;
        //Load Data
        $.ajax({
            url: '/Home/GetSalesData',
            dataType: 'json',
            type: 'GET',
            success: function (d) {
                chartData = d;
                console.log(chartData);
            },
            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 ()
            {
                exportData = columnChart.getImageURI();
                $('#export').show();
            });
            columnChart.draw(data, options);
        }

        function ExportImageToServer() {
            var string = exportData;
            var image = string.replace('data:image/png;base64,', '');
            $.ajax({
                type: "POST",
                url: "/home/ExportReport",
                data: '{"imageData":"' + image + '"}',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (d) {
                    alert(d);
                },
                error: function () {
                    alert('Error! Please try again.');
                }
            });
        }
    </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: Add another action into your controller for Save image to server disk.

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

public JsonResult ExportReport(string imageData)
{
    string fileName = Path.Combine(Server.MapPath("~/ExportImage"), DateTime.Now.ToString("ddMMyyyyhhmmsstt") + ".png");
    using (FileStream fs = new FileStream(fileName, FileMode.Create))
    {
        using (BinaryWriter bw = new BinaryWriter(fs))
        {
            byte[] data = Convert.FromBase64String(imageData);
            bw.Write(data);
            bw.Close();
        }
    }
    return new JsonResult { Data = "Image saved successfully" };
}
        

Step-11: 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.