我正在尝试保存在 iFrame 中加载的 pdf 文件。默认情况下,iFrame 中有一个按钮用于保存文件,但我想要一个额外的按钮(在 iFrame 外部)来保存文件。
<iframe id="labelFrame" src="loadedFile.pdf"></iframe>
<button id="savePDF">Download File</button>
Run Code Online (Sandbox Code Playgroud)
在 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?
}
Run Code Online (Sandbox Code Playgroud)
达到这个目标的最佳方法是什么?
我也需要这个问题的答案并找到了解决方案。
当在 IFrame 中显示 PDF 时,浏览器会将其呈现在一个<embed>元素中,据我所知,从那里我们无法在 javascript 中使用它。
我们需要使用XMLHttpRequestJavaScript 从服务器获取 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();
Run Code Online (Sandbox Code Playgroud)
该xhr.onload函数将设置src为 iframe 并将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();
}
Run Code Online (Sandbox Code Playgroud)