首页 > 解决方案 > 如何为 jsPDF 调整画布的大小

问题描述

我在 chrome 中使用 jsPDF 在 react 中工作。我正在制作一个画布,然后尝试将我的网站的 png 图像放在该画布上并将其下载为 pdf。该过程有效,但图像显得拉伸。我尝试手动更改画布的大小并更改放置在画布上的图像的尺寸,但这似乎对最终的 pdf 没有影响。

在谁能提供一些指导之前,有没有人处理过这个烦人的问题?谢谢 :)

创建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);
        });
    }

我还将包含我获得的最终 PDF 以供参考在此处输入图像描述

标签: javascriptreactjspngjspdf

解决方案


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>).


推荐阅读