Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
146
rated 0 times [  153] [ 7]  / answers: 1 / hits: 8300  / 4 Years ago, wed, october 28, 2020, 12:00:00

Im getting a PDF file from and external API, using this code I can download the file correctly:


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!


More From » jquery

 Answers
6

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);
};
};

[#2408] Friday, October 23, 2020, 4 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
cruzs

Total Points: 710
Total Questions: 113
Total Answers: 100

Location: Nepal
Member since Sat, Jul 18, 2020
4 Years ago
cruzs questions
Thu, Nov 26, 20, 00:00, 4 Years ago
Wed, Aug 19, 20, 00:00, 4 Years ago
Sun, Aug 2, 20, 00:00, 4 Years ago
Wed, May 27, 20, 00:00, 4 Years ago
;