How to create downloadable link of google chart in image file - javascript

In the code, I am trying to add a hyperlink below the chart. As I click it, it will take me to a new tab with a google chart image for download.Any helps?
https://codepad.remoteinterview.io/KOURCFTBEG
As I viewed a lot of examples, most of them put
google.visualization.events.addListener(chart, 'ready',function() {
console.log(chart.getChart().getImageURI());
document.getElementById('png').innerHTML = '<a href="' +
chart.getChart().getImageURI() + '">Printable version</a>';
});
It seems to me that this would create a downloadable link to an image of the google chart on the <div id=png>But in my case, no link or clickable button is created.
google.charts.load('current', {'packages':['bar']});
google.charts.setOnLoadCallback(drawBar);
function drawBar() {
var data = google.visualization.arrayToDataTable([
['Year', 'Sales', 'Expenses', 'Profit'],
['2013', 1001, 401, 201],
['2014', 1000, 400, 200],
['2015', 1170, 460, 250],
['2016', 660, 1120, 300],
['2017', 1030, 540, 350]
]);
var options = {
chart: {
title: 'Company Performance',
subtitle: 'Sales, Expenses, and Profit: 2014-2017',
}
};
//---------------------------//
var chart = new google.charts.Bar(document.getElementById('chart_div'));
// Wait for the chart to finish drawing before calling the getImageURI() method.
google.visualization.events.addListener(chart, 'ready', function() {
console.log(chart.getChart().getImageURI());
document.getElementById('png').innerHTML = 'Printable version';
});
chart.draw(data, options);
}
<body>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi?autoload={'modules':[{'name':'visualization','version':'1.0','packages':['corechart']},{'name':'visualization','version':'1.0','packages':['controls']}]}"></script>
<div id="chart_div" style="width: 900px; height: 500px;"></div>
<div id='png'></div>
</body>
I followed the online source as similar as I can, but still get error like chart.getURI() is not function.
Here is the online source I referred most. Here is Fiddle.

Try this
<a href="link_to_image_download" target=_blank>Download here</a>
if you don't have a link to download, go to imgur.com and upload the image and add the share link into your href=

You can use print() as suggested by Google Developer API.
Here is the thing I assume you're looking for:
https://developers.google.com/chart/interactive/docs/printing

By removing getChart() in chart.getChart().getImageURI()and
,in package, by modifying bar to corechart can do the work.
google.charts.load('current', {'packages':['corechart']});
google.charts.setOnLoadCallback(drawBar);
function drawBar() {
var data = google.visualization.arrayToDataTable([
['Year', 'Sales', 'Expenses', 'Profit'],
['2013', 1001, 401, 201],
['2014', 1000, 400, 200],
['2015', 1170, 460, 250],
['2016', 660, 1120, 300],
['2017', 1030, 540, 350]
]);
var options = {
chart: {
title: 'Company Performance',
subtitle: 'Sales, Expenses, and Profit: 2014-2017',
}
};
//---------------------------//
var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));
// Wait for the chart to finish drawing before calling the getImageURI() method.
google.visualization.events.addListener(chart, 'ready', function() {
// console.log(chart.getImageURI());
document.getElementById('png').innerHTML = 'Printable version';
});
chart.draw(data, options);
}
<body>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi?autoload={'modules':[{'name':'visualization','version':'1.0','packages':['corechart']},{'name':'visualization','version':'1.0','packages':['controls']}]}"></script>
<div id="chart_div" style="width: 900px; height: 500px;"></div>
<div id='png'></div>
</body>

Related

Generate a graph in html and save as image

I want to generate a graph using certain values and capture/save the output as jpeg/png. I'm generating a graph using google charts and capturing using html2canvas. Following is the code i am trying.
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript" src="https://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript" src="html2canvas.js"></script>
<script type="text/javascript" src="jquery-3.2.1.min.js"></script>
<script language="javascript">
<script type="text/javascript">
google.charts.load('current', {'packages':['bar']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Year', 'Sales', 'Expenses', 'Profit'],
['2014', 1000, 400, 200],
['2015', 1170, 460, 250],
['2016', 660, 1120, 300],
['2017', 1030, 540, 350]
]);
var options = {
chart: {
title: 'Company Performance',
subtitle: 'Sales, Expenses, and Profit: 2014-2017',
},
bars: 'horizontal'
};
var chart = new google.charts.Bar(document.getElementById('barchart_material'));
chart.draw(data, google.charts.Bar.convertOptions(options));
}
$(document).ready(function() {
html2canvas($("#barchart_material"), {
onrendered: function(canvas) {
// canvas is the final rendered <canvas> element
var myImage = canvas.toDataURL("image/png");
window.open(myImage);
}
});
</script>
</head>
<body>
<div id="barchart_material" style="width: 900px; height: 500px;"></div>
</body>
</html>
Google graph works fine and also the opening of image captured, as a separate code, but when i merge both it doesn't.
And also, my objective is to SAVE the image locally and not just open.
Save yourself a lot of hassle and don't use the interactive Google Charts API. Use the image-based charting instead.
https://developers.google.com/chart/image/docs/gallery/bar_charts

Animate the Column chart in Android application

I want to add start up animation in google Column chart on starting the chart in Android Application. I tried to run the code given at GoogleChart that is
<html>
<head>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
google.charts.load('current', {'packages':['bar']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Year', 'Sales', 'Expenses', 'Profit'],
['2014', 1000, 400, 200],
['2015', 1170, 460, 250],
['2016', 660, 1120, 300],
['2017', 1030, 540, 350]
]);
var options = {
chart: {
title: 'Company Performance',
subtitle: 'Sales, Expenses, and Profit: 2014-2017',
animation:{
duration: 1000,
easing: 'linear',
startup: true
},
}
};
var chart = new google.charts.Bar(document.getElementById('columnchart_material'));
chart.draw(data, options);
}
</script>
</head>
<body>
<div id="columnchart_material" style="width: 900px; height: 500px;"></div>
</body>
</html>
I have added the animation properties as:
animation: {
duration: 1000,
easing: 'linear',
startup: true
},
But the chart is not animating in Android App on the start.
I also tried to run the code in browser, the chart is working fine but is not animating.
there are several options Material charts do not support, including animation
see --> Tracking Issue for Material Chart Feature Parity #2143
Material charts --> google.charts.Bar -- packages: ['bar']
Core charts --> google.visualization.ColumnChart -- packages: ['corechart']
using a Core chart with the following option will display similar to Material
theme: 'material'
when using animation, the option is not part of any other
the code in the question has animation as part of chart -- (chart.animation)
it would be more like...
var options = {
animation:{
duration: 1000,
easing: 'linear',
startup: true
},
chart: {
title: 'Company Performance',
subtitle: 'Sales, Expenses, and Profit: 2014-2017',
}
};
see following working snippet for animation using Core chart...
google.charts.load('current', {
callback: function () {
drawChart();
window.addEventListener('resize', drawChart, false);
},
packages:['corechart']
});
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Year', 'Sales', 'Expenses', 'Profit'],
['2014', 1000, 400, 200],
['2015', 1170, 460, 250],
['2016', 660, 1120, 300],
['2017', 1030, 540, 350]
]);
var options = {
animation:{
duration: 1000,
easing: 'linear',
startup: true
},
height: 600,
theme: 'material',
title: 'Company Performance'
};
var chart = new google.visualization.ColumnChart(document.getElementById('columnchart_material'));
chart.draw(data, options);
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="columnchart_material"></div>
note: Core chart does not have option for chart

Execute Google Chart API (Javascript) in php file

I am creating a mail in php, in a wordpress plugin, and would like to include an image created by the google chart api. I tried the following:
<?php
$message.= <<<HTML
<script>
google.charts.load('current', {
'packages': ['corechart']
});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Year', 'Sales', 'Expenses'],
['2013', 1000, 400],
['2014', 1170, 460],
['2015', 660, 1120],
['2016', 1030, 540]
]);
var options = {
title: 'Company Performance',
hAxis: {
title: 'Year',
titleTextStyle: {
color: '#333'
}
},
vAxis: {
minValue: 0
}
};
var chart = new google.visualization.AreaChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
HTML;
$message.=<<<HTML
<h1> test message </h1>
HTML;
$to = "test#test.com";
$subject = "test message";
$headers = "test message";
add_filter( 'wp_mail_content_type', 'set_html_content_type' );
wp_mail( $to, $subject, $message,$headers );
remove_filter( 'wp_mail_content_type', 'set_html_content_type' );
?>
My problem is that Javascript cannot be executed in a delivered mail. Hence, I am looking for a way to execute Javascript inside the script.
Any suggestions how to execute javascript in a php file to get the resulting google-api link?
I appreciate a working example!
PS.: My php version is:
> php --version
PHP 5.5.9-1ubuntu4.17 (cli) (built: May 19 2016 19:05:57)
Copyright (c) 1997-2014 The PHP Group
Zend Engine v2.5.0, Copyright (c) 1998-2014 Zend Technologies
with Zend OPcache v7.0.3, Copyright (c) 1999-2014, by Zend Technologies
with Xdebug v2.4.0, Copyright (c) 2002-2016, by Derick Rethans
google charts have a native method (getImageURI)
it creates a base64 string representation of the chart
which can be included in the src attribute of an img element
or saved to a file as .png
see Printing PNG Charts for more info
in addition, you should wait for the chart's 'ready' event to fire,
before grabbing the image
to send the chart image in an email, recommend having a page that draws the chart
then when the 'ready' event fires, sends the image string via ajax to the controller that sends the email...
see following snippet for example of getting image...
google.charts.load('current', {
callback: function () {
var data = google.visualization.arrayToDataTable([
['Year', 'Sales', 'Expenses'],
['2013', 1000, 400],
['2014', 1170, 460],
['2015', 660, 1120],
['2016', 1030, 540]
]);
var options = {
title: 'Company Performance',
hAxis: {title: 'Year', titleTextStyle: {color: '#333'}},
vAxis: {minValue: 0},
legend: {
position: 'top'
}
};
var chart = new google.visualization.AreaChart(document.getElementById('chart_div'));
google.visualization.events.addListener(chart, 'ready', function () {
document.getElementById('image_div').innerHTML = '<img src="' + chart.getImageURI() + '" />';
});
chart.draw(data, options);
},
packages: ['corechart']
});
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div>Chart</div>
<div id="chart_div"></div>
<div>Image</div>
<div id="image_div"></div>
EDIT
taking from the example above, when the chart's 'ready' event fires,
send the image string back to the same page via ajax post
then in php, check if the image was received
if received, send email, otherwise draw chart
following is a primitive example of the workflow...
<?php
if(isset($_POST['chartImage'])) {
$to = "test#test.com";
$subject = "test message";
$headers = "test message";
$message = $_POST['chartImage'];
add_filter( 'wp_mail_content_type', 'set_html_content_type' );
wp_mail( $to, $subject, $message, $headers );
remove_filter( 'wp_mail_content_type', 'set_html_content_type' );
} else {
?>
<script>
google.charts.load('current', {
callback: function () {
var data = google.visualization.arrayToDataTable([
['Year', 'Sales', 'Expenses'],
['2013', 1000, 400],
['2014', 1170, 460],
['2015', 660, 1120],
['2016', 1030, 540]
]);
var options = {
title: 'Company Performance',
hAxis: {title: 'Year', titleTextStyle: {color: '#333'}},
vAxis: {minValue: 0},
legend: {
position: 'top'
}
};
var chart = new google.visualization.AreaChart(document.getElementById('chart_div'));
google.visualization.events.addListener(chart, 'ready', function () {
// send chart image
$.ajax({
type: 'POST',
url: 'mail.php',
data: {
'chartImage': chart.getImageURI(),
},
success: function(){
console.log('email sent');
}
});
});
chart.draw(data, options);
},
packages: ['corechart']
});
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>
<?php
}
?>
Not exactly the usage of google chart api, but this might actually help you.
Google also have their Image Charts (which is deprecated, however they stated they have no plans to turn it off). You can use the Image Charts to generate the graph that you want and get an image in return.
I took the data and generated this image:
Which can be generated using this link.
I know this is not exactly the same graphics as the Chart API (and their image charts missing some great things like opacity and stuff) but It might be the quick solution that you are looking for.
And a live snippet:
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script>
google.charts.load('current', {
'packages': ['corechart']
});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Year', 'Sales', 'Expenses'],
['2013', 1000, 400],
['2014', 1170, 460],
['2015', 660, 1120],
['2016', 1030, 540]
]);
var options = {
title: 'Company Performance',
hAxis: {
title: 'Year',
titleTextStyle: {
color: '#333'
}
},
vAxis: {
minValue: 0
}
};
var chart = new google.visualization.AreaChart(document.getElementById('chart_div'));
chart.draw(data, options);
}
</script>
<div id="chart_div"></div>
<img src="https://chart.googleapis.com/chart?cht=lc&chd=t:1000,1170,660,1030|400,460,1120,540&chds=a&chxr=1,0,1200,300&chxt=x,y&chxl=0:|2013|2014|2015|2016&chs=600x200&chm=B,c2d1f0,0,0,0|B,f5c4b8,1,1,0&chtt=Company%20Performance&chts=000000,20,l&chdl=Sales|Expenses&chco=0000FF,FF0000">
You can use canvas2html.js to export chart as data URI
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<script src="canvas2html.js"></script>
<div id="chart_div"></div>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js">
</script>
<script type="text/javascript">
google.charts.load('current', {
'packages': ['corechart']
});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Year', 'Sales', 'Expenses'],
['2013', 1000, 400],
['2014', 1170, 460],
['2015', 660, 1120],
['2016', 1030, 540]
]);
var options = {
title: 'Company Performance',
hAxis: {
title: 'Year',
titleTextStyle: {
color: '#333'
}
},
vAxis: {
minValue: 0
}
};
var chart = new google.visualization
.AreaChart(document.getElementById('chart_div'));
chart.draw(data, options);
html2canvas(document.getElementById('chart_div'))
.then(function(canvas) {
var dataURL = canvas.toDataURL();
// `dataURL` : `data URI` of chart drawn on `<canvas>` element
console.log(dataURL);
})
}
</script>
</body>
</html>
plnkr http://plnkr.co/edit/WPeiFuSdFIYP9297yHYN?p=preview
I would render the charts using PhantomJS or any other headless browser good with js. Please see this link for examples:
http://johanndutoit.net/google-charts-js-api-server-side-nodejs/
Since you're using php you need to wrap the request with something like this:
http://jonnnnyw.github.io/php-phantomjs/

Google Bar Chart Not Changing Background Color

I'm using the google Material Charts static api library and I cannot figure out why the background color I"m entering is not reflecting the change when the page loads.
Here are the options I have:
var options = {
backgroundColor: '#E8E4D8',
chart: {
title: 'Coaches by Service',
subtitle: 'Coaches by Services: From 2016-09-10 until Today'
}
};
And here is how I'm instantiating the chart:
var chart = new google.charts.Bar(document.getElementById('chart_div'));
chart.draw(data, google.charts.Bar.convertOptions(options));
The chart title and subtitle are correctly displaying, any advice as to why the background color remains as the default white would be greatly appreciated.
Is there more you can share? Appears to work here...
Maybe, check the version you're loading.
Here, I use frozen version '44', instead of 'current'.
There have been recent issues.
google.charts.load('44', {
callback: drawChart,
packages: ['bar']
});
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Year', 'Sales', 'Expenses', 'Profit'],
['2014', 1000, 400, 200],
['2015', 1170, 460, 250],
['2016', 660, 1120, 300],
['2017', 1030, 540, 350]
]);
var options = {
backgroundColor: '#E8E4D8',
chart: {
title: 'Coaches by Service',
subtitle: 'Coaches by Services: From 2016-09-10 until Today'
}
};
var chart = new google.charts.Bar(document.getElementById('chart_div'));
chart.draw(data, google.charts.Bar.convertOptions(options));
}
<script src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div" style="width: 900px; height: 500px;"></div>
For me it was missing google.charts.Bar.convertOptions
Originally it was like this.
chart.draw(data, options);
This works:
chart.draw(data, google.charts.Bar.convertOptions(options));

How to add multiple material google charts to one page?

This question has been asked before, but in regards to the old corechart API, which I haven't had a problem with, not the new Material charts. For instance, the following code will create two charts as expected:
var data = [
['Year', 'Sales', 'Expenses', 'Profit'],
['2014', 1000, 400, 200],
['2015', 1170, 460, 250],
['2016', 660, 1120, 300],
['2017', 1030, 540, 350]
];
google.load('visualization', '1', {
'packages': ['corechart']
});
google.setOnLoadCallback(drawChart);
function drawChart() {
new google.visualization.ColumnChart(document.getElementById('groupedBar')).draw(
new google.visualization.arrayToDataTable(data), {});
new google.visualization.ColumnChart(document.getElementById('stackedBar')).draw(
new google.visualization.arrayToDataTable(data), {isStacked:true});
}
http://jsfiddle.net/crclayton/r67ega11/10/
However, the updated version:
google.load('visualization', '1.1', { // note version 1.1 and bar package
'packages': ['bar']
});
google.setOnLoadCallback(drawChart);
function drawChart() {
new google.charts.Bar(document.getElementById('groupedBar')).draw(
new google.visualization.arrayToDataTable(data),
google.charts.Bar.convertOptions({}));
new google.charts.Bar(document.getElementById('stackedBar')).draw(
new google.visualization.arrayToDataTable(data),
google.charts.Bar.convertOptions({
isStacked: true
}));
}
http://jsfiddle.net/crclayton/r67ega11/6/
... will only render one of the charts, sometimes the first, sometimes the second. It won't throw an error, it will simply ignore the other. I've tried breaking them up into individual functions, assigning everything to variables, resetting google.setOnLoadCallback with the same results.
I've also found that when rendering different types of charts, I don't have that problem.
Any ideas?
It's most likely the same issue that was reported in google-visualization-issues repository:
The problems people have seen with the sizing of multiple instances of
material charts should be resolved with this new release. You can
change your code to load "1.1" now so that when the candidate release
becomes available, you will be using it.
There are at least two solutions available at the moment:
Option 1. Render charts synchronously
The general idea is to render chart synchronously. Since draw function is asynchronous, we utilize ready event handler for that purpose.
Replace:
function drawChart_() {
new google.charts.Bar(document.getElementById('groupedBar')).draw(
new google.visualization.arrayToDataTable(data),
google.charts.Bar.convertOptions({}));
new google.charts.Bar(document.getElementById('stackedBar')).draw(
new google.visualization.arrayToDataTable(data),
google.charts.Bar.convertOptions({
isStacked: true
}));
}
with:
function drawChart() {
var groupedBarChart = new google.charts.Bar(document.getElementById('groupedBar'));
google.visualization.events.addOneTimeListener(groupedBarChart, 'ready', function(){
var stackedBarChart = new google.charts.Bar(document.getElementById('stackedBar'));
stackedBarChart.draw(new google.visualization.arrayToDataTable(data),google.charts.Bar.convertOptions({isStacked: true}));
});
groupedBarChart.draw(new google.visualization.arrayToDataTable(data),google.charts.Bar.convertOptions({}));
}
Example
var data = [
['Year', 'Sales', 'Expenses', 'Profit'],
['2014', 1000, 400, 200],
['2015', 1170, 460, 250],
['2016', 660, 1120, 300],
['2017', 1030, 540, 350]
];
google.load('visualization', '1.1', {
'packages': ['bar']
});
google.setOnLoadCallback(drawChart);
function drawChart() {
var groupedBarChart = new google.charts.Bar(document.getElementById('groupedBar'));
google.visualization.events.addOneTimeListener(groupedBarChart, 'ready', function(){
var stackedBarChart = new google.charts.Bar(document.getElementById('stackedBar'));
stackedBarChart.draw(new google.visualization.arrayToDataTable(data),google.charts.Bar.convertOptions({isStacked: true}));
});
groupedBarChart.draw(new google.visualization.arrayToDataTable(data),google.charts.Bar.convertOptions({}));
}
function drawChart_() {
new google.charts.Bar(document.getElementById('groupedBar')).draw(
new google.visualization.arrayToDataTable(data),
google.charts.Bar.convertOptions({}));
new google.charts.Bar(document.getElementById('stackedBar')).draw(
new google.visualization.arrayToDataTable(data),
google.charts.Bar.convertOptions({
isStacked: true
}));
}
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="chart.js"></script>
<div class="chart" id="groupedBar" style></div>
<div class="chart" id="stackedBar" style></div>
Option 2. Using the frozen version loader.
Since
The rollout of the v43 candidate release that would fix this problem
switch to using the frozen version loader.
Steps:
1)Add a reference to loader: <script
src="//www.gstatic.com/charts/loader.js"></script>
2)Then load a 43 version of library: google.charts.load("43",{packages:["bar"]});
3)Replace:
google.setOnLoadCallback(drawChart);
with
google.charts.setOnLoadCallback(drawChart);
Example
var data = [
['Year', 'Sales', 'Expenses', 'Profit'],
['2014', 1000, 400, 200],
['2015', 1170, 460, 250],
['2016', 660, 1120, 300],
['2017', 1030, 540, 350]
];
google.charts.load("43",{packages:["bar","corechart"]});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
new google.charts.Bar(document.getElementById('groupedBar')).draw(
new google.visualization.arrayToDataTable(data),
google.charts.Bar.convertOptions({}));
new google.charts.Bar(document.getElementById('stackedBar')).draw(
new google.visualization.arrayToDataTable(data),
google.charts.Bar.convertOptions({
isStacked: true
}));
}
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script src="http://www.gstatic.com/charts/loader.js"></script>
<div class="chart" id="groupedBar" style></div>
<div class="chart" id="stackedBar" style></div>

Categories