2014-05-05

HOWTO: Make Google Charts SVG responsible and printable with full page width

Google Charts is widely used for a while. It's no doubt that it is easy to use and have great documentation. But, it has also many limitations. One problem I recently discovered is printing. Since the SVG that is generated by Google Charts is NOT responsible. If the user wants to print the page, the result only shows part of the charts since the Google Charts adds a CSS style like "overflow:hidden" to the SVG.

What I want is very simple, the user gets a printed result like WYSIWYG. After different approaches, I came to the idea of Image Replacement. 

The idea: since the generated SVG doesn't response to width changes, we have to use a responsive image instead of the SVG to get the perfect print result.

So here is the implementation. :)

HTML:
<div id='timeline'></div>
<div id='timeline_print'></div>

CSS:
@media print {
    #timeline_print {
        width: 100%;
    }
}

JavaScript(assumed that jQuery is loaded, this.chart refers to the Google Charts object):

var beforePrint = function() {
    $("#timeline_print").html('<img src="' + this.chart.getImageURI() + '">');
    $("#timeline").addClass('hidden');
};
var afterPrint = function() {
    $("#timeline_print").empty();
    $("#timeline").removeClass('hidden');
};
if (window.matchMedia) {
    var mediaQueryList = window.matchMedia('print');
    mediaQueryList.addListener(function(mql) {
        if (mql.matches) {
            beforePrint();
        } else {
            afterPrint();
        }
    });
}

window.onbeforeprint = beforePrint;
window.onafterprint = afterPrint;

No comments: