Converting Google Chart into Image - javascript

I'm trying convert a Google Chart into a image like this link but I don't understand about the line
var chartArea = chartContainer.getElementsByTagName('iframe')[0].contentDocument.getElementById('chartArea');
The code generated by the Google Chart, doesn't create any iFrame or elements called chartArea
Can someone help me ?
UPDATED
Follow the source of the generated by the chart, when I transform him into a image
http://chart.googleapis.com/chart?cht=lc&chs=500x200&chtt=Acessos%20ao%20im%C3%B3vel%20dos%20ultimos%20sete%20dias&chxt=x%2Cy&chxl=0%3A%7C24%2F01%7C25%2F01%7C26%2F01%7C27%2F01%7C28%2F01%7C29%2F01%7C30%2F01%7C1%3A%7C%7C0%7C&chdlp=r&chdl=San%7CSite%7CAtendimento&chco=ff8a00%2C585857%2C5501ff&chd=e%3Af.f.f.f.f.f.f.%2Cf.f.f.f.f.f.f.%2Cf.f.f.f.f.f.f.

This can be done by following the steps on this page. Note that the code in the article is based on an old version of Google Visualization which used iframes, and will not work as posted. However, you can do the same using the following code (found in the comments):
var svg = $(chartContainer).find('svg').parent().html();
var doc = chartContainer.ownerDocument;
var canvas = doc.createElement('canvas');
canvas.setAttribute('style', 'position: absolute; ' + '');
doc.body.appendChild(canvas);
canvg(canvas, svg);
var imgData = canvas.toDataURL("image/png");
canvas.parentNode.removeChild(canvas);
return imgData;
Note: I did not create this code, it was originally created by the author of the above site (Riccardo Govoni) and updated in the comments section by user Thomas.

You can get a PNG version of your chart using chart.getImageURI() like following:
Needs to be after the chart is drawn, so in the ready event!
var my_div = document.getElementById('my_div');
var my_chart = new google.visualization.ChartType(chart_div);
google.visualization.events.addListener(my_chart, 'ready', function () {
my_div.innerHTML = '<img src="' + chart.getImageURI() + '">';
});
my_chart.draw(data);

Related

How to convert as pdf while dealing with xml nodes in mxGraph?

I am implementing the graph editor using mxGraph javascript library and able to display the diagram and save the diagram.
Now,I have to export the diagram in to PDF file.
Primary question is,
Is there any other builtin feature is available on mxGraph library itself?
I used mxImageExport() class to exporting PNG image then its is redirecting to null url page.redirect page image
Here is the code:
function convertPDF() {
var graph = universalGraph; // get xml form the graph stored in graph variable
var xmlDoc = mxUtils.createXmlDocument();
var root = xmlDoc.createElement('output');
xmlDoc.appendChild(root);
var xmlCanvas = new mxXmlCanvas2D(root);
var imgExport = new mxImageExport();
imgExport.drawState(graph.getView().getState(graph.model.root), xmlCanvas);
var bounds = graph.getGraphBounds();
var w = Math.ceil(bounds.x + bounds.width);
var h = Math.ceil(bounds.y + bounds.height);
var xml = mxUtils.getXml(root);
new mxXmlRequest('export', 'format=png&w=' + w +
'&h=' + h + '&bg=#F9F7ED&xml=' + encodeURIComponent(xml))
.simulate(document, '_self');
}
(or) else I have to use regular JS PDF library?(I cannot convert the HTML content inside tag in to PDF, While converting it is showing
graph's background only no single shapes are in it. Since it is from XML nodes, I referred the internet and asked me to convert from XML in to SVG then PDF
but this method also not work because I have received the blank PDF file.)
Here is the code:
function savePDF() {
var imgData;
html2canvas($(".svgClass"), {
useCORS: true,
onrendered: function(canvas) {
imgData = canvas.toDataURL(
'image/png');
console.log(imgData);
var doc = new jsPDF('p', 'pt', 'a4');
doc.addImage(imgData, 'PNG', 10, 10);
doc.save('sample-file.pdf');
window.open(imgData);
}
});
}

How to covert multiple svg to png in single html page?

I used d3 and venn.js for creating this venn diagram.
The code goes here : Svg actually created inside div venn2 by these scripts.
<div id="venn2"></div>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="js/venn.js"></script>
<script>
var sets = [
{sets:["A"], size: 12, label: "A"},
{sets:["B"], size:12, label: "B"},
{sets: ["A", "B"], size: 4, label: "AB"}
];
var chart = venn.VennDiagram()
.wrap(false)
.fontSize("14px")
.width(400)
.height(400);
function updateVenn(sets) {
var div = d3.select("#venn2").datum(sets);
var layout = chart(div),
textCentres = layout.textCentres;
div.selectAll(".label").style("fill", "white");
div.selectAll(".venn-circle path").style("fill-opacity", .6);
return layout;
}
</script>
The script I got here to convert svg to png via canvas.
<canvas id="canvas" ></canvas>
<div id="png-container" ></div>
<script>
var svgString = new XMLSerializer().serializeToString(document.querySelector('svg'));
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var DOMURL = self.URL || self.webkitURL || self;
var img = new Image();
var svg = new Blob([svgString], {type: "image/svg+xml;charset=utf-8"});
var url = DOMURL.createObjectURL(svg);
img.onload = function() {
ctx.drawImage(img, 0, 0);
var png = canvas.toDataURL("image/png");
document.querySelector('#png-container').innerHTML = '<img src="'+png+'"/>';
DOMURL.revokeObjectURL(png);
};
img.src = url;
</script>
So, the venn diagram as svg was created inside venn2 div by script 1 and svg then written as a png by script 2.
It worked perfectly fine for one svg image per page.
When I have more than one such svg venn diagrams on single html page. Only the first gets converted to png.
But I am unable to fetch the svg at position 2 and 3 or more to convert to png.
I am stuck at this code
var svgString = new XMLSerializer().serializeToString(querySelectorAll('svg'));
where 'svg' means only first svg i guess but not later.
I can't even create svgs with different "id" as svg is formed by d3 and venn.js scripts.
The question is that : How to convert all svg images in a html page
when I don't know their id to png images via above code?
I do not know how to parse this whole string var svgString to convert all to different png images?
In case someone else comes looking for sample code, I figured it out as follows.
My case: I had an svg with two layers drawn by plotly. I was only getting the first layer like the OP. Plotly drew into an element with id="chart". A new canvas already created with id="layer0".
Eventually I needed to send back to PHP as a dataURL so:
var nodes = document.getElementById("chart").querySelectorAll('svg');
for (var i = 0; i < nodes.length; i++) {
result = new XMLSerializer().serializeToString(nodes[i]);
eval('layer'+[i]+'chart').src = 'data:image/svg+xml;base64,' + btoa(result);
}
elem0 = document.getElementById("layer0");
ctx0 = elem0.getContext("2d");
layer0chart.onload = function() {
ctx0.drawImage(layer0chart,0,0,w*1.5,h*1.5);
ctx0.drawImage(layer1chart,0,0,w*1.5,h*1.5);
canvasdata = elem0.toDataURL();
console.log(canvasdata);
}
I appreciate the help from #BioDeveloper and #RobertLongson. The key for me ultimately was to also make sure the toDataURL was being called as an image was being loaded. Cheers.

Turning HTML content in to a canvas element [duplicate]

It would be incredibly useful to be able to temporarily convert a regular element into a canvas. For example, say I have a styled div that I want to flip. I want to dynamically create a canvas, "render" the HTMLElement into the canvas, hide the original element and animate the canvas.
Can it be done?
There is a library that try to do what you say.
See this examples and get the code
http://hertzen.com/experiments/jsfeedback/
http://html2canvas.hertzen.com/
Reads the DOM, from the html and render it to a canvas, fail on some, but in general works.
Take a look at this tutorial on MDN: https://developer.mozilla.org/en/HTML/Canvas/Drawing_DOM_objects_into_a_canvas (archived)
Its key trick was:
var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');
var data = '<svg xmlns="http://www.w3.org/2000/svg" width="200" height="200">' +
'<foreignObject width="100%" height="100%">' +
'<div xmlns="http://www.w3.org/1999/xhtml" style="font-size:40px">' +
'<em>I</em> like ' +
'<span style="color:white; text-shadow:0 0 2px blue;">' +
'cheese</span>' +
'</div>' +
'</foreignObject>' +
'</svg>';
var DOMURL = window.URL || window.webkitURL || window;
var img = new Image();
var svg = new Blob([data], {type: 'image/svg+xml;charset=utf-8'});
var url = DOMURL.createObjectURL(svg);
img.onload = function () {
ctx.drawImage(img, 0, 0);
DOMURL.revokeObjectURL(url);
}
img.src = url;
That is, it used a temporary SVG image to include the HTML content as a "foreign element", then renders said SVG image into a canvas element. There are significant restrictions on what you can include in an SVG image in this way, however. (See the "Security" section for details — basically it's a lot more limited than an iframe or AJAX due to privacy and cross-domain concerns.)
Sorry, the browser won't render HTML into a canvas.
It would be a potential security risk if you could, as HTML can include content (in particular images and iframes) from third-party sites. If canvas could turn HTML content into an image and then you read the image data, you could potentially extract privileged content from other sites.
To get a canvas from HTML, you'd have to basically write your own HTML renderer from scratch using drawImage and fillText, which is a potentially huge task. There's one such attempt here but it's a bit dodgy and a long way from complete. (It even attempts to parse the HTML/CSS from scratch, which I think is crazy! It'd be easier to start from a real DOM node with styles applied, and read the styling using getComputedStyle and relative positions of parts of it using offsetTop et al.)
You can use dom-to-image library (I'm the maintainer).
Here's how you could approach your problem:
var parent = document.getElementById('my-node-parent');
var node = document.getElementById('my-node');
var canvas = document.createElement('canvas');
canvas.width = node.scrollWidth;
canvas.height = node.scrollHeight;
domtoimage.toPng(node).then(function (pngDataUrl) {
var img = new Image();
img.onload = function () {
var context = canvas.getContext('2d');
context.translate(canvas.width, 0);
context.scale(-1, 1);
context.drawImage(img, 0, 0);
parent.removeChild(node);
parent.appendChild(canvas);
};
img.src = pngDataUrl;
});
And here is jsfiddle
Building on top of the Mozdev post that natevw references I've started a small project to render HTML to canvas in Firefox, Chrome & Safari. So for example you can simply do:
rasterizeHTML.drawHTML('<span class="color: green">This is HTML</span>'
+ '<img src="local_img.png"/>', canvas);
Source code and a more extensive example is here.
No such thing, sorry.
Though the spec states:
A future version of the 2D context API may provide a way to render fragments of documents, rendered using CSS, straight to the canvas.
Which may be as close as you'll get.
A lot of people want a ctx.drawArbitraryHTML/Element kind of deal but there's nothing built in like that.
The only exception is Mozilla's exclusive drawWindow, which draws a snapshot of the contents of a DOM window into the canvas. This feature is only available for code running with Chrome ("local only") privileges. It is not allowed in normal HTML pages. So you can use it for writing FireFox extensions like this one does but that's it.
You could spare yourself the transformations, you could use CSS3 Transitions to flip <div>'s and <ol>'s and any HTML tag you want. Here are some demos with source code explain to see and learn: http://www.webdesignerwall.com/trends/47-amazing-css3-animation-demos/
the next code can be used in 2 modes, mode 1 save the html code to a image, mode 2 save the html code to a canvas.
this code work with the library: https://github.com/tsayen/dom-to-image
*the "id_div" is the id of the element html that you want to transform.
**the "canvas_out" is the id of the div that will contain the canvas
so try this code.
:
function Guardardiv(id_div){
var mode = 2 // default 1 (save to image), mode 2 = save to canvas
console.log("Process start");
var node = document.getElementById(id_div);
// get the div that will contain the canvas
var canvas_out = document.getElementById('canvas_out');
var canvas = document.createElement('canvas');
canvas.width = node.scrollWidth;
canvas.height = node.scrollHeight;
domtoimage.toPng(node).then(function (pngDataUrl) {
var img = new Image();
img.onload = function () {
var context = canvas.getContext('2d');
context.drawImage(img, 0, 0);
};
if (mode == 1){ // save to image
downloadURI(pngDataUrl, "salida.png");
}else if (mode == 2){ // save to canvas
img.src = pngDataUrl;
canvas_out.appendChild(img);
}
console.log("Process finish");
});
}
so, if you want to save to image just add this function:
function downloadURI(uri, name) {
var link = document.createElement("a");
link.download = name;
link.href = uri;
document.body.appendChild(link);
link.click();
}
Example of use:
<html>
<head>
</script src="/dom-to-image.js"></script>
</head>
<body>
<div id="container">
All content that want to transform
</div>
<button onclick="Guardardiv('container');">Convert<button>
<!-- if use mode 2 -->
<div id="canvas_out"></div>
</html>
Comment if that work.
Comenten si les sirvio :)
The easiest solution to animate the DOM elements is using CSS transitions/animations but I think you already know that and you try to use canvas to do stuff CSS doesn't let you to do. What about CSS custom filters? you can transform your elements in any imaginable way if you know how to write shaders. Some other link and don't forget to check the CSS filter lab.
Note: As you can probably imagine browser support is bad.
function convert() {
dom = document.getElementById('divname');
var script,
$this = this,
options = this.options,
runH2c = function(){
try {
var canvas = window.html2canvas([ document.getElementById('divname') ], {
onrendered: function( canvas ) {
window.open(canvas.toDataURL());
}
});
} catch( e ) {
$this.h2cDone = true;
log("Error in html2canvas: " + e.message);
}
};
if ( window.html2canvas === undefined && script === undefined ) {
} else {.
// html2canvas already loaded, just run it then
runH2c();
}
}

Export Highcharts to PDF (using javascript and local server - no internet connection)

I am using Highcharts in my application (without any internet connection)
I have multiple charts on a html page, and I want to generate a PDF report that contains all the charts from this page.
How can I do this without sending the data to any server on the internet ?
I will be thankful for any help or any example you can provide.
Thank you in advance :)
Yes this is possible but involves a few different libraries to get working. The first Library is jsPDF which allows the creation of PDF in the browser. The second is canvg which allows for the rendering and parsing of SVG's, the bit that is really cool though is it can render an svg on to canvas element. Lastly is Highcharts export module which will allow us to send the svg to the canvg to turn into a data URL which can then be given to jsPDF to turn into your pdf.
Here is an example http://fiddle.jshell.net/leighking2/dct9tfvn/ you can also see in there source files you will need to include in your project.
So to start highcharts provides an example of using canvg with it's export to save a chart as a png. because you want all the iamges in a pdf this has been slightly altered for our purpose to just return the data url
// create canvas function from highcharts example http://jsfiddle.net/highcharts/PDnmQ/
(function (H) {
H.Chart.prototype.createCanvas = function (divId) {
var svg = this.getSVG(),
width = parseInt(svg.match(/width="([0-9]+)"/)[1]),
height = parseInt(svg.match(/height="([0-9]+)"/)[1]),
canvas = document.createElement('canvas');
canvas.setAttribute('width', width);
canvas.setAttribute('height', height);
if (canvas.getContext && canvas.getContext('2d')) {
canvg(canvas, svg);
return canvas.toDataURL("image/jpeg");
} 
else {
alert("Your browser doesn't support this feature, please use a modern browser");
return false;
}
}
}(Highcharts));
Then for the example i have set up export on a button click. This will look for all elements of a certain class (so choose one to add to all of your chart elements) and then call their highcharts.createCanvas function.
$('#export_all').click(function () {
var doc = new jsPDF();
// chart height defined here so each chart can be palced
// in a different position
var chartHeight = 80;
// All units are in the set measurement for the document
// This can be changed to "pt" (points), "mm" (Default), "cm", "in"
doc.setFontSize(40);
doc.text(35, 25, "My Exported Charts");
//loop through each chart
$('.myChart').each(function (index) {
var imageData = $(this).highcharts().createCanvas();
// add image to doc, if you have lots of charts,
// you will need to check if you have gone bigger
// than a page and do doc.addPage() before adding
// another image.
/**
* addImage(imagedata, type, x, y, width, height)
*/
doc.addImage(imageData, 'JPEG', 45, (index * chartHeight) + 40, 120, chartHeight);
});
//save with name
doc.save('demo.pdf');
});
important to note here that if you have lots of charts you will need to handle placing them on a new page. The documentation for jsPDF looks really outdated (they do have a good demos page though just not a lot to explain all the options possible), there is an addPage() function and then you can just play with widths and heights until you find something that works.
the last part is to just setup the graphs with an extra option to not display the export button on each graph that would normally display.
//charts
$('#chart1').highcharts({
navigation: {
buttonOptions: {
enabled: false
}
},
//this is just normal highcharts setup form here for two graphs see fiddle for full details
The result isn't too bad i'm impressed with the quality of the graphs as I wasn't expecting much from this, with some playing of the pdf positions and sizes could look really good.
Here is a screen shot showing the network requests made before and after the export, when the export is made no requests are made http://i.imgur.com/ppML6Gk.jpg
here is an example of what the pdf looks like http://i.imgur.com/6fQxLZf.png (looks better when view as actual pdf)
quick example to be tried on local https://github.com/leighquince/HighChartLocalExport
You need to setup your own exporting server, locally like in the article
Here is an example using the library pdfmake:
html:
<div id="chart_exchange" style="width: 450px; height: 400px; margin: 0 auto"></div>
<button id="export">export</button>
<canvas id="chart_exchange_canvas" width="450" height="400" style="display: none;"></canvas>
javascript:
function drawInlineSVG(svgElement, canvas_id, callback) {
var can = document.getElementById(canvas_id);
var ctx = can.getContext('2d');
var img = new Image();
img.setAttribute('src', 'data:image/svg+xml;base64,' + btoa(unescape(encodeURIComponent(svgElement))));
img.onload = function() {
ctx.drawImage(img, 0, 0);
callback(can.toDataURL("image/png"));
}
}
full working code:
https://jsfiddle.net/dimitrisscript/f6sbdsps/
Maybe this link can help you out.
http://bit.ly/1IYJIyF
Try refer to the exporting properties (fallbackToExportServer: false) and the necessary file that need to be include (offline-exporting.js).
Whereas for the export all at once part, currently I myself also still trying. Will update here if any.
This question is a bit old but was something i was working on myself recently and had some trouble with it.
I used the jsPDF library: https://github.com/MrRio/jsPDF
Issues i ran into involved jsPDF not supporting the SVG image exported by the high chart + images being blurry and low quality.
Below is the solution I used to get two charts into one pdf document:
function createPDF() {
var doc = new jsPDF('p', 'pt', 'a4'); //Create pdf
if ($('#chart1').length > 0) {
var chartSVG = $('#chart1').highcharts().getSVG();
var chartImg = new Image();
chartImg.onload = function () {
var w = 762;
var h = 600;
var chartCanvas = document.createElement('canvas');
chartCanvas.width = w * 2;
chartCanvas.height = h * 2;
chartCanvas.style.width = w + 'px';
chartCanvas.style.height = h + 'px';
var context = chartCanvas.getContext('2d');
chartCanvas.webkitImageSmoothingEnabled = true;
chartCanvas.mozImageSmoothingEnabled = true;
chartCanvas.imageSmoothingEnabled = true;
chartCanvas.imageSmoothingQuality = "high";
context.scale(2, 2);
chartCanvas.getContext('2d').drawImage(chartImg, 0, 0, 762, 600);
var chartImgData = chartCanvas.toDataURL("image/png");
doc.addImage(chartImgData, 'png', 40, 260, 250, 275);
if ($('#chart2').length > 0) {
var chart2SVG = $('#chart2').highcharts().getSVG(),
chart2Img = new Image();
chart2Img.onload = function () {
var chart2Canvas = document.createElement('canvas');
chart2Canvas.width = w * 2;
chart2Canvas.height = h * 2;
chart2Canvas.style.width = w + 'px';
chart2Canvas.style.height = h + 'px';
var context = chart2Canvas.getContext('2d');
chart2Canvas.webkitImageSmoothingEnabled = true;
chart2Canvas.mozImageSmoothingEnabled = true;
chart2Canvas.imageSmoothingEnabled = true;
chart2Canvas.imageSmoothingQuality = "high";
context.scale(2, 2);
chart2Canvas.getContext('2d').drawImage(chart2Img, 0, 0, 762, 600);
var chart2ImgData = chart2Canvas.toDataURL("image/png");
doc.addImage(chart2ImgData, 'PNG', 300, 260, 250, 275);
doc.save('ChartReport.pdf');
}
chart2Img.src = "data:image/svg+xml;base64," + window.btoa(unescape(encodeURIComponent(chart2SVG)));
}
}
chartImg.src = "data:image/svg+xml;base64," + window.btoa(unescape(encodeURIComponent(chartSVG)));
}
}
scripts to include:
<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.2.61/jspdf.min.js"></script>

canvas.toDataURL() not working properly except mozilla firefox

I have developed a coupon generator module in the site I create a coupon in the html format and fill that html value in canvas by using JavaScript function which is
function checkcanvas(id) {
var canvas = document.getElementById("canvas");
var ctx = canvas.getContext("2d");
var data = "<svg xmlns='http://www.w3.org/2000/svg' width='437' height='262'>"
+ "<foreignObject width='100%' height='100%'>"
+ "<div xmlns='http://www.w3.org/1999/xhtml' style='font-size:40px'>"
+ $("#coupon_td").html()
+ "</div>"
+ "</foreignObject>"
+ "</svg>";
var DOMURL = self.URL || self.webkitURL || self;
var img = new Image();
var svg = new Blob([data], {type: "image/svg+xml;charset=utf-8"});
var url = DOMURL.createObjectURL(svg);
img.onload = function() {
ctx.drawImage(img, 0, 0);
DOMURL.revokeObjectURL(url);
};
img.src = url;
if(id == 2) {
document.getElementById('base_64_img').value = canvas.toDataURL();
}
}
base_64_img is just a hidden element so I can post the data into my php code and create a image using base64 code.
The biggest issue I am facing that this code perfectly worked in Mozilla Firefox almost every version but not working in Google chrome.
In your code you are generating an "SVG IMAGE" and trying to convert into toDataURL().
var svg = new Blob([data], {type: "image/svg+xml;charset=utf-8"});
This is the problem, from this URL toDataURL :
If the type requested is not image/png, and the returned value starts
with data:image/png, then the requested type is not supported.
In this fiddlecode if you see the printed output , "data:image/png;base64". its supposed to be "data:image/svg;base64".
Instead of creating svg image, use canvas element and javascript to draw the related banner image and if you take the output then try copy & paste in your browser. ( it may work ).
Check this js plugin called SVG.toDataURL
Hope this helps.

Categories