简体   繁体   中英

How to fix content cut off issues in jspdf / html2canvas?

I am using jspsf and html2canvas to convert the components into a PDF.

Below is the code for that,

  function generatePDF() {
    const input = document.getElementById("pdf");
    html2canvas(input, {
      logging: true,
      letterRendering: 1,
      scale: 2,
      windowWidth: 1440,
      useCORS: true
    }).then((canvas) => {
      var imgData = canvas.toDataURL("image/png");
      var imgWidth = 210;
      var pageHeight = 295;
      var imgHeight = (canvas.height * imgWidth) / canvas.width;
      var heightLeft = imgHeight;
      var doc = new jsPDF("p", "mm");
      var position = 0;
      doc.addImage(imgData, "jpeg", 0, position, imgWidth, imgHeight);
      heightLeft -= pageHeight;
      while (heightLeft >= 0) {
        position = heightLeft - imgHeight;
        doc.addPage();
        doc.addImage(imgData, "jpeg", 0, position, imgWidth, imgHeight);
        heightLeft -= pageHeight;
      }

      const pages = doc.internal.getNumberOfPages();

      for (let j = 1; j < pages + 1; j++) {
        let horizontalPos = imgWidth / 2; //Can be fixed number
        let verticalPos = pageHeight - 10; //Can be fixed number
        doc.setPage(j);
        doc.setFontSize(10);
        doc.text(`${j} of ${pages}`, horizontalPos, verticalPos, {
          align: "center" //Optional text styling});
        });
      }

      doc.save("output.pdf");
    });
  }

Here I am facing a problem of content cutting off, like this in the below image.

在此处输入图像描述

is there any way to fix this issue? Please help me to solve this one.

Here you can get the working demo link - https://codesandbox.io/s/react-component-to-pdf-goe-page-cutting-3rnl29?file=/src/App.js:412-1697

is this achievable by using html2pdf / react-to-print ?

The values and charts might get added based on the API data. It's a dynamic component

Sure, just remove the top and bottom padding from the pdf in styles.css

eg

.pdf {
  margin: 0;
  padding: 0 20px;
  max-width: 1000px;
}

result

在此处输入图像描述

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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