Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
347 views
in Technique[技术] by (71.8m points)

reactjs - Having trouble while exporting component to PDF

I'm using html2canvas and jsPDF to export my component to multiple pdf pages. But there is something wrong with the loop logic that make It didn't render properly.

Here is my code:

const handlePrint = () => {

    var timeline = document.getElementById('element-to-print');

    html2canvas(timeline).then((canvas) => {
      const imgData = canvas.toDataURL("image/png");
      const pdf = new jsPDF("l", "mm", "a4");
      
      const imgProps = pdf.getImageProperties(imgData);
      
      //Get the width and height per pdf page to capture
      const pdfWidth = pdf.internal.pageSize.getWidth();
      const pdfHeight = (imgProps.height * pdfWidth) / imgProps.width;

      pdf.addImage(imgData, 'PNG', 0, 0, pdfWidth, pdfHeight);
      
      // Calculate number of pages left to capture
      var remainingPdfPages = Math.ceil(imgProps.height/pdfHeight) - 1;
      
      // Capture the remaining
      for (var i = 1; i <= remainingPdfPages ; i ++) {
        pdf.addPage();
        pdf.addImage(imgData, 'PNG', 0, pdfHeight*i, pdfWidth, pdfHeight);
      }
      // Save pdf
      pdf.save('download.pdf');

    });
  }

The value of all the width and height properties is shown below:

imgProps.width: 1127
imgProps.height: 2763
pdfWidth: 297
pdfHeight: 728
remainingPdfPages: 3

The result of that function is It stopped capturing after finishing the first page. Here is the image's link: https://imgur.com/a/lTmrfha . Can somebody point out what I'm missing. I appreciate all of your help.

question from:https://stackoverflow.com/questions/65884521/having-trouble-while-exporting-component-to-pdf

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...