Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to export a Google Chart using dompdf?

In my Laravel 5 project, I am using Lavacharts (powered by Google Charts) for displaying charts and a dompdf wrapper, laravel-dompdf, for generating PDF files.

Is it possible to export such charts using dompdf, and if so, how can this be achieved?

Presumably I would have to first save the chart as an image, but this is not really an option since saving the image is done via Javascript and for generating the PDF all the work is done in the backend (PHP).

like image 200
Tudor Ciotlos Avatar asked May 19 '16 15:05

Tudor Ciotlos


1 Answers

Dompdf is unable to process JavaScript-based content on a page. You have two options:

  1. Preview the charts in a browser and send an image version to the server for rendering.
  2. Use a headless browser (like PhantomJS) to render your HTML (with JavaScript) to PDF

I don't have much to say on the second option, but on the first...

The Google Charts API can generate a PNG version of your chart. There are plenty of posts on SO on how to get the PNG to your PHP code (search it).

Something like the following might work:

<script type="text/javascript">
google.charts.load("current", {packages:['corechart']});
google.charts.setOnLoadCallback(drawChart);
function drawChart() {

  var data = google.visualization.arrayToDataTable([
    ['Element', 'Density', { role: 'style' }],
    ['Copper', 8.94, '#b87333', ],
    ['Silver', 10.49, 'silver'],
    ['Gold', 19.30, 'gold'],
    ['Platinum', 21.45, 'color: #e5e4e2' ]
  ]);

  var options = {
    title: "Density of Precious Metals, in g/cm^3",
    bar: {groupWidth: '95%'},
    legend: 'none',
  };

  var chart_div = document.getElementById('chart_div');
  var chart_input = document.getElementById('chart_input');
  var chart = new google.visualization.ColumnChart(chart_div);

  // 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() + '">';
    chart_input.value = chart.getImageURI();
  });

  chart.draw(data, options);

}
</script>

<div id='chart_div'></div>

<form method="post" action="print_chart.php">
<input type="hidden" name="chartImg" id="chartImg">
<button type="submit">print</button>
</form>

Google Charts renders the PNG using a data-uri, which dompdf supports. Once you have the PNG on the server side you can just insert it into an img tag:

$html = '<img src="' . $_POST['chart_input'] . '">';
$dompdf->load_html($html);
$dompdf->render();
$dompdf->stream('chart.pdf');
like image 52
BrianS Avatar answered Oct 21 '22 03:10

BrianS