Nadya
Nadya

Reputation: 73

Highcharts: print chart without designated button

I want user to be able to print a whole page with highcharts control in it with standard browser's Print functionality. But control is being cut off. I wrapped control in .chart-wrapper div and try to set fixed width for printing:

@media print {
    .chart-wrapper{
        width: 1000px;
    }
}
.chart-wrapper{
    width: 100%;
}

But it does not work, and printed page looks like this: enter image description here

If I set .chart-wrapper width to 1000px outside of @media print block chart will have 1000px width both on a page and printed page, but I need chart to take all width of non-printed page.

So how can chart be displayed with 100% width on non-printed page and with 1000px on printed page?

Upvotes: 1

Views: 1372

Answers (2)

Vin
Vin

Reputation: 2155

This worked for me.

<script>
(function() {

    var beforePrint = function() {
        chart = jQuery('#graphArea').highcharts();
        chartWidth = chart.chartWidth;
        chartHeight = chart.chartHeight;
        chart.setSize(670,chartHeight, false);                  
    };

    var afterPrint = function() {
        chart.setSize(chartWidth,chartHeight, false);
        chart.hasUserSize = null;    // This makes chart responsive
    };

    if (window.matchMedia) {
        var mediaQueryList = window.matchMedia('print');
        mediaQueryList.addListener(function(mql) {
            if (mql.matches) {
                beforePrint();
            } else {
                afterPrint();
            }
        });
    }

    window.onbeforeprint = beforePrint;
    window.onafterprint = afterPrint;
}());

</script>

How it works: Detect 'before print' event, resize chart to 670px (a reliable width to print A4), detect 'after print' event and resize chart to original size.

Credits go to: TJ VanToll for detecting print event function, the people on this thread for highcharts resizing functions and this answer for suggesting the 670px.

Upvotes: 2

SteveP
SteveP

Reputation: 19093

Have you tried setting the screen width inside a @media screen css block ?

@media print {
    .chart-wrapper{
        width: 1000px;
    }
}

@media screen {
    .chart-wrapper{
         width: 100%;
    }

}

Upvotes: 0

Related Questions