I've got an issue. I'm on Laravel and I need to export a HTML page to PDF.
So I'm using barryvdh/laravel-dompdf
, I tried to export some datas and images and it works fine.
The fact is I need to export a LineChart Canvas to PDF, so I convert the canvas to image before, it works in my view but not in my PDF.
I use this script to make graphs : https://mdbootstrap.com/javascript/charts/
Here's my code :
// Controller code
public function pdf($name)
{
$MyObject = Object::where('name', $name)->first()->toArray();
$pdf = PDF::loadView('pdf.object', compact('object'));
// If I want to return and test with my view I use this line
return view('pdf.object', compact('object'));
// If I want to download the pdf I use this line
return $pdf->download($object['name'] . '.pdf');
}
// HTML Canvas + The script I use
<canvas id="myChart"></canvas>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="{{ asset('js/mdb.min.js') }}"></script>
// JS Code
var ctxL = document.getElementById("myChart").getContext('2d');
var myLineChart = new Chart(ctxL, {
type: 'line',
data: {
labels: ["label1","label2","label3"],
datasets: [
{
label: "My first line",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
borderColor : "rgb(66, 40, 124)",
pointBackgroundColor : "rgb(66, 40, 124)",
pointHoverBorderColor : "rgb(66, 40, 124)",
backgroundColor: "transparent",
data: [15, 9, 13]
},
{
label: "My second line",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
borderColor : "rgb(120, 60, 135)",
pointBackgroundColor : "rgb(120, 60, 135)",
pointHoverBorderColor : "rgb(120, 60, 135)",
backgroundColor: "transparent",
data: [3, 9, 4]
}
]
},
options: {
responsive: true,
animation: false
}
});
var canvas = $('#myChart');
var dataURL = canvas.get(0).toDataURL();
var img = $("<img style='width:100%;height:auto;'></img>");
img.attr("src", dataURL);
canvas.replaceWith(img);
When I export, my canvas doesn't show up, but in my view, my canvas is an image, is anything I didn't see wrong in my code ? Thanks in advance !
You're trying to interpret Javascript through php and dompdf, what is not possible, as they will not, cause they don't support that feature.
You should use an other utility that will allow you to execute the javascript that will create the image, like:
Those utilities will allow you to render your page and get the image you want to export to PDF, you can even get the PDF directly from some of theme.