Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Resize chart.js canvas for printing

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)?

enter image description here

like image 648
ncohen Avatar asked Jan 16 '17 11:01

ncohen


People also ask

How do I set the size of a Chartjs?

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 .

What is responsive in chart js?

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.

How do you resize a chart in HTML?

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.


2 Answers

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;
    }
}
like image 192
Jonas Sciangula Street Avatar answered Oct 22 '22 19:10

Jonas Sciangula Street


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.

like image 44
Reggie Pinkham Avatar answered Oct 22 '22 20:10

Reggie Pinkham