Search code examples
jqueryimagepdfjspdfhtml2canvas

Js pdf browser crashes for chrome, firefox


We are using jsPDF for generating HTML to PDF. however while adding 40 elements to my PDF and rendering it to canvas my browser crashes.

We are using below function for adding and element as image to pdf.

function addElement(element, doc, opt, newPage, callback) {
        var thiscreen = element;
        //Get the original background color.
        var originalBGColor = thiscreen.style.backgroundColor;
        //Change the background color of the element to desired color.
        if (opt.bgColor)
            thiscreen.style.backgroundColor = opt.bgColor;
        var options = options || {};
        options.elements = [thiscreen];
        //Increment the in-progress counter.
        counter++;
        console.log('adding' + counter);
        console.log(element);
        //The complete callback method.
        options.complete = setTimeout(function(images) {
            //Decrement the in-progress counter since the image is successfully generated..
            counter--;
            console.log('complete' + counter);
            console.log(element);
            var queue = html2canvas.Parse(thiscreen, images, options),
                canvas = html2canvas.Renderer(queue, options);
            //Reset the background color.
            thiscreen.style.backgroundColor = originalBGColor;
            //Add the generated image to PDF document.
            doc.addImage(canvas.toDataURL(), 'png', opt.x, opt.y, opt.width, opt.height);
            //Call the callback method if any
            if (callback) {
                callback();
            }
        }, 500);
        //Conver the html to PNG using html2canvas util.
        html2canvas.Preload(thiscreen, options);
    }

We have also tried using below solution.

var blob = doc.output("blob");
window.open(URL.createObjectURL(blob));

Or is there any way to add low resolution images to pdf.


Solution

  • If you have a lot of images, try using the compression parameter with addImage.

    https://github.com/MrRio/jsPDF/blob/master/src/modules/addimage.js#L720

    You may need to test each compression option to see which one handles what you need: 'FAST', 'SLOW', 'MEDIUM', 'NONE'.

    During the testing I've done with PDF's with a large amount of images, this has made a drastic difference. The memory still gets pretty high during the processing, but it does improve the speed and performance.