Search code examples
javascriptpdfhtml2canvasjspdf

Cannot add content after PDF reaches certain size


I made a recursive function for generate a PDF iterating some divs. When there's no more divs, I save the PDF. I'm using html2canvas to catpure the HTML code of each div into a canvas and jsPDF to put the canvas as an image and generate the PDF. This code works well, except when the PDF exceeds 8MB, it stops adding content:

I want to know if jsPDF have a limit in size when generating PDF's.

var doc = new jsPDF();

appendDataToPDF(some_div, doc, 1); /* calling function below */

function appendDataToPDF(div, doc, top)
{
    html2canvas(div, {
        onrendered: function(canvas) {
            var img = canvas.toDataURL();
            doc.addImage(img, 'JPEG', 10, top, width, height);

            if(top > 200 /* some value to detect if limit of page reached */)
            {
                doc.addPage();
                top = 1;
            }
            else
                top += 40;

            div = div.nextSibling;

            if(div === null)
                doc.save('Test.pdf');
            else
                appendDataToPDF(div, doc, top);
        }
    });
}

Solution

  • There shouldn't be any hard limits, other than resources available to your machine. Max I generated was only a 2.7MiB 21-page pdf file but I could only save this file on my machine. Displaying it directly in a new tab would cause FF and Chrome to crash, probably because the data: uri is too long, since smaller files work just fine.

    FYI, you can actually call doc.addHTML() in the current version, which uses html2canvas internally:

    function appendDataToPDF(div, doc, top, left) {
        doc.addHTML(div, top, left, {w: width, h: height}, function() {
            if(top > 200) {
                doc.addPage();
                top = 1;
            }
            else
                top += 40;
    
            div = div.nextSibling;
    
            if(div === null)
                doc.save('Test.pdf');
            else
                appendDataToPDF(div, doc, top, left);
        });
    }