Redraw/Resize highcharts when printing website

前端 未结 3 2036
悲哀的现实
悲哀的现实 2021-02-06 05:57

When I\'m printing the bottom right frame the text some text is partly covered by the highcharts because they don\'t resize before printing. Is there a solution to

3条回答
  •  面向向阳花
    2021-02-06 06:45

    Here is a mix of different solutions, with no need of exporting.js (which adds exporting button to all graphs on page...)

    The size is automatically rescaled, then reset after print.

    Tested mostly on IE

    window.onbeforeprint = function() {
        $(Highcharts.charts).each(function(i,chart){
            chart.oldhasUserSize = chart.hasUserSize;
            chart.resetParams = [chart.chartWidth, chart.chartHeight, false];
    
            var height = chart.renderTo.clientHeight;
            var width = chart.renderTo.clientWidth;
            chart.setSize(width, height);
        });
    }
    window.onafterprint = function() {
        $(Highcharts.charts).each(function(i,chart){
            chart.setSize.apply(chart, chart.resetParams);
            chart.hasUserSize = chart.oldhasUserSize;
        });
    }
    

    UPDATE: I now use a different version, fixing the size of each chart instead of using clientWidth. It works on the 3 browsers I tested (IE 11, FF & Chrome)

    function redimChartBeforePrint(chart, width, height) {
        if (typeof(width) == 'undefined')
            width  = 950;
        if (typeof(height) == 'undefined')
            height = 400;
        chart.oldhasUserSize = chart.hasUserSize;
        chart.resetParams = [chart.chartWidth, chart.chartHeight, false];
        chart.setSize(width, height, false);
    }
    function redimChartAfterPrint(chart) {
        chart.setSize.apply(chart, chart.resetParams);
        chart.hasUserSize = chart.oldhasUserSize;
    }
    
    window.onbeforeprint = function() {
        redimChartBeforePrint($('#chart1').highcharts());
        redimChartBeforePrint($('#chart2').highcharts(), 800, 600);
        ...
    };
    window.onafterprint = function() {
        redimChartAfterPrint($('#chart1').highcharts());
        redimChartAfterPrint($('#chart2').highcharts());
        ...
    };
    

提交回复
热议问题