Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
peapaa opened this issue Oct 20, 2024 · 0 comments
Open

Comments

@peapaa
Copy link

peapaa commented Oct 20, 2024

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.");
}

};

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant