我也需要这个问题的答案并找到了解决方案。
当在 IFrame 中显示 PDF 时,浏览器会将其呈现在 <embed> 元素中,据我所知,我们无法在 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();
}