eKoopmans/html2pdf.js

Generate a multi-page PDF with a scroll y div using html2canvas and jsPDF

Opened this issue · 0 comments

When I generate a PDF using html2canvas and jsPDF, the div with className="overflow-auto h-[200px]" only shows the first page with data when printing, while pages 2 and 3 are blank. Please provide me with a solution.

const handleDownloadPdf = async () => {
const element = printRef.current;
const options = {
allowTaint: true,
dpi: 300,
letterRendering: true,
logging: false,
scale: 1,
};

if (element) {
  console.log("scrollTop", element.scrollTop);
  const currentPosition = element.scrollTop;
  element.style.height = "auto";
  const totalHeight = element.scrollHeight; 
  console.log("totalHeight", totalHeight);
  const pdf = new jsPDF("p", "px", "a4");
  const marginLeft = 20 * 3.77953; 
  const marginTop = 20 * 3.77953; 

  const pdfWidth = 210 * 3.77953;
  const pdfHeight = 297 * 3.77953; 

  const imgWidth = pdfWidth - marginLeft * 2; 
  console.log("imgWidth", imgWidth);

  let remainingHeight = totalHeight; 
  let positionY = 0; 

  while (remainingHeight > 0) {
    const canvasSectionHeight = Math.min(
      remainingHeight,
      pdfHeight - marginTop * 2 
    );
    console.log("remainingHeight", remainingHeight);
    console.log("canvasSectionHeight", canvasSectionHeight);

    element.scrollTop = positionY;
    console.log("element.scrollTop", element.scrollTop);
    console.log("positionY", positionY);
  
    await new Promise((resolve) => setTimeout(resolve, 500));
    const canvas = await html2canvas(element, {
      ...options,
      height: canvasSectionHeight,
      y: positionY,
    });

    const imgData = canvas.toDataURL("image/png");
    const imgHeight = (canvas.height * imgWidth) / canvas.width; // Tính chiều cao hình ảnh
    console.log("imgHeight", imgHeight);
  
    pdf.addImage(
      imgData,
      "PNG",
      marginLeft,
      positionY,
      imgWidth,
      imgHeight,
      undefined,
      "FAST"
    );


    remainingHeight -= canvasSectionHeight;
    positionY += canvasSectionHeight;

    if (remainingHeight > 0) {
      pdf.addPage(); 
    } else {
      pdf.save("web.pdf"); 
    }
  }
  element.style.height = "200px";
  element.scrollTop = currentPosition;
} else {
  console.error("Element not found for PDF generation.");
}

};