[英]Print PDF from BLOB
Im getting a PDF file from and external API, using this code I can download the file correctly:我从外部 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();
};
But what I really need is to print the file without open it , I tried something like但我真正需要的是在不打开文件的情况下打印文件,我尝试了类似的方法
window.open(window.URL.createObjectURL(blob));
window.print();
But when do this way the file does not show correctly, It shows something like this:但是当这样做时,文件无法正确显示,它显示如下:
PDF-1.7
%����
6 0 obj
<< /Type /Page /Parent 1 0 R /LastModified (D:20201027223421-03'00') ... bla bla
Thanks in advance!提前致谢!
Try the code below to make sure the .pdf file is correct.试试下面的代码以确保 .pdf 文件是正确的。 Verify the pdf with the preview that opens.
使用打开的预览验证 pdf。
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>MDN Example</title>
<script type="text/javascript">
function closePrint () {
document.body.removeChild(this.__container__);
}
function setPrint () {
this.contentWindow.__container__ = this;
this.contentWindow.onbeforeunload = closePrint;
this.contentWindow.onafterprint = closePrint;
this.contentWindow.focus(); // Required for IE
this.contentWindow.print();
}
function printPage (sURL) {
var oHiddFrame = document.createElement("iframe");
oHiddFrame.onload = setPrint;
oHiddFrame.style.position = "fixed";
oHiddFrame.style.right = "0";
oHiddFrame.style.bottom = "0";
oHiddFrame.style.width = "0";
oHiddFrame.style.height = "0";
oHiddFrame.style.border = "0";
oHiddFrame.src = sURL;
document.body.appendChild(oHiddFrame);
}
</script>
</head>
<body>
<!-- <p><span onclick="printPage('externalPage.html');" style="cursor:pointer;text-decoration:underline;color:#0000ff;">Print external page!</span></p> -->
</body>
</html>
<script>
req.onload = function (event) {
var blob = req.response;
var link=document.createElement('a');
let srcPdf =window.URL.createObjectURL(blob);
printPage(srcPdf)
};
</script>
I have already solve this using:我已经使用以下方法解决了这个问题:
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);
};
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.