I have a PHP page with Google charts and a table below it that needs to be exported as PDF.
I tried using
var doc = new jsPDF();
doc.addImage(chart.getImageURI(), 0,0);
doc.save('chart.pdf');
for the google chart and dompdf for the table but obviously when using both code at once it doesn't work.
Is there a way to export the page as a whole, or a PDF page of the chart and 2nd for the table all within the same PDF file?
you can use html2canvas to get an image of the entire page,
then send that to pdf...
just need to make sure both the chart and table have finished drawing.
see following working snippet...
$(document).ready(function() {
google.charts.load('current', {
packages: ['corechart', 'table']
}).then(function () {
var data = new google.visualization.arrayToDataTable([
['x', 'y0', 'y1'],
['0-10', -3, 3],
['11-20', -2.5, 2.5],
['21-30', -2, 2],
['31-40', -1.5, 1.5],
]);
var chart = new google.visualization.BarChart(document.getElementById('chart_div'));
var chartReady = false;
var table = new google.visualization.Table(document.getElementById('table_div'));
var tableReady = false;
google.visualization.events.addListener(chart, 'ready', onChartReady);
google.visualization.events.addListener(table, 'ready', onTableReady);
chart.draw(data, {
hAxis: {
format: '#,##0.000',
ticks: [
{v: -8, f: '8.000'},
{v: -6, f: '6.000'},
{v: -4, f: '4.000'},
{v: -2, f: '2.000'},
0, 2, 4, 6, 8
]
},
isStacked: true
});
table.draw(data);
function onChartReady() {
chartReady = true;
onIsReady();
}
function onTableReady() {
tableReady = true;
onIsReady();
}
function onIsReady() {
if ((chartReady) && (tableReady)) { html2canvas($('#dashboard_div').get(0)).then(function(canvas) {
// export pdf
var pdfDoc = new jsPDF({
orientation: 'landscape',
unit: 'px',
format: [canvas.width, canvas.height]
});
pdfDoc.addImage(canvas.toDataURL('image/png'), 0, 0);
pdfDoc.save('page.pdf');
});
}
}
});
});
.table {
text-align: center;
}
#table_div {
display: inline-block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://www.gstatic.com/charts/loader.js"></script>
<script src="https://cdn.jsdelivr.net/npm/html2canvas@1.0.0-rc.5/dist/html2canvas.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jspdf@1.5.3/dist/jspdf.min.js"></script>
<div id="dashboard_div">
<div id="chart_div"></div>
<div class="table">
<div id="table_div"></div>
</div>
</div>