【问题标题】:Js pdf browser crashes for chrome, firefoxchrome、firefox的js pdf浏览器崩溃
【发布时间】:2016-04-27 17:36:28
【问题描述】:

我们正在使用 jsPDF 将 HTML 生成为 PDF。但是,在向我的 PDF 添加 40 个元素并将其渲染到画布时,我的浏览器崩溃了。

我们正在使用以下函数将元素作为图像添加到 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);
    }

我们也尝试过使用以下解决方案。

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

或者有什么方法可以将低分辨率图像添加到 pdf 中。

【问题讨论】:

    标签: jquery image pdf jspdf html2canvas


    【解决方案1】:

    如果您有很多图像,请尝试使用 addImage 的压缩参数。

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

    您可能需要测试每个压缩选项以查看哪个可以处理您需要的内容:“FAST”、“SLOW”、“MEDIUM”、“NONE”。

    在我对包含大量图像的 PDF 进行的测试期间,这产生了巨大的差异。在处理过程中内存仍然很高,但它确实提高了速度和性能。

    【讨论】:

    • 链接已失效,能否提供新链接?
    • 谢谢@JayeshL!我已经用新链接更新了帖子。代码进行了大幅度的重构。
    猜你喜欢
    • 2017-03-15
    • 2020-06-09
    • 2018-08-20
    • 2019-08-02
    • 2016-07-14
    • 2013-10-24
    • 2018-06-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多