【问题标题】:Writing PDF on local storage using JsPdf in PhoneGap在 PhoneGap 中使用 JsPdf 在本地存储上编写 PDF
【发布时间】:2014-08-12 08:01:18
【问题描述】:

我正在尝试通过 jspdf 编写一个 html 转换的 pdf 文件,但它在这里不起作用的是 js 方法

function gotFileWriter(writer) {
    writer.onwriteend = function(evt) {
        console.log("contents of file now 'some sample text'");
        writer.truncate(11);
        writer.onwriteend = function(evt) {



            console.log("contents of file now 'some sample'");
            writer.seek(4);var pdfOut;
        var pdf = new jsPDF('p','pt','a4');
        pdf.addHTML(document.body,function() {
        pdfOut = pdf.output('datauri');
                });
         // this alerts shows "Undefined"
        alert(pdfOut);
        writer.write(pdfOut);



            writer.onwriteend = function(evt){
                console.log("contents of file now 'some different text'");
            }
        };
    };
            var pdfOut;
        var pdf = new jsPDF('p','pt','a4');
        pdf.addHTML(document.body,function() {
        pdfOut = pdf.output('datauri');
                });
        // this alerts shows "Undefined"
            alert(pdfOut);
        writer.write(pdfOut);


}

两个警报都显示“未定义”。如果我将其创建为 .txt 文件,它会显示空文件,如果我将其保存为 .pdf,则如果创建损坏的文件。 JsPdf 工作正常,因为我可以在日志中看到 pdf.output('datauri'); 的 base64 字符串结果...

【问题讨论】:

  • 你能分享你使用 jspdf lib 跟随我的教程,但它没有生成 pdf 文件
  • @Erum :我不记得我遵循了哪个教程,但有问题的代码工作正常,诀窍是您需要等待 addHTML 方法执行其功能,然后编写 pdf 文件。请参阅下面接受的答案和我的评论。

标签: javascript cordova jspdf


【解决方案1】:

addHTML 调用是异步的,因此您必须等待完成才能尝试使用 pdf 输出。此外,最适合使用 FileWriter 的“arraybuffer”输出。

试试这个:

    function gotFileWriter(writer) {
      writer.onwriteend = function (evt) {
        console.log("contents of file now 'some sample text'");
        // ...
      };
      var pdf = new jsPDF('p', 'pt', 'a4');
      pdf.addHTML(document.body, function () {
        writer.write(pdf.output('arraybuffer'));
      });
    }

【讨论】:

  • 这是仪式我发现了问题并使用“setTimeout”等待,但你的方法看起来好多了..谢谢..
猜你喜欢
  • 2015-01-05
  • 2013-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-02
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多