4👍
This is fine but what if you want to bypass the on screen part and go straight to a pdf document and include the image
You can still use chart.js exporting as PDF with PhantomJs (a headless browser that will open a html page with your charts, and save it via PDF). If you are working with nodejs there’s a good library that abstracts PhantomJs and make the PDF easy: https://github.com/sindresorhus/pageres. It seems like a workaround, but usually these canvas to PDF doesn’t render well, specially charts!
Yeah, you still need to create a html page to print your PDF, however you have 2 options:
-
Use the same page, and via CSS print styles, you can show/hide things that will print only on PDF (as PhantomJs will create PDF in print mode).
-
Create a custom webpage only for PDF renderization
- [Chartjs]-How to modify bar width in Chartjs 2 bar charts
- [Chartjs]-How can labels/legends be added for all chart types in chart.js (chartjs.org)?
2👍
I was working on a similar problem and built QuickChart. It is a web service that renders Chart.js charts in several static formats including PDF.
The full source code is here: https://github.com/typpo/quickchart
You may be interested in lib/charts.js and lib/pdf.js in particular. The solution is built on top of a Javascript canvas implementation (node-canvas) and a Chart.js wrapper library (chartjs-node-canvas). First the chart is rendered to a PNG image using the canvas. Then the PNG is positioned on a document and rendered using pdfkit.
Hope you find the source code useful. I also host the QuickChart web service for free so you can use the web API directly https://quickchart.io/chart?width=500&height=300&format=pdf&c={chart.js config here}
Here’s an example of a PDF chart generated on-the-fly:
- [Chartjs]-How to implement chart.js in Angular2
- [Chartjs]-Remove the vertical line in the chart js line chart
0👍
While this does not answer the question directly as I could not get chart.js to do what I wanted being client side, I found a good solution using pChart. As the pdf is being generated, the chart is created and is temporarily saved on the server until the pdf is finished. The chart is inserted into the pdf and then deletes the chart from the server. There is a bit of manipulation to correctly size the image.
$myPicture->render("path/imagename.png");
if (file_exists("path/imagename.png")) {
$ycurrent = $pdf->GetY();
list($width, $height) = getimagesize("path/imagename.png");
$imageWidth = 160;
$ratio = $imageWidth/$width;
$xpos = 25;
$pdf->Image("path/imagename.png", $xpos, $ycurrent, $width * $ratio, $height * $ratio, "png", '');
unlink ("path/imagename.png");
}
- [Chartjs]-Can't change color line with chart.js
- [Chartjs]-How to change colours for Angular-Chart.js