Search code examples
javascriptreactjspngjspdf

How to size a canvas for jsPDF


I'm working in chrome with jsPDF in react. I am making a canvas then attempting to place a png image of my website on that canvas and download it as a pdf. The process works but the image appears stretched. I have tried altering the size of the canvas manually and changing the dimensions of the image placed on the canvas but that seems to have no effect on the final pdf.

Has anyone dealt with this annoying issue before who can provide some guidance? thanks :)

code to create a pdf:

downloadPdf = (quality = 2) => {
        const filename  = 'ThisIsYourPDFFilename.pdf';

        html2canvas(document.querySelector('#nodeToRenderAsPDF'), 
                                {scale: quality}
                         ).then(canvas => {
            let pdf = new jsPDF('p', 'px', 'a4'); 
            pdf.height="600"
            pdf.width= "800" //this is the canvas resolution
            pdf.addImage(canvas.toDataURL('image/png'), 'PNG', 0, 0, 450, 500); //this is the image resolution
            pdf.save(filename);
        });
    }

I'll also include the final PDF I get for reference enter image description here


Solution

  • Your image dimensions are 450 x 500, but your pdf dimensions are 600 x 800. 450 / 500 = .9 = 90% and 600 / 800 = .75 = 75%, so your image will appear stretched as it converts from one aspect ratio to another. If I were you, I would pick one set of sizes and stick with it. 600 x 800 seems reasonable, so try to change that last line to:

    pdf.addImage(canvas.toDataURL('image/png'), 'PNG', 0, 0, 600, 800); //this is the image resolution
    

    and declare your canvas size the same (ie, wherever that canvas html element is declared, set it like <canvas id="myCanvas" width="600" height="800"></canvas>).