Chartjs-Changing size of the canvas makes it blurry

0👍

Canvas to PDF with selected DPI using chart.js and html2pdf.js

To change the output resolution for the canvas in the PDF you need to set the DIP

From memory a A4 is ~11+ inch across in landscape and you want to fit 2000 pixels, So let have a margin total of 1+inch making the width of the graph 10". We can use the CSS unit size of points (72 points per inch) so the canvas size should be 72pt * 10" = 720pt across. Scale the height by the same amount.

Now to get the DPI divide the canvas.width by the size 2000 / 10 = 200.

But I am assuming you want higher than that. So let’s do it more accurately.

const A4 = {  // looked this up with google
    width : 11.69,
    height : 8.27,
}
// using pts and inches (I dont like using CSS inches)
const points = 72; // points per inch
const graphWidth = 10; // in inches on the page.
const graphDPI = 300; // desired DPI
const aspect = 492/2000; // aspect of image

function generate_pdf(){
    var canvas = document.getElementById('blanks_graph');
    canvas.width = graphWidth * graphDPI;
    canvas.height = Math.floor(canvas.width * aspect);
    canvas.style.width = (graphWidth * points) + "pt";
    canvas.style.height = Math.floor(graphWidth * points * aspect)+"pt";
    // add left margin to center graph.
    // you should remove the button and maybe put a margin on the top of
    // the canvas
    canvas.style.marginLeft = Math.floor(((A4.width - graphWidth) / 2) * points) + "pt"
    // changing the size needs to redraw the canvas
    redrawGraph();
    // the graph is drawn via a timeout event so will not be ready untill
    // after this function is done. Also there is the animation to avoid
    // So easy way is to just create the PDF with a timeout
    setTimeout(function(){
        var element = document.getElementById('main_data_div');
        html2pdf(element, {
            margin:       0,
            filename:     'myfile.pdf',
            image:        { type: 'jpeg', quality: 0.98 },
            html2canvas:  { dpi: graphDPI, letterRendering: true },
            jsPDF:        { unit: 'in', format: 'a4', orientation: 'l' }
         });
        },
        3000 // 3 seconds to redraw and animate.
    );
}

function redrawGraph(){ // redraws the graph
                        // just wrap this function around the graph draw code

Leave a comment