Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redraw/Resize highcharts when printing website

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 configure a printing layout with @media print for the website and force highcharts to redraw/resize to container size when website is printed?

HTML

<script src="http://code.highcharts.com/highcharts.js"></script>
<script src="http://code.highcharts.com/modules/exporting.js"></script>

<div id="container" style="height: 400px"></div>
<div id="container" style="height: 400px"></div>

JavaScript

$(function () {
    Highcharts.setOptions({ // Apply to all charts
        chart: {
            events: {
                beforePrint: function () {
                    this.oldhasUserSize = this.hasUserSize;
                    this.resetParams = [this.chartWidth, this.chartHeight, false];
                    this.setSize(600, 400, false);
                },
                afterPrint: function () {
                    this.setSize.apply(this, this.resetParams);
                    this.hasUserSize = this.oldhasUserSize;
                }
            }
        }
    });

    $('#container').highcharts({

        title: {
            text: 'Rescale to print'
        },

        subtitle: {
            text: 'Click the context menu and choose "Print chart".<br>The chart size is set to 600x400 and restored after print.'
        },

        xAxis: {
            categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
                'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
        },

        series: [{
            data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]
        }]

    });

});

JSFiddle

like image 728
user3665396 Avatar asked Sep 28 '15 10:09

user3665396


2 Answers

Taking these suggestions, I wanted to offer a 3rd approach that should solve some of the shortcomings of the previous answers in conjunction with other solutions I have seen elsewhere, resulting in what worked for me (that the above did not).

Setting window.onbeforeprint is fine, unless you have other onbeforeprint handlers and don't want to blow them away. window.addEventListener('onbeforeprint', function) allows you to both set numerous separate event listeners, AND remove them when you're done. Additionally, Safari does not support these specific event listeners anyways, so it is recommended to use window.matchMedia instead, which is supported on all evergreen browsers.

function _setupPrintHandler() {
    let chart; // save a local copy so you don't have to find the element again.
    var beforePrint = function() {
        chart = $('#container').highcharts();
        if (chart) {
            // Set your arbitrary width/height needed for printing
            // Save the existing chart info if explicitly set
            // beforeChartWidth = chart.chartWidth;
            // beforeChartHeight = chart.chartHeight;
            const printWidth = 710, printHeight = 450;
            chart.setSize(printWidth, printHeight, false);
            chart.reflow()
        }
    };
    var afterPrint = function() {
        if (chart) {
            // if the previous values were saved, use them, otherwise `null` will return to auto-fit the container size
            const prevWidth = beforeChartWidth || null;
            const prevHeight = beforeChartHeight || null;
            chart.setSize(prevWidth, prevHeight, false);
            chart.reflow();
        }
    };

    // use the new window.matchMedia query with better support
    if (window.matchMedia) {
        var mediaQueryList = window.matchMedia('print');
        mediaQueryList.addListener(function(mql) {
            if (mql.matches) {
                beforePrint();
            } else {
                afterPrint();
            }
        });
    }
    // Fallback if matchMedia isn't available
    else {
        window.addEventListener('onbeforeprint', beforePrint);
        window.addEventListener('onafterprint', afterPrint);
        // Use elsewhere if needed:
        // window.removeEventListener('onbeforeprint', beforePrint)
        // window.removeEventListener('onafterprint', afterPrint)
    }
};

Update:

Runnable example sans jQuery because it's 2020. Use the "expand snippet" link to test the print scenario.

Highcharts.setOptions({ // Apply to all charts
  chart: {
    events: {
      beforePrint: function() {
        // Not called from global print event
        this.oldhasUserSize = this.hasUserSize;
        this.resetParams = [this.chartWidth, this.chartHeight, false];
        this.setSize(600, 400, false);
      },
      afterPrint: function() {
        //not called from global print event
        this.setSize.apply(this, this.resetParams);
        this.hasUserSize = this.oldhasUserSize;
      }
    }
  }
});

Highcharts.chart('container', {
  title: {
    text: 'Rescale to print'
  },
  subtitle: {
    text: 'The chart size is set to 600x400 and restored after User-prompted print.'
  },
  xAxis: {
    categories: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
      'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'
    ]
  },
  series: [{
    data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4]
  }]
});


function _setupPrintHandler() {
let beforeChartWidth, beforeChartHeight;
  var beforePrint = function() {
    // Access cached charts without jQuery
    Highcharts.charts.forEach(chart => {
      if (chart) {
        // Set your arbitrary width/height needed for printing
        // Save the existing chart info if explicitly set
        // beforeChartWidth = chart.chartWidth;
        // beforeChartHeight = chart.chartHeight;
        const printWidth = 600,
          printHeight = 200;
        chart.setSize(printWidth, printHeight, false);
        chart.reflow()
      }
    });
  };
  var afterPrint = function() {
    Highcharts.charts.forEach(chart => {
      if (chart) {
        // if the previous values were saved, use them, otherwise `null` will return to auto-fit the container size
        const prevWidth = beforeChartWidth || null;
        const prevHeight = beforeChartHeight || null;
        chart.setSize(prevWidth, prevHeight, false);
        chart.reflow();
      }
    });
  };

  // use the new window.matchMedia query with better support
  if (window.matchMedia) {
    var mediaQueryList = window.matchMedia('print');
    mediaQueryList.addListener(function(mql) {
      if (mql.matches) {
        beforePrint();
      } else {
        afterPrint();
      }
    });
  }
  // Fallback if matchMedia isn't available
  else {
    window.addEventListener('onbeforeprint', beforePrint);
    window.addEventListener('onafterprint', afterPrint);
    // Use elsewhere if needed:
    // window.removeEventListener('onbeforeprint', beforePrint)
    // window.removeEventListener('onafterprint', afterPrint)
  }
};

// Run the setup function
_setupPrintHandler()
<script src="https://code.highcharts.com/highcharts.js"></script>
<!-- Don't need exporting anymore -->
<!-- <script src="https://code.highcharts.com/modules/exporting.js"></script> -->

<div id="container" style="height: 400px"></div>
like image 144
mix3d Avatar answered Oct 05 '22 16:10

mix3d


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());
    ...
};
like image 33
Worst Avatar answered Oct 05 '22 15:10

Worst