【问题标题】:Chrome viewer pdf button not working with jsPDFChrome 查看器 pdf 按钮不适用于 jsPDF
【发布时间】:2018-12-07 09:56:05
【问题描述】:

Chrome pdf viewer button is not working with jsPDF

我正在使用 jsPDF 生成 pdf,它工作正常。 Chrome 查看器 pdf 按钮不起作用。我尝试了许多不同的方法,但都没有成功。

在这里我想分享示例代码:

download() {
var doc = new jsPDF();
doc.text(20, 20, 'Hello world!');
doc.text(20, 30, 'This is client-side Javascript, pumping out a PDF.');
doc.addPage();
doc.text(20, 20, 'Do you like that?');

// Save the PDF

var string = doc.output('datauristring');
var iframe = "<iframe width='100%' height='100%' src='" + string + "'></iframe>"
var x = window.open();
x.document.open();
x.document.write(iframe);
x.document.close();
//doc.save('Test.pdf');

}

通过此代码,新选项卡已打开,但 chrome 查看器下载按钮不起作用。

那么有没有其他方法可以做到这一点。

【问题讨论】:

    标签: pdf jspdf


    【解决方案1】:

    我找到了解决方案。我们只需使用此代码,Chrome pdf 查看器下载按钮就可以正常工作。

    window.open(doc.output('bloburl'), '_blank');

    【讨论】:

    • 不适合我,你能指定你在哪里使用 window.open(doc.output('bloburl'), '_blank');??
    • @SergioCano 在您的 pdf 文件代码末尾,您可以使用此代码并在新选项卡中打开 pdf,您可以选择下载文件:window.open(doc.output('bloburl '), '_blank');
    • 谢谢,它正在工作,但它也产生了其他问题,pdfs名称现在是打开的新标签页的url,这是一个非常罕见的名称,你是如何处理的?提前致谢
    • 我使用了这个函数 doc.save('fileName' );之前 window.open(doc.output('bloburl'), '_blank');当用户单击它时,它将提供使用您指定的文件名保存文件的选项。但不幸的是,当用户通过浏览器单击下载按钮时,我没有更改文件名的解决方案。
    • @Carsten 抱歉,伙计,我找不到解决方案,但我找到了另一种方法...以模态显示 PDF,所以我不需要打开新标签...所以... pdf 的名称和下载按钮工作正常。希望对你有帮助
    【解决方案2】:

    虽然 window.open 工作正常,但出于安全原因,新的 chrome 版本默认会阻止弹出窗口,因此我需要另一个解决方案。

    我个人会再次尝试 iframe 解决方案。我正在编写下面对我有用的解决方案:

    HTML 代码(用于屏幕上的全尺寸 iframe):

     <iframe id="main-iframe" style="width: 100%; height: 100%; position: fixed; top: 0; left: 0; z-index: 2; border: none;"></iframe>
    

    JavaScript 代码:

     document.getElementById('main-iframe').setAttribute('src', doc.output('bloburl'));
    

    【讨论】:

      【解决方案3】:

      添加一些方便的东西: window.open 对我有用,但是当我只使用时

      window.open(pdf.output('bloburl'), '_blank')
      

      它给了我错误

      error TS2345: Argument of type 'URL' is not assignable to parameter of type 'string'.
      

      为了纠正这个问题,我只需要添加 .toString()。下面是我使用的代码以及如何编辑打开的标签的标题。

      PDF.setProperties({
          title: "jsPDF sample"
      });
      window.open(PDF.output('bloburl').toString(), '_blank');
      

      【讨论】:

        猜你喜欢
        • 2018-05-15
        • 2017-01-23
        • 2017-12-20
        • 1970-01-01
        • 1970-01-01
        • 2011-04-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多