chartjs / Chart.js

Simple HTML5 Charts using the <canvas> tag
https://www.chartjs.org/
MIT License
64.48k stars 11.89k forks source link

Printing chart, resize don't work #7006

Open WebCimes opened 4 years ago

WebCimes commented 4 years ago

I have a problem when I try to print a chart who are responsive, the problem have already been reported but the solution don't work.

Like it's write in the doc at https://www.chartjs.org/docs/latest/general/responsive.html (bottom of the page), I have create an handler for "onbeforeprint" event, with a function who try to resize the chart before printing, but they doesn't work with the last version of chart.js and chrome or firefox. The event fire well, but the resize take too much time to be execute, and the chart keep the width of the browser before the print.

here an example : function beforePrintHandler() { for(var id in Chart.instances) { Chart.instances[id].resize(); } } window.onbeforeprint = beforePrintHandler;

So I think we need a solution for the resize function work, if you have an idea ?

Thanks

Related subject : https://github.com/chartjs/Chart.js/issues/1350 https://github.com/chartjs/Chart.js/issues/5206 https://www.chartjs.org/docs/latest/general/responsive.html https://stackoverflow.com/questions/41674976/resize-chart-js-canvas-for-printing https://stackoverflow.com/questions/52754926/chartjs-responsive-resize-for-print-not-working-in-firefox-ie11-edge

cdefy commented 4 years ago

Hi there,

Got the same problem with a radar chart (using Chart.js by vue-chart in Nuxt.js), depending on screen size the print results is almost OK. On a 13" :

But no resize seems to happen because if I try the same on a 24" screen, chart is align on the right and cut almost in half on Firefox and Chrome, on Safari as the alignment seems to be different I can still see the chart but it's not in the middle any more.

Will be awesome to have help on that! Thx

rbubley commented 4 years ago

I had some success with:

if ('matchMedia' in window) {
  window.matchMedia('print').addListener(function (media) {
  beforePrintHandler();
 });
} else {
  window.onbeforeprint = beforePrintHandler;
}

(inspired by https://www.thetopsites.net/article/52406555.shtml)

fhackenberger commented 2 months ago
@media print {
    #myChart { 
        width: 100% !important;
        height: auto !important;
    }
}

works for me on Chromium 125 and Firefox 127, with the following snippets and no event handlers whatsoever.

<div class="chart"><canvas id="myChart"></canvas></div>
const chartData = {
    type: 'bar' as ChartType,
    options: {
        indexAxis: 'y', // Make it horizontal
        responsive: true,
        maintainAspectRatio: false,
    },
} as ChartConfiguration;