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).
Dompdf is unable to process JavaScript-based content on a page. You have two options:
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With