简体   繁体   English

html2canvas/jsPDF - 将 html 转换为 pdf 时不显示图像

[英]html2canvas/jsPDF - images not showing when converting html to a pdf

I'm looking to convert some simple HTML into a PDF.我希望将一些简单的 HTML 转换为 PDF。 It seems the easiest way to do this and keep the css styling is to use the 'html2canvas' js library to convert the html to canvas first, and then create the PDF using jsPDF. It seems the easiest way to do this and keep the css styling is to use the 'html2canvas' js library to convert the html to canvas first, and then create the PDF using jsPDF.

The issue I'm getting is that I have both a background image and inline image in my HTML but neither are showing in the PDF once converted.我遇到的问题是我的 HTML 中既有背景图像又有内联图像,但转换后的 PDF 中都没有显示。 I've created a Codepen here: https://codepen.io/adamboother/pen/NWGeqom我在这里创建了一个 Codepen: https://codepen.io/adamboother/pen/NWGeqom

Here's my js that does the conversion:这是我的 js 进行转换:

function convertToPdf()
{
    html2canvas(document.querySelector('#certificate')).then(canvas => {
        let pdf = new jsPDF('landscape', 'mm', 'a4');

        pdf.addImage(canvas.toDataURL('image/png'), 'PNG', 0, 0, pdf.internal.pageSize.width, pdf.internal.pageSize.height);

        pdf.save('certificate.pdf');
    });
}

Has anyone found a fix for this?有没有人找到解决这个问题的方法?

I am using useCORS: true to your code and it works, assuming your image is in the server.我正在使用useCORS: true to your code 并且它可以工作,假设你的图像在服务器中。 Besides you can follow below code:此外,您可以遵循以下代码:

function convertToPdf()
{ 
    html2canvas(document.querySelector('#certificate'), {useCORS: true}).then(function(canvas) {
      let img = new Image();
      img.src = canvas.toDataURL('image/png');
      img.onload = function () {
        let pdf = new jsPDF('landscape', 'mm', 'a4');
        pdf.addImage(img, 0, 0, pdf.internal.pageSize.width, pdf.internal.pageSize.height);
        pdf.save('certificate.pdf');
      };
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM