Using Google Charts API Generated Graphic in FPDF

一笑奈何 提交于 2019-12-06 07:59:52

Here is a jsfiddle example of a google chart rendered as an image. You can easily put the "printable version" in your pdf.

Google charts have the getImageURI method that provides you with a png of the chart you created.

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

Correct me if I am wrong, but as far as i know FPDF is only able to use (include) image files. So what you could do is generate that graph with image headers and than include the link to that graph in FPDF (works fine when including things generated in php and adding image headers, but can be tricky with converting JS generated graphic, could need some hacks). Another solution (if possible) try using wkhtmltopdf. It generates PDF from html pages (again not sure if that will work with JS generated graphics).

I used this method to save google charts as an image by using base64 url to save in some folder from server side finally use in fpdf as an image from folder.

<script type="text/javascript" src="https://www.google.com/jsapi"></script>
<script type="text/javascript" src="js/jquery-2.1.4.min.js"></script>
<script type="text/javascript">

    google.load("visualization", "1", {packages:["corechart"]});
    google.setOnLoadCallback(drawVisualization);

    function drawVisualization() {
    // Some raw data (not necessarily accurate)
    var data = google.visualization.arrayToDataTable([
    ['', ''],
    ['Numerical', 4],
    ['Verbal', 6],
    ['Mechanical', 4],  
    ['Reasoning', 5],  
    ['Spatial', 9]
    ]);

    var options = {
    title : '',
    vAxis: {title: "", viewWindowMode:'explicit',
          viewWindow:{
            max:12,
            min:0
          }},
    hAxis: {title: ""},
    seriesType: "bars",
    series: {5: {type: "line"}}
    };

    var chart = new google.visualization.ComboChart(document.getElementById('chart_div'));
    chart.draw(data, options);

    var app1=(chart.getImageURI());
        $.post("appt1.php",{postapp: app1},
        function(){});
    }
</script>
<div id="chart_div" style="display: none;"></div>


<!-- On the Server side  do this to store image appt1.php -->

$data =$_POST['postapp'];
list($type, $data) = explode(';', $data);
list(, $data) = explode(',', $data);
$data = base64_decode($data);

file_put_contents('exam_images/'."1".'.png', $data);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!