Download and Open PDF File Using Ajax

Download and open PDF file using Ajax

You don't necessarily need Ajax for this. Just an <a> link is enough if you set the content-disposition to attachment in the server side code. This way the parent page will just stay open, if that was your major concern (why would you unnecessarily have chosen Ajax for this otherwise?). Besides, there is no way to handle this nicely acynchronously. PDF is not character data. It's binary data. You can't do stuff like $(element).load(). You want to use completely new request for this. For that <a href="pdfservlet/filename.pdf">pdf</a> is perfectly suitable.

To assist you more with the server side code, you'll need to tell more about the language used and post an excerpt of the code attempts.

Download pdf file using jquery ajax

jQuery has some issues loading binary data using AJAX requests, as it does not yet implement some HTML5 XHR v2 capabilities, see this enhancement request and this discussion

Given that, you have one of two solutions:

First solution, abandon JQuery and use XMLHTTPRequest

Go with the native HTMLHTTPRequest, here is the code to do what you need

  var req = new XMLHttpRequest();
req.open("GET", "/file.pdf", true);
req.responseType = "blob";

req.onload = function (event) {
var blob = req.response;
console.log(blob.size);
var link=document.createElement('a');
link.href=window.URL.createObjectURL(blob);
link.download="Dossier_" + new Date() + ".pdf";
link.click();
};

req.send();

Second solution, use the jquery-ajax-native plugin

The plugin can be found here and can be used to the XHR V2 capabilities missing in JQuery, here is a sample code how to use it

$.ajax({
dataType: 'native',
url: "/file.pdf",
xhrFields: {
responseType: 'blob'
},
success: function(blob){
console.log(blob.size);
var link=document.createElement('a');
link.href=window.URL.createObjectURL(blob);
link.download="Dossier_" + new Date() + ".pdf";
link.click();
}
});

PDF File download from AJAX Post success callback

The result you get back from using jQuery ajax is plain text and can lead to "out of range" for downloading binary as text and not as arrayBuffer or blob. jQuery don't support responseType in any way (that i know of)

So you need to rely on xhr or fetch to get it as a blob to get the content right. Otherwise you will get corrupt data

Here is an example of using the new fetch api and FileSaver

function saveAs(blob, filename){
if(navigator.msSaveOrOpenBlob)
return navigator.msSaveOrOpenBlob(blob, filename)

var link = document.createElement('a')
link.href = window.URL.createObjectURL(blob)
link.download = filename
link.click()
}

fetch(myUrl, {
method: 'post',
body: JSON.stringify(params)
headers: {
'Content-Type': 'application/json;charset=UTF-8'
}
})
.then(res => res.blob())
.then(blob => saveAs(blob, 'PreviewProposalAsPdf.pdf'))

// EXAMPLE USING XHR
var req = new XMLHttpRequest
req.open('GET', myUrl, true)
req.responseType = 'blob'
req.onload = function() {
saveAs(res.response, 'Dossier_' + new Date() + '.pdf')
}
req.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');
req.send(JSON.stringify(params))

But ofc, there is more wider support if you use xhr + responseType = blob

The best thing you can do is just send content-disposition header and make a attachment - but then you can not use ajax... need to submit form (could be from iframe)

Download pdf file from ajax response

Any idea on how to optimize it for all modern browsers?

Yes, I can give you a solution tested on windows 10 with IE11, Firefox 47 and Chrome 52. Nothing for Microsoft Edge at the moment.

At the beginning you need to distinguish if you are on IE or the other two browsers. This because on IE11 you can use:

window.navigator.msSaveBlob(req.response, "PdfName-" + new Date().getTime() + ".pdf");

For the other two browsers your code works on Chrome but not on Firefox because you did not append the element to the document body.

So the corrected code is:

var req = new XMLHttpRequest();
req.open("POST", "/servicepath/Method?ids=" + ids, true);
req.responseType = "blob";
req.onreadystatechange = function () {
if (req.readyState === 4 && req.status === 200) {

// test for IE

if (typeof window.navigator.msSaveBlob === 'function') {
window.navigator.msSaveBlob(req.response, "PdfName-" + new Date().getTime() + ".pdf");
} else {
var blob = req.response;
var link = document.createElement('a');
link.href = window.URL.createObjectURL(blob);
link.download = "PdfName-" + new Date().getTime() + ".pdf";

// append the link to the document body

document.body.appendChild(link);

link.click();
}
}
};
req.send();

Not able to download Pdf/Excel with JQuery AJAX get request with some data sent with get request

This works

$.ajax({
url: "http://localhost:8000/get_excel",
type: "POST",
data: {data : list_of_tables},
dataType: 'binary',
xhrFields: {
'responseType' : 'blob'
},
headers: {
'Accept': "application/json",
'Authorization': 'Bearer ' + getCookie(ACCESS_TOKEN),
},
success: function (data, textStatus, request) {
alert("success in fetching data");
let url = URL.createObjectURL(data);
let $a = $('<a />', {
'href': url,
'download': 'document.xlsx',
'text': "click"
}).hide().appendTo("body")[0].click();

// URL.revokeObjectURL(url);

},
error: function (XMLHttpRequest, data) {
console.log("error in show_history");
console.log(data);
console.log(XMLHttpRequest.status);
console.log(XMLHttpRequest.responseJSON);
}
});



Related Topics



Leave a reply



Submit