Tom*_*oro 4 javascript ajax jquery
我从外部 API 获取 PDF 文件,使用此代码我可以正确下载该文件:
\nvar req = new XMLHttpRequest();\n req.open("POST", url, true);\n req.responseType = "blob";\n req.setRequestHeader("Content-type", "application/x-www-form-urlencoded");\n req.send(data);\n\n req.onload = function (event) {\n var blob = req.response;\n var link=document.createElement('a');\n link.href=window.URL.createObjectURL(blob);\n link.download="receipt_" + new Date() + ".pdf";\n link.click();\n };\n
Run Code Online (Sandbox Code Playgroud)\n但我真正需要的是打印文件而不打开它,我尝试了类似的方法
\nwindow.open(window.URL.createObjectURL(blob));\nwindow.print();\n
Run Code Online (Sandbox Code Playgroud)\n但是,当这样做时,文件无法正确显示,它显示如下:
\nPDF-1.7\n%\xef\xbf\xbd\xef\xbf\xbd\xef\xbf\xbd\xef\xbf\xbd\n6 0 obj\n<< /Type /Page /Parent 1 0 R /LastModified (D:20201027223421-03'00') ... bla bla\n
Run Code Online (Sandbox Code Playgroud)\n提前致谢!
\nTom*_*oro 12
我已经使用以下方法解决了这个问题:
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);
};
};
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
12779 次 |
最近记录: |