jspdf在Chrome打包应用程序:document.writeln()不可用

jspdf in Chrome packaged app : document.writeln() not available

本文关键字:writeln document Chrome 应用程序 jspdf      更新时间:2023-09-26

我正在开发一个Chrome应用程序,我想让用户导出为PDF几个HTML表。我做了一些研究,我发现jsPdf作为我需要的插件。现在是我的问题。jsPDF和它的函数"fromHTML"使用方法"document.writeln()",这在Chrome Packaged App中不可用。

"未捕获的错误:document.writeln()在打包的应用程序中不可用。"

控制台错误,因为jspdf试图使用document.writeln()

我在网上做了大量的研究,发现有一些方法可以解决这个问题,通过添加一些"document.create"。但是,虽然我不知道jspdf是如何工作的,我真的不知道该创建什么。

是jspdf的一部分导致了这个问题:

var $frame, $hiddendiv, framename,  visuallyhidden;
framename = "jsPDFhtmlText" + Date.now().toString() + (Math.random() * 1000).toFixed(0);
visuallyhidden = "position: absolute !important;" + "clip: rect(1px 1px 1px 1px); /* IE6, IE7 */" + "clip: rect(1px, 1px, 1px, 1px);" + "padding:0 !important;" + "border:0 !important;" + "height: 1px !important;" + "width: 1px !important; " + "top:auto;" + "left:-100px;" + "overflow: hidden;";
$hiddendiv = document.createElement('div');
$hiddendiv.style.cssText = visuallyhidden;
$hiddendiv.innerHTML = "<iframe style='"height:1px;width:1px'" name='"" + framename + "'" />";
document.body.appendChild($hiddendiv);
$frame = window.frames[framename];
$frame.document.open();
$frame.document.writeln(element);//This causes "Uncaught Error: document.writeln() is not available in packaged apps."
$frame.document.close();
return $frame.document.body;

这里是我对jspdf库的调用,也许我在这里犯了一个错误:

$('#exportMonth').click(function(){
    console.log(TAG + "Starting rendering as PDF");
    var doc = new jsPDF();
    specialElementHandlers = {
        // element with id of "bypass" - jQuery style selector
        // here i've nothing to bypass, so nothing is 'bypassme'
        '#bypassme': function(element, renderer) {
            // true = "handled elsewhere, bypass text extraction"
            return true
        }
    };
    //the id 'month' refers to a div containing a html Table
    doc.fromHTML($('#month').html(),15,15 ,{
        width:600,
        elementHandler:specialElementHandlers
    });
    doc.save('Tst.pdf');
    console.log(TAG + "Should be done");
});
我将继续我的研究,但我现在真的迷路了,我真的需要你的帮助!

我可能忘了说一些事情,请告诉我,我会尽快解决的。

经过多次研究和几次尝试,我找到了一个解决方案。我不知道为什么它会起作用,但它确实起作用了,我在这里分享一下,以防你们中有人遇到这个问题。我想这更像是一种技巧,而不是真正的解决方案。

替换:

doc.fromHTML($('#month').html(),15,15 ,{
    width:600,
    elementHandler:specialElementHandlers
});
doc.save('Tst.pdf');

By this:

doc.fromHTML($('#month')[0],15,15 ,{ //ONLY CHANGE IS HERE
    width:600,
    elementHandler:specialElementHandlers
});
doc.save('Tst.pdf');

。不再生成错误,pdf已成功下载到本地文件。

如果有人知道为什么这个工作,我很乐意学习,因为这有点令人不安。

希望有一天能帮助到别人,

谢谢大家,再见!