0

I am using google charts and have a page of mixed charts, some pie, a column chart and a gauge chart

The page has an option to generate a pdf, so I am converting the charts to PNG to use in the pdf..

all the charts are generated in the same manner, using a div to display the google chart and a hidden div to store the png image

 var chart = new google.visualization.Gauge(document.getElementById('gauge'));
    var hidden = new google.visualization.Gauge(document.getElementById('gauge_hidden'));

  // Wait for the chart to finish drawing before calling the getImageURI() method.
    google.visualization.events.addListener(chart, 'ready', function () {
        gauge_hidden.innerHTML = '<img src="' + chart.getImageURI() + '">';

    });
    chart.draw(data, options);

this code works fin on he pie and column charts, but on the gauge chart I am seeing

chart.getImageURI is not a function

any ideas how I can get the png?

CHeers

Andie
  • 413
  • 1
  • 6
  • 17
  • I'm trying to do the same and stuck at the place on how to use charts in PDF. Could you help me with an example? Thanks. – Aqua267 May 24 '20 at 06:53

1 Answers1

0

I was facing this same issue, but after some reading i've come to this solution:

I'm using jQuery to make this a little easier.

First, use XMLSerializer to convert the SVG chart to a string and then use btoa to convert that to base64. You can use this string this way:

var s = new XMLSerializer().serializeToString($(chart_div).find('svg')[0]);
var base64String = "data:image/svg+xml;base64," + window.btoa(s);

In my case i needed to draw the gauge chart to a PDF and DOMPDF doesn't support this format, so if you need a "data:image/png;base64," string, you can continue with this solution.

You need to set the "svg+xml;base64" as src of a new Image and then draw that image to a Canvas. After that you can use toDataURL method from canvas to get the content as base64 png.

var s = new XMLSerializer().serializeToString($(chart_div).find('svg')[0]);
var image = new Image();
image.width = 640;
image.height = 480;
image.src = 'data:image/svg+xml;base64,' + window.btoa(s);
var myCanvas = document.createElement('canvas');
myCanvas.width = 640;
myCanvas.height = 480;
var myCanvasContext = myCanvas.getContext('2d');
myCanvasContext.drawImage(image,0,0);
// get google chart gague to base64, yey!
var base64String = myCanvas.toDataURL();

Thanks to the author of this answer and this post

Community
  • 1
  • 1
Elmer Rivera
  • 1
  • 1
  • 1