在iframe中加载的PDF文件如何保存

5
我正在尝试保存加载在iFrame中的PDF文件。iFrame中默认有一个按钮用于保存文件,但我想要一个额外的按钮(在iFrame之外)来保存文件。请注意保留HTML标记。
<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?
    }

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

你是否得到了这个问题的答案? - Dean.DePue
1个回答

0

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

当在IFrame中显示PDF时,浏览器将在<embed>元素中呈现它,据我所知,我们无法在javascript中使用它。

我们需要使用XMLHttpRequest作为Blob对象从服务器获取PDF文件,只有这样,我们才能够使用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();
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接