Search code examples
jspdfhtml2canvas

html2canvas out of memory


Good day, colleagues. I have the problem, html2canvas when generating screenshots I give the error "out of memory" in google chrome.

                window.jsPDF = window.jspdf.jsPDF;
                let printArea = [...document.querySelectorAll('.print:not([style*="display: none;"])')]
                var doc = new jsPDF('l', 'mm', "a4");
                let tasks = printArea.map(tab => html2canvas(tab, {scale:2, removeContainer: true}))

                
                Promise.all(tasks).then(canvases =>
                {
                    var boolAdd = false
                    console.log(canvases)
                    for (const canvas of canvases)
                    {
                        if(true == boolAdd) {
                            doc.addPage();
                        }
                    
                        let imgData = canvas.toDataURL('image/jpeg', 0.6);
                        const pageHeight = doc.internal.pageSize.getHeight();
                        const imgWidth = doc.internal.pageSize.getWidth();
                    
                        var imgHeight = canvas.height * imgWidth / canvas.width;
                        var heightLeft = imgHeight - 20;
                        var position = 10;
                        doc.addImage(imgData, 'JPEG', 20, position, imgWidth - 40, imgHeight);
                        heightLeft -= pageHeight;
                    
                        position += heightLeft - imgHeight; // top padding for other pages
                        doc.addImage(imgData, 'PNG', 0, position, imgWidth, imgHeight, undefined,'FAST');
                        heightLeft -= pageHeight;
                        boolAdd = true
                    }
                    
                    console.log("report")
                    doc.save( 'report.pdf');
                })

how to fix the error? Or how to free up memory? Alternatively, you can offer another library if you can't make it so that there are no memory problems.

Example

https://embed.plnkr.co/plunk/Zz4iFK 700 > mb


Solution

  • Good day, Comrads. I solved my problem. I replaced library html2canvas on htmlToImage witch method toCanvas. –