How Do I Prevent Children/Sub Divs from Being Cut/Split Using Html2Canvas/PDF?

47 Views Asked by At

I'm trying to create a button that when clicked downloads the html website in a PDF form but using HTML2Canvas causes the divs to be split/cut off when going to the next page. Instead of the divs being cut, I'd like for the divs to go to the new page whenever it's about to be cut.

 const saveAsPDF = () => {
    const cardElement = document.getElementById("container-to-print");

    if (!cardElement) {
        return;
    }

    html2canvas(cardElement).then((canvas) => {
        const imgData = canvas.toDataURL("image/jpeg");

        if (!imgData) {
            return;
        }

        const pdf = new jsPDF();
        const imgWidth = pdf.internal.pageSize.getWidth();
        const imgHeight = (canvas.height * imgWidth) / canvas.width;

        const pageHeight = pdf.internal.pageSize.getHeight();

        // Calculate the number of pages needed
        const totalPages = Math.ceil(canvas.height / pageHeight);

        // Add pages with images
        for (let i = 0; i < totalPages; i++) {
            if (i > 0) {
                pdf.addPage();
            }
            const position = i * pageHeight;
            pdf.addImage(imgData, "JPEG", 0, -position, imgWidth, imgHeight);
        }

        pdf.save("download.pdf");
    });
};

I've tried using ReactPDF but it seems to be impractical for my React project as it's many nested divs I have to add the tags (like , etc) too.

The current solution just adds blank pages and causes the children divs to be cut.

0

There are 0 best solutions below