我从外部 API 获取 PDF 文件,使用此代码我可以正确下载该文件:
var req = new XMLHttpRequest();
req.open("POST", url, true);
req.responseType = "blob";
req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
req.send(data);
req.onload = function (event) {
var blob = req.response;
var link=document.createElement('a');
link.href=window.URL.createObjectURL(blob);
link.download="receipt_" + new Date() + ".pdf";
link.click();
};
但我真正需要的是打印文件而不打开它,我尝试过类似的东西
window.open(window.URL.createObjectURL(blob));
window.print();
但是,当这样做时,文件无法正确显示,它显示如下:
PDF-1.7
%����
6 0 obj
<< /Type /Page /Parent 1 0 R /LastModified (D:20201027223421-03'00') ... bla bla
提前致谢!
我已经使用以下方法解决了这个问题:
req.onload = function (event) {
var blob = new Blob([req.response], {type: 'application/pdf'}); //this make the magic
var blobURL = URL.createObjectURL(blob);
iframe = document.createElement('iframe'); //load content in an iframe to print later
document.body.appendChild(iframe);
iframe.style.display = 'none';
iframe.src = blobURL;
iframe.onload = function() {
setTimeout(function() {
iframe.focus();
iframe.contentWindow.print();
}, 1);
};
};
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)