Search code examples
jquerypdfgoogle-visualizationcss-to-pdf

Export Google Chart to PDF using Cloudformatter, generates blank PDF


I'm trying to export google chart to the PDF file. I'm using xepOnline.jqPlugin.js plugin for it from cloudformatter.com. I followed all the steps from http://www.cloudformatter.com/CSS2Pdf.APIDoc.Usage

But when i try to export, PDF get generates with blank square box.

enter image description here

I'm loading the google chart from jquery ajax call. Can any body tell me what could be the issue ?

Here is a sample code without ajax call -

 <button type="button" id="" class="btn btn-success pull-right" style="margin-right: 7px;" onclick="return xepOnline.Formatter.Format('chart_container', {render: 'download', filename: 'Years_Build', mimeType: 'application/pdf'});">Export</button>
    <div id="chart_container">
      <div id="chart_div"></div>
    </div>
<script type="text/javascript">
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',
          }
        };

        var chart = new google.charts.Bar(document.getElementById('chart_div'));
        chart.draw(data, google.charts.Bar.convertOptions(options));
                                                            }
google.charts.load('current', {'packages': ['bar']});
google.charts.setOnLoadCallback(drawChart);
</script>

Solution

  • You are missing the SVG namespace which needs to be added. If you examine the sample fiddle on their site for each chart you will see a function that adds the namespace after the chart is drawn.

    For example, see http://jsfiddle.net/w1rpjxoe/

    You would see this function:

    function AddNamespace(){
      var svg = jQuery('#chart_div svg');
      svg.attr("xmlns", "http://www.w3.org/2000/svg");
      svg.css('overflow','visible');
    }
    

    It is called from this Listener:

     google.visualization.events.addListener(chart, 'ready', AddNamespace);
    

    What this does is add the missing SVG namespace to the chart SVG that Google charts does not do but @cloudformatter requires.