1. Code
  2. JavaScript

Creating Flash Charts From Google Spreadsheets

Scroll to top
18 min read

With Google docs gaining popularity, it is anticipated that in the near future there will be a great demand for connecting it to external systems for various purposes such as data interchange, data visualization, etc. In this article, I will show you how to connect Flash based charts (FusionCharts) to Google Spreadsheets and plot live data using JavaScript.

Before I delve into the technicalities involved in retrieving data from Google spreadsheets, I will provide an overview to FusionCharts and begin my explanation from root level – this is for the benefit of those who have come across FusionCharts for first time. A no-restriction version of FusionCharts can be downloaded from www.fusioncharts.com/download. FusionCharts also has a totally free version at www.fusioncharts.com/free; but this article uses a lot of features from FusionCharts v3, so it is recommended to download FusionCharts v3.

All the code associated with this article (and some more examples as well) are present as a download with this article.

Quick Introduction to FusionCharts

FusionCharts is a Flash charting solution that helps you create animated & interactive charts for web pages. FusionCharts is essentially a collection of SWF files which run inside Adobe Flash player, and accept data and configuration settings in XML, thereby making it cross-script and cross-platform compatible. The XML is intuitive and it can be learnt easily with the help of an exhaustive online documentation, which can be accessed from www.fusioncharts.com/docs.

Additionally, if you're not a die-hard fan of XML, FusionCharts comes with an extensive range of API’s, which help in its implementation with all forms of web programming technologies such as ASP, ASP.NET, PHP, Ruby on Rails, Python etc.

Quick Example of Building a Chart with FusionCharts

FusionCharts SWF’s can be embedded in a HTML page either using the <object>/<embed> tags or through FusionCharts JavaScript class. Using the JavaScript class for embedding the chart is advisable, as this ensures that the charts will function smoothly on all browsers. The XML data source can be provided to the chart either as an external file, or it can be directly incorporated within the HTML page.

Let's quickly build a chart to depict the data shown in the table below.

Appliance

Units in Watt

Lighting

1200

Heater

1800

Desktop

1500

Cooler

1200

Elevator

1500

Microwave Oven

1600

Television

1500

Washing Machine

2800

Music System

2200

Cleaners

600

The following piece of code constitutes the XML data source pertaining to the data table above:

1
2
<chart numberSuffix='W' caption='Electricity Consumption' formatNumberScale='0'>
3
	<set label='Lighting' value='1200' />
4
	<set label='Heater' value='1800' />
5
	<set label='Desktop' value='1500' />
6
	<set label='Cooler' value='1200' />
7
	<set label='Elevator' value='1500' />
8
	<set label='Microwave Oven' value='1600' />
9
	<set label='Television' value='1500' />
10
	<set label='Washing Machine' value='2800' />
11
	<set label='Music System' value='2200' />
12
	<set label='Cleaners' value='600' />
13
</chart>

Quite simple and intuitive - isn't it? The <chart> element is the root element that contains visual and functional configuration of chart. Each <set> element represents a data item in the chart. This data structure pertains to single series charts in FusionCharts, where you've only dataset. Multiple data-sets call for multi-series XML format, which involves a couple more XML elements.

Now that the XML is ready (we've saved it as myXML.xml), we need to embed the chart into an HTML page with the help of the following code:

1
<script src="FusionCharts.js" type="text/javascript"></script>
2
3
	<div id="firstChartDiv">
4
		My Chart DIV
5
	</div>
6
	<script type="text/javascript">
7
		// Initialize chart

8
		var chart = new FusionCharts("Pie3D.swf", "firstChartId", "600", "300", "0", "0");
9
		
10
		// feed chart dta source

11
        chart.setDataURL("myXML.xml");
12
		
13
		// render chart into DIV

14
        chart.render("firstChartDiv");
15
		
16
	</script>

The code (above) creates a DIV named firstChartDiv which will serve as a container for the chart. Up next, an instance of the FusionCharts object is created using JavaScript and following parameters are passed into it.

  • Name of the SWF file to be used (Pie3d.swf in this case)
  • Name of the Chart (firstChartId in this case)
  • Height of the chart in pixels
  • Width of the chart in pixels
  • >

The subsequent line of code provides the name of the external XML data source file (myXML.xml in this case). And the final line of the JavaScript code indicates the name of the container DIV in which the chart will render. While using the JavaScript class for embedding the chart, it is necessary to create a container DIV for the chart.

The following chart is generated by the code. The image belows shows a static version; the actual chart is animated and allows interactivity like slicing of pies, rotation of chart, tool-tips etc.

Now, that we have covered the process of creating charts using static data source, let's move on to the process of rendering a chart using data obtained from Google spreadsheet.

Connecting these charts to Google Docs Spreadsheet

Google Docs spreadsheets transfer data in form of JSON feeds. So, in order to render charts using data obtained from Google spreadsheet, it is important to convert the acquired JSON feeds into XML format as required by FusionCharts.

There are multiple ways to convert JSON into XML. Either, you could write your own code to take each JSON element and convert into XML. Or, you could make use of rule based engines like JsonT to aid in this process. We'll use JsonT for this article, as it helps us do things easier and quicker. JsonT can be downloaded from http://goessner.net/articles/jsont/

Using JsonT one can easily define a rule to convert JSON data into a string of desired format. Following is an example of JSON data:

1
	var coffeeSalesJSON = {
2
		"Espresso" 		: "5000",
3
		"Cappuccino"		: "6000",
4
		"Latte"			: "7000",
5
		"affogato" 		: "4000",
6
		"Cortado" 		: "2000",
7
		"Macchiato"	 	: "3000",
8
		"Frappuccino"		: "6000"
9
	};

The following code converts the JSON data (displayed abve) into FusionCharts XML format and then creates a chart out of it.

1
2
	var JSONParseRules = {
3
	 "self" : "<chart>\n {@getData(#)}</chart>", 
4
	 "getData" : function(x){ 
5
			var c = ""; 
6
			for( var i in x	) 
7
				c += "\n<set label='" + i + "' value='" + x[i]  + "'/>"; 
8
			return c;
9
	   }
10
	 }
11
12
	var coffeeChartStrXML = jsonT( coffeeSalesJSON, JSONParseRules );
13
	
14
	var coffeeChart = new FusionCharts("Column3D.swf", "CoffeeChartId", "600", "350", "0", "0");
15
	
16
	coffeeChart.setDataXML( coffeeChartStrXML );		   
17
	
18
	coffeeChart.render( "coffeeChartDiv" );

For the code to work, it is essential to link jsont.js JavaScript file to the HTML page.

The code (above) builds XMLstring from JSON data with the help of a rule, that iterates through each key-value pairs of JSON data and treats key names as categories and values as data values for the chart. You may read more on JsonT rules at http://goessner.net/articles/jsont/. Next, we use that XML and build the chart.

In order to use a Google spreadsheet as a dynamic data source for the chart, it is essential to publish it for public viewing. At the time of publishing the document for public viewing – Google generates a unique key. This key is used for requesting data feeds from Google; hence it is important to preserve the key.

Please note that, in order to work with Google's JSON feeds it is essential to modify josnt.js slightly. I have made minor modifications to jsont.js in order to prevent the conflict that arises due to Jsont.js’s use of $ as an object pointer and Google generated JSON feed's use of $ as property name. I have modified Jsont.js so that it uses # as an object pointer.

For this demonstrative example I created a Google spreadsheet, which included three sheets – each of which, contained yearly sales data for the years 2006, 2007 and 2008. The spreadsheet can be viewed through the following link http://docs.google.com.

    
   

The process of creating a Google spreadsheet

The following code will help you render a chart that is plotted using data drawn from Google spreadsheet:

1
<script src="FusionCharts.js" type="text/javascript"></script><br /><br /><body onload="initpage();">
2
	<div id="coffeeChartDiv">Chart Will load up here</div>
3
</body>
4
<script type="text/javascript">
5
	// stores the array of spreadsheets present in the specified google spreadsheet

6
	var sheets;
7
	
8
	// stores the count of spreadsheets parsed 

9
	// When sheetCount becomes equal to the length of number of sheet 

10
	// I render the chart finally

11
	var sheetsCount = 0;
12
	
13
	// stores various chart configurations to be added in <chart> element of XML
14
	// you can modify these pas per your needs

15
	var chartConfigJSON = { rotateValues:1, placeValuesInside:1, numberPrefix:'£' };
16
17
	// store XML elements in array (later to be joined as string)

18
	var strXML=Array(4);
19
20
	/* 

21
	* Fetches Google Spreadsheet data

22
	* pass your spreadsheet key as parameter or the full url of the feed

23
	* @param 	key 		 key of Spreadsheet or the full url of the feed

24
	* @param	callback	 your callback function name as string

25
	* @param	feedtype	 can be json/json-in-script

26
	* @param	feedformat list/cells/spreadsheets

27
	*/
28
	function getGoogleSpreadsheetData(key, callback, feedtype,feedformat ){
29
		
30
		// default values

31
		feedtype = feedtype || "json-in-script";
32
		feedformat  = feedformat || "list" ;
33
		callback = callback || "gssdatafeedcallback";
34
		
35
		// build feed url

36
		var href;
37
		if( key.search("http")<0)
38
			href = 'http://spreadsheets.google.com/feeds/'+ feedformat + '/' + key + '/public/values';
39
		else
40
			href = key;
41
		
42
  		// create script element

43
		var script = document.createElement('script');
44
		// add spreadsheet feed as the source of the script

45
		script.setAttribute('src', href+'?alt='+feedtype+'&callback='+callback);
46
	  	script.setAttribute('id', 'jsonScript');
47
	  	script.setAttribute('type', 'text/javascript');
48
		// add script to fetch Google Spreadsheet feed

49
	  	document.documentElement.firstChild.appendChild(script);
50
	}
51
		
52
	// Callback function to parse spreadsheet data and 

53
	// fetch data from each spreadsheet present in the spreadsheet

54
	// the json data would be passed as parameter

55
	function parseSpreadsheet(jsonsheets){
56
		// get chart caption as the name of the spreadsheet

57
		chartConfigJSON.caption = jsonsheets.feed.title.$t;
58
		// get the array of all spreadsheets

59
		sheets =jsonsheets.feed.entry;
60
	
61
		// fetch data from each spreadsheet

62
		for(var i=0;i<sheets.length;i++)
63
			getGoogleSpreadsheetData(sheets[i].link[0].href, "parsespreadsheet", "json-in-script" );	
64
		
65
	}
66
	
67
	// This function is the actual chart data generator

68
	// It receives each spreadsheet JSON data feed

69
	// parses using jsonT into required XML

70
	function parsespreadsheet(gjson)
71
	{
72
		// Since one feed is received increase count by 1

73
		sheetsCount++;
74
		
75
		// will store JSON parsing rule as per jsonT library

76
		var rule;
77
		
78
		// get array of spreadsheet data

79
		var feedEntries = gjson.feed.entry;
80
		
81
		// get the name of the sheet as series name of the chart dataset

82
		var seriesName = gjson.feed.title.$t;
83
		
84
		// get the column name as per google spreadsheet's column name

85
		var colName;
86
		if( feedEntries[0])
87
			colName =feedEntries[0].content.$t.match(/.+(?=\:)/);
88
89
		// initializing XML building array only once.

90
		// Hence checking if the first element is empty

91
		// I also fetch the category names from the first sheet

92
		// This process I keep simple for demonstration 

93
		if (!strXML[0]){
94
			strXML[0]="<chart>";
95
			// set xAxisName (hardcode it as Google List Data 

96
			// API does not provide this name as yet in JSON) 

97
			chartConfigJSON.xAxisName= "Products";
98
			// Set the column name as the yAxisName

99
			if (feedEntries[0]) chartConfigJSON.yAxisName = colName;  
100
			// if so I add all chart configurations etc. (one time)

101
			for(var i in chartConfigJSON) {
102
				strXML[0]= strXML[0].replace(/(<chart[^>]*)(>)/,"$1 "+ i+"='"+chartConfigJSON[i] +"' $2");
103
			}
104
			
105
			strXML[3] ="</chart>";
106
			
107
			// Build JsonT rule to parse category names

108
			rule = {
109
				"self":"<categories>{#}</categories>",
110
				"self[*]":"<category label='{#.title.$t}'/>"
111
			};
112
			
113
			// store category labels in array using jsonT

114
			strXML[1] =  jsonT(feedEntries, rule);
115
			
116
			// initialize data storing element of the XML building array

117
			strXML[2] = "";
118
		}
119
		
120
		// From each JSON spreadsheet I would build datasets of data

121
		// Build jsonT rule to parse JSON data

122
		rule = {
123
				"self":"<dataset  seriesName='"+seriesName+"'>{#}</dataset>",
124
				"self[*]":"<set value='{#.gsx$"+colName+".$t}'/>"
125
		
126
		};
127
		
128
		// apply rule to data entries to 

129
		// and store in XML building array

130
		strXML[2]+=jsonT(feedEntries, rule);
131
		
132
		// when all charts finishes rendering 

133
		// i.e. sheetsCount is equal to the length of sheets array

134
		// enable Export button

135
		if(sheetsCount==sheets.length)
136
		{
137
			renderChart();
138
		}
139
	}
140
	
141
	// render chart 

142
	function renderChart(){
143
		// initialize Multiseries Column 3D chart

144
		var chart = new FusionCharts("MSColumn3D.swf", "CoffeeChartId", "600", "350", "0", "0");
145
		// set chart data

146
		chart.setDataXML(strXML.join(''));
147
		// render chart

148
		chart.render("coffeeChartDiv");
149
	}
150
	
151
	//initialize page that initializes google JSON feed 

152
	function initpage()
153
	{
154
		// fetch data from Google Spreadsheet

155
		// Pass the Key of the published spreadsheet as first parameter

156
		// in second parameter pass the callback function

157
		getGoogleSpreadsheetData('p06JfhjnK8PwEWRkmlWiiQg', "parseSpreadsheet", "json-in-script", "spreadsheets" );
158
	}
159
	
160
</script>

Here's how the code works:

  1. The program initiates by declaring a variable named ‘sheets’ for storing the array of spreadsheet definitions obtained from the specified Google Spreadsheet. It then declares the ‘sheetCount’ counter variable which keeps track of number of spreadsheets from which data has been received. This counter ensures that the chart renders, once all the data has been received.

  2. Up next, the ‘chartConfigJSON’ object is declared to store the chart configuration settings.

  3. The XML that would be gradually built, will be stored in an array named ‘strXML’. When XML building process is finally complete, the elements of the array would be joined to form the XML string.

  4. Moving on, the initpage() function placed in the body of the HTML is called when the onload event occurs. This function in turn calls the getGoogleSpreadsheetData() which requests for the spreadsheet data in form of JSON feeds. The getGoogleSpreadsheetData() function requests for the spreadsheet data by sending the Google generated spreadsheet key, it also specifies the feed format and handles the feed once it has been received.

  5. 1
    getGoogleSpreadsheetData("p06JfhjnK8PwEWRkmlWiiQg",  "parseSpreadsheet", "json-in-script",  "spreadsheets" )
    
  6. Once this feed has been received, a callback function parseSpreadsheet () is fired. This function gets the spreadsheet name from jsonsheets.feed.title.$t and then it loops through each spreadsheet entry. Each spreadsheet entry provides feed links to all available feed types (spreadsheet/list/cell/gViz) in the link array. After acquiring a list of feed type, getGoogleSpreadsheetData() function requests for JSON feeds from each spreadsheet.

    1
    getGoogleSpreadsheetData( sheets[i].link[0].href,  "parsespreadsheet",  "json-in-script" );
    



    The link[0].href element contains the URL for available feed types, which is passed to the function. After the feed has been received the callback function parsespreadsheet is called and JSON data is passed to it.

  7. Once the feed for each spreadsheet is received, the sheetCount is increased by 1.
  8. Feeds obtained from each spreadsheet would be regarded as a dataset for the chart. Hence, the feed title is taken as the series name for each dataset.
  9. 1
    var seriesName = gjson.feed.title.$t;
    
  10. The configuration settings of the chart are stored in strXML[0]. Please note that the function parsespreadsheet() would be called multiple times for as many times as the number of spreadsheets contained within the Google spreadsheet. The code contains a condition which prevents further repetition of this process.
  11. Chart categories are defined using the first spreadsheet. The list of category name is built using jsonT.
  12. 1
    rule = { 		
    
    2
    "self":"<categories>{#}</categories>", 
    
    3
    "self[*]":"<category label='{#.title.$t}'/>" 	
    
    4
    };
    
    5
    6
    strXML[1] =  jsonT(feedEntries, rule);
    
  13. Finally, jsonT is called into action to populating the dataset values.:
  14. 1
    2
    rule = {
    
    3
    "self":"<dataset  seriesName='"+seriesName+"'>{#}</dataset>",
    
    4
    "self[*]":"<set value='{#.gsx$"+colName+".$t}'/>"
    
    5
    };
    
    6
    7
    strXML[2]+=jsonT(feedEntries, rule);
    

    When this code is executed, the following chart would be generated in your page.

The multi-series chart created using data obtained from Google spreadsheet document

Now that we've been able to generate a chart, let's take it a step further and add the ability to export it as images or PDFs. This will be very useful for emailing to your colleagues.

PDF Export

The latest version of FusionCharts (v3.1) provides comprehensive range of export features. You can export the charts as PDFs, PNGs or JPEGs - both at client-side or save them on server as well.

In our example, since we're not using any server-side scripts, we'll stick to client side export. At client side, the export feature is implemented with the help of FusionCharts Client-side export components - collective name given to FusionChartsExportComponent.js and FCExporter.swf. FCExporter.swf is the client-side export engine that allows charts to be exported. The JavaScript file provides an interface between the chart and the FCExporter.swf.

This JavaScript class facilitates rendering of the FCExporter.swf, which is the engine for export and also serves as a graphical user interface. With the help of export API's you can easily customize the appearance of the GUI. The API's also enable you to control the functional aspects of the GUI. The following code illustrates the process:

1
<script type="text/javascript" src="FusionChartsExportComponent.js"></script>
2
<div id="componentContainer"></div>

1
2
	  function loadExportComponent()
3
	  {
4
	
5
		// initialize FusionCharts Export Component

6
		// put all settings in parameters

7
		exportComponent = new FusionChartsExportObject('exportComponentH', 'FCExporter.swf', 
8
			{	
9
				width: '250', 
10
				height: '250', 
11
				fullMode:1, 
12
				saveMode:'both', 
13
				defaultExportFormat:"pdf" ,
14
				showAllowedTypes:1,
15
				saveAllTitle:'Save All', 
16
				btnSaveAllTitle:'As Single File' , 
17
				defaultExportFileName:"SalesReport"
18
19
			},
20
			{ 
21
				exportFormat:"PDF", 
22
				exportHandler:"exportComponentH", 
23
				exportAtClient:1
24
			}
25
		);
26
27
		exportComponent.Render('componentContainer');
28
	}

The code (above) configures the export GUI so that, it displays a button which triggers the export process. Additionally, each chart would be listed in the GUI panel and the user would be presented with an option to export all the charts into a single PDF file. The GUI will also allow the user to change the default export format from PDF to jpeg or png.

In order to demonstrate the export process, I have added the code for configuring the export GUI, to the code that renders a chart based on data derived from Google spreadsheet document. However, I have made some modifications to the code, so that it will now render three single-series charts instead of a single multi-series chart. Each chart will displaying data pertaining to a particular spreadsheet.

Following is the combined code:

1
2
<html>
3
<head>
4
<script type="text/javascript" src="FusionCharts.js"></script>
5
<script type="text/javascript" src="JSON/jsont.js"></script>
6
<script type="text/javascript" src="FusionChartsExportComponent.js"></script>
7
<script type="text/javascript">
8
9
	// stores the array of spreadsheets present in the specified google spreadsheet

10
	var sheets;
11
	// stores the count of spreadsheets and reduce count when the sheet feed is received

12
	// I use this to add a counter to the chart id and chart container id

13
	// When sheetCount becomes equal to the length of number of sheet 

14
	// I enable export HTML button

15
	var sheetsCount = 0;
16
	
17
	// stores various chart configurations to be added in <chart> element of XML
18
	// you can modify these pas per your needs

19
	var chartConfigJSON={ 
20
		rotateLabels	: 1, 
21
		rotateValues	: 1, 
22
		numberPrefix	: '£', 
23
		exportEnabled	: 1, 
24
		exporthandler	:'exportComponentH', 
25
		exportAtClient	: 1 ,
26
		placeValuesInside : 1 
27
	};
28
	
29
	// Fetching Google Spreadsheet data

30
	// pass your spreadsheet key as parameter or the full url of the feed

31
	// callback		: your callback function name as string

32
	// feedtype 	: can be json/json-in-script

33
	// feedformat : list/cells/spreadsheets

34
	function getGoogleSpreadsheetData(key, callback, feedtype,feedformat ){
35
		
36
		// default values

37
		feedtype = feedtype || "json-in-script";
38
		feedformat  = feedformat || "list" ;
39
		callback = callback || "gssdatafeedcallback";
40
		
41
		// build feed url

42
		var href;
43
		if( key.search("http")<0)
44
			href = 'http://spreadsheets.google.com/feeds/'+ feedformat + '/' + key + '/public/values';
45
		else
46
			href = key;
47
		
48
  		// create script element

49
		var script = document.createElement('script');
50
		// add spreadsheet feed as the source of the script

51
		script.setAttribute('src', href+'?alt='+feedtype+'&callback='+callback);
52
	  	script.setAttribute('id', 'jsonScript');
53
	  	script.setAttribute('type', 'text/javascript');
54
		// add script to fetch Google Spreadsheet feed

55
	  	document.documentElement.firstChild.appendChild(script);
56
	}
57
	
58
	// Callback function to parse spreadsheet data and 

59
	// fetch data from each spreadsheet present in the spreadsheet

60
	function parseSpreadsheet(jsonsheets){
61
		// get chart caption as the name of the spreadsheet

62
		chartConfigJSON.subCaption = jsonsheets.feed.title.$t;
63
		// get the array of all spreadsheets

64
		sheets =jsonsheets.feed.entry;
65
	
66
		// fetch data from each spreadsheet

67
		for(var i=0;i<sheets.length;i++)
68
			getGoogleSpreadsheetData(sheets[i].link[0].href, "parsespreadsheet", "json-in-script" );		
69
	}
70
	
71
	// This function is the actual chart data generator

72
	// It receives each spreadsheet JSON data feed

73
	// parses using jsonT into required XML

74
	function parsespreadsheet(gjson)
75
	{
76
		// Since one feed is received increase sheet count by 1

77
		sheetsCount++;
78
79
		// will store JSON parsing rule as per jsonT library

80
		var rule;
81
		
82
		// get array of spreadsheet data

83
		var strXML=Array(3);
84
		
85
		// get chart caption from spreadsheet's name

86
		chartConfigJSON.caption =gjson.feed.title.$t;
87
		
88
		//stores the data entries separately 

89
		var feedEntries = gjson.feed.entry;
90
	
91
		// set xAxisName (hardcode it as Google List Data 

92
		// API does not provide this name as yet in JSON) 

93
		chartConfigJSON.xAxisName= "Products";
94
95
		var colName;
96
		if( feedEntries[0]){
97
			// get the column name as per google spreadsheet's column name	

98
			// Set the column name as the yAxisName

99
			colName =feedEntries[0].content.$t.match(/.+(?=\:)/);
100
			chartConfigJSON.yAxisName = colName;  
101
		}
102
103
		// store chart element in XML building array

104
		strXML[0]="<chart>";
105
 
106
 		// iterate through chartConfigJSON and build chart attributes

107
		for(var i in chartConfigJSON) {
108
			strXML[0]= strXML[0].replace(/(<chart[^>]*)(>)/,"$1 "+ i+"='"+chartConfigJSON[i] +"' $2");
109
		}
110
		
111
		strXML[2] ="</chart>";
112
113
		// Build rule to parse JSON feed and add chart values in <set> element of XML
114
		rule = {
115
				"self":"{#}",
116
				"self[*]":"<set value='{#.gsx$"+colName+".$t}' label='{#.title.$t}'/>"
117
		};
118
119
		// apply the rule to JSON feed

120
		strXML[1]+=jsonT(feedEntries, rule);
121
		
122
		// pass the XML to chart rendering function

123
		renderChart(strXML.join(''));
124
	}
125
	
126
	// this function renders chart

127
	function renderChart(strXML){
128
	
129
		// create a new span

130
		var div = document.createElement('span');
131
		div.setAttribute('id','chartDivId'+sheetsCount);
132
		document.documentElement.lastChild.appendChild(div);
133
		
134
		// render single series column 3D chart		

135
		var  chart = new FusionCharts("Column3D.swf", "CoffeeChartId"+sheetsCount, "300", "300", "0", "1");
136
		
137
		// set chart data XML

138
		chart.setDataXML(strXML);
139
		
140
		// render chart

141
		chart.render('chartDivId'+sheetsCount);
142
	}
143
	
144
	// This function is called automatically form chart when 

145
	// the chart completes rendering

146
	function FC_Rendered(DOMId){
147
		
148
		// when all charts finishes rendering 

149
		// i.e. sheetsCount is equal to the length of sheets array

150
		// enable Export button

151
		if (sheetsCount==sheets.length) { 
152
			document.getElementById("exportButtonPDF").disabled=false; 
153
		}
154
	}
155
156
	function loadExportComponent()
157
	{
158
	
159
		// initialize FusionCharts Export Component

160
		// put all settings in parameters

161
		exportComponent = new FusionChartsExportObject('exportComponentH', 'FCExporter.swf', 
162
			{	
163
				width: '250', 
164
				height: '250', 
165
				fullMode:1, 
166
				saveMode:'both', 
167
				defaultExportFormat:"pdf" ,
168
				showAllowedTypes:1,
169
				saveAllTitle:'Save All', 
170
				btnSaveAllTitle:'As Single File' , 
171
				defaultExportFileName:"SalesReport"
172
			},
173
			{ 
174
				
175
				exportFormat:"PDF", 
176
				exportHandler:"exportComponentH", 
177
				exportAtClient:1
178
			}
179
		);
180
181
		exportComponent.Render('componentContainer');
182
	}
183
184
	// call the export all event of FusionChaRTS Export Component

185
	// This function finds all FusionCharts present in the page and 

186
	// exports all to the export component

187
	function exportCharts(){
188
		exportComponent.BeginExportAll();
189
	}
190
191
	function pageinit()
192
	{
193
		// initialize export button as disabled

194
		document.getElementById("exportButtonPDF").disabled=true;
195
196
		// fetch Google Spreadsheet data

197
		getGoogleSpreadsheetData('p06JfhjnK8PwEWRkmlWiiQg', "parseSpreadsheet", "json-in-script", "spreadsheets" );
198
		
199
		// load FusionCharts Export component

200
		loadExportComponent();	
201
	}
202
	
203
</script>
204
</head>
205
206
<body onload="pageinit();" >
207
       <input type="button" class="button" value="Export as PDF" onclick="exportCharts()" id="exportButtonPDF" disabled="disabled" />
208
      <div id="componentContainer"></div>
209
</body>
210
</html>

Following is the depiction of the export process as seen from the client side:

  • The charts render in the browser.
  • Charts are converted to bitmap when 'Export As PDF' button is clicked.
  • The export GUI displays a list of charts to be exported.
  • The charts are saved into a single PDF file when the user clicks the 'As Single PDF' button.
  • And with that, we end this article. There are a lot more features offered by FusionCharts that can potentially be put into use. Creating charts from data stored in Google spreadsheets is just one example of innovations which are possible with FusionCharts. Thanks for reading!