【问题标题】:Save PDF file loaded in iframe保存在 iframe 中加载的 PDF 文件
【发布时间】:2015-09-25 00:49:07
【问题描述】:

我正在尝试保存加载到 iFrame 中的 pdf 文件。默认情况下,iFrame 中有一个按钮来保存文件,但我想要一个额外的按钮(在 iFrame 之外)来保存文件。

<iframe id="labelFrame" src="loadedFile.pdf"></iframe>

<button id="savePDF">Download File</button>

在 javascript 中:

 $('#savePDF').click(function(){
    var save = document.getElementById('labelFrame');
    //Save the file by opening the explorer for the user to select the place to save or save the file in a default location, how do I do this?
    }

实现这一目标的最佳方法是什么?

【问题讨论】:

  • 你有没有得到这个答案?

标签: file iframe save


【解决方案1】:

我也需要这个问题的答案并找到了解决方案。

当在 IFrame 中显示 PDF 时,浏览器会将其呈现在 &lt;embed&gt; 元素中,据我所知,我们无法在 javascript 中使用它。

我们需要使用 XMLHttpRequest 从服务器获取 PDF 作为 Blob 对象,然后我们才能显示它并使用 javascript 保存它。

var iframe = document.getElementById('labelFrame'),
    saveBtn = document.getElementById('savePDF'),
    pdfUrl = 'loadedFile.pdf';

var xhr = new XMLHttpRequest();
xhr.open("GET", pdfUrl);
xhr.responseType = 'blob'; // <- important (but since IE10)
xhr.onload = function() {
    var blobUrl = URL.createObjectURL(xhr.response); // <- used for display + download
    iframe.src = blobUrl
    saveBtn.onclick = function() {
        downloadBlob(blobUrl, 'myFilename.pdf');
    }
};
xhr.send();

xhr.onload 函数将设置为 iframe 的 src 并将 onclick 处理程序添加到保存按钮

这是我在示例中使用的downloadBlob() 函数

function downloadBlob(blobUrl, filename) {
    var a = document.createElement('a');

    a.href = blobUrl;
    a.target = '_parent';
    // Use a.download if available. This increases the likelihood that
    // the file is downloaded instead of opened by another PDF plugin.
    if ('download' in a) {
        a.download = filename;
    }
    // <a> must be in the document for IE and recent Firefox versions,
    // otherwise .click() is ignored.
    (document.body || document.documentElement).appendChild(a);
    a.click();
    a.remove();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-05-20
    • 2018-12-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-09
    相关资源
    最近更新 更多