Chartjs-How to improve PDF rasterization quality in PhantomJS?

1👍

im not familiar with PhantomJS.

i had a similar problem and solved by setting up the width and height of the container that contains the chart

<div id="container" style="width: 1920px; height: 1080px;">
    <canvas id="canvas"></canvas>
</div>

i also added an invisible image-tag without source

<img src="" alt="Chart" id="chartImg" style="display: none;"/>

and registered a plugin

Chart.plugins.register({
    id: 'charttoimg',
    beforeRender: function(chart, options) {
        document.getElementById('container').style.width='1920px';
        document.getElementById('container').style.height='1080px';
    },
    afterRender: function(chart, options) {
        document.getElementById('chartImg').src=chart.chart.canvas.toDataURL('image/png');
        document.getElementById('container').style.width='75%';
        document.getElementById('container').style.height='';
    }
});

with the following method i captured the print-event to toggle image and container before and after printing

(function() {
    var beforePrint = function() {
        document.getElementById('container').style.display='none';
        document.getElementById('chartImg').style.display='inline';
    };
    var afterPrint = function() {
        document.getElementById('chartImg').style.display='none';
        document.getElementById('container').style.display='block';
    };
    if (window.matchMedia) {
        var mediaQueryList = window.matchMedia('print');
        mediaQueryList.addListener(function(mql) {
            if (mql.matches) {
                beforePrint();
            } else {
                afterPrint();
            }
        });
    }
    window.onbeforeprint = beforePrint;
    window.onafterprint = afterPrint;
}());

0👍

Now in 2021 Chart.js has the parameter "devicePixelRatio" to increase the quality.
In my case, I set the value to 1.5 to get a high resolution that is also suitable for printing with PDF.

options:{
      devicePixelRatio: 1.5
}

Documentation: https://www.chartjs.org/docs/3.0.2/configuration/device-pixel-ratio.html

Leave a comment