I'm using the @media print {
to customize my print view. The problem with my charts is that their printing size depends on the size of the browser window. So when my browser is big, the canvas will be too big for the page (I'm using responsive charts)
I have tried to redefine the size of the canvas inside @media print {
without success.
What are the solutions to get a consistant chart size when I print (without affecting my browser view)?
To set the chart size in ChartJS, we recommend using the responsive option, which makes the Chart fill its container. You must wrap the chart canvas tag in a div in order for responsive to take effect. You cannot set the canvas element size directly with responsive .
Chart. js provides a few options to enable responsiveness and control the resize behavior of charts by detecting when the canvas display size changes and update the render size accordingly.
You can resize the chart using the resize function that is provided by KoolChart's JavaScript charting library. Set the width and height of the <DIV> element where the chart is created before the resize function is called.
If your charts are simple, try using just using css
@media print {
canvas.chart-canvas {
min-height: 100%;
max-width: 100%;
max-height: 100%;
height: auto!important;
width: auto!important;
}
}
The problem is the chart does not fit the new print width dimension. Fortunately we can perform a redraw when print is initiated.
The solution is to render your chart to an image using the canvas.toDataURL()
method when printing is invoked, then switch it back to the canvas chart after printing. More on toDataURL().
To detect when to invoke your functions webkit provide the method window.matchMedia('print')
(which will be true
during print or false
again afterwards) while other browsers use window.onbeforeprint
and window.onafterprint
. More on print methods.
All that is then left to do is ensure the image is responsive using CSS, i.e. scales to 100% width.
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