Chart.js icon indicating copy to clipboard operation
Chart.js copied to clipboard

Printing chart, resize don't work

Open WebCimes opened this issue 5 years ago • 3 comments

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

WebCimes avatar Jan 23 '20 11:01 WebCimes

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" :

  • Safari: chart is OK and align in the middle
  • Firefox, Chrome: chart is OK but align on the right

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

cdefy avatar May 25 '20 13:05 cdefy

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)

rbubley avatar Sep 08 '20 22:09 rbubley

@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;

fhackenberger avatar Jul 25 '24 06:07 fhackenberger