jsPDF和html2canvas图像被压缩?

问题描述 投票:0回答:1

我目前正在尝试在我的网站上生成div的PDF。我的基本功能已经完成;但是,当我下载PDF时,div的内容会被压缩和拉伸,而不是与我的网站完全匹配。附件是我正在使用的代码以及PDF和网站的屏幕截图:

<link rel="stylesheet" href="/stylesheets/style.css">
<link href="https://fonts.googleapis.com/css?family=Work+Sans&display=swap" rel="stylesheet">

<div class="header" id="nodeToRenderAsPDF" style="padding: 150px 0 150px 0">
    <h2><%=companyName%>, your PDF will begin downloading!</h2>
    <p>Thanks for submitting your information. We hope you enjoy!</p>
    <button id="pdfDownloadButton">Download PDF</button>
    <a href="javascript:print()">Download PDF</a>
</div>

<script
  src="https://code.jquery.com/jquery-3.4.1.min.js"
  integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo="
  crossorigin="anonymous"></script>
<script src="/javascripts/js.js"></script>
<script src="/javascripts/jspdf.min.js"></script>
<script src="/javascripts/html2canvas.min.js"></script>

...和JS:

function print(quality = 2) {
    const filename  = 'ThisIsYourPDFFilename.pdf';

    html2canvas(document.querySelector('#nodeToRenderAsPDF'), 
                            {scale: quality}
                     ).then(canvas => {
        let pdf = new jsPDF('p', 'mm');
        pdf.addImage(canvas.toDataURL('image/png'), 'PNG', 0, 0, 211, 298);
        pdf.save(filename);
    });
}

$("#pdfDownloadButton").on("click", print);

以及一些屏幕截图:

https://imgur.com/a/h1a8sKl

非常感谢我提出的解决办法。谢谢!

javascript html jspdf html2canvas
1个回答
0
投票

我尚未对此进行测试,但是您可以尝试指定宽度和高度。因为似乎div不适合pdf页面。 div的宽度比pdf文档的标准尺寸大。让我知道是否有帮助。

html2canvas(document.querySelector('#nodeToRenderAsPDF', {
  width: 1200,
  height: 400
}).then(function(canvas) {
  let pdf = new jsPDF('p', 'mm');
  pdf.addImage(canvas.toDataURL('image/png'), 'PNG', 0, 0, 211, 298);
  pdf.save(filename);
});
© www.soinside.com 2019 - 2024. All rights reserved.