Download pdf file using jquery ajax

I want to download a pdf file for jquery ajax response. Ajax response contains pdf file data. I tried this solution. My code is given below but I always get a blank pdf.

$(document).on('click', '.download-ss-btn', function () < $.ajax(< type: "POST", url: 'http://127.0.0.1:8080/utils/json/pdfGen', data: < data: JSON.stringify(jsonData) >>).done(function (data) < var blob = new Blob([data]); var link = document.createElement('a'); link.href = window.URL.createObjectURL(blob); link.download = "Sample.pdf"; link.click(); >); >); 
1 1 1 silver badge asked Jan 4, 2016 at 7:43 1,747 1 1 gold badge 19 19 silver badges 41 41 bronze badges Try substituting XMLHttpRequest for jQuery.ajax() see stackoverflow.com/questions/12876000/… Commented Jan 4, 2016 at 7:45

Why do you need to use AJAX for this? Downloading files is much more easily and reliably done without it.

Commented Jan 4, 2016 at 7:57

You can not make pdf with json response.It should be a HTML response and also it dosn't work on all browser. In given ex. it returns Url means a HTML response.

Commented Jan 4, 2016 at 8:00

Here i am using a web service to get formatted pdf file for json data. the response pdf file data start with %PDF-1.4

Commented Jan 4, 2016 at 8:08

You have to write code in success then .done and in which browser version you are testing. ` Blob([data])` not working in some browser.

Commented Jan 4, 2016 at 8:11

5 Answers 5

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(); >>); 
answered Jan 4, 2016 at 9:26 2,706 1 1 gold badge 15 15 silver badges 18 18 bronze badges

To make it work in Firefox you have to add 'document.body.appendChild(link);' before clicking the link :)

Commented Jun 8, 2017 at 11:24

Works nicely but I found you will need window.navigator.msSaveBlob(blob, filename); to get this working in IE11 as shown by @anonymous.

Commented Mar 21, 2018 at 16:22 Thank you so much! Commented Jan 30, 2019 at 7:33 This is exactly what I needed. xhrFields: < responseType: 'blob' >, Commented Feb 11, 2019 at 23:43

InvalidStateError: Failed to read the 'responseText' property from 'XMLHttpRequest': The value is only accessible if the object's 'responseType' is '' or 'text' (was 'blob').

Commented Jun 18, 2019 at 14:24

I am newbie and most of the code is from google search. I got my pdf download working with the code below (trial and error play). Thank you for code tips (xhrFields) above.

$.ajax(< cache: false, type: 'POST', url: 'yourURL', contentType: false, processData: false, data: yourdata, //xhrFields is what did the trick to read the blob to pdf xhrFields: < responseType: 'blob' >, success: function (response, status, xhr) < var filename = ""; var disposition = xhr.getResponseHeader('Content-Disposition'); if (disposition) < var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/; var matches = filenameRegex.exec(disposition); if (matches !== null && matches[1]) filename = matches[1].replace(/['"]/g, ''); >var linkelem = document.createElement('a'); try < var blob = new Blob([response], < type: 'application/octet-stream' >); if (typeof window.navigator.msSaveBlob !== 'undefined') < // IE workaround for "HTML7007: One or more blob URLs were revoked by closing the blob for which they were created. These URLs will no longer resolve as the data backing the URL has been freed." window.navigator.msSaveBlob(blob, filename); >else < var URL = window.URL || window.webkitURL; var downloadUrl = URL.createObjectURL(blob); if (filename) < // use HTML5 a[download] attribute to specify filename var a = document.createElement("a"); // safari doesn't support this yet if (typeof a.download === 'undefined') < window.location = downloadUrl; >else < a.href = downloadUrl; a.download = filename; document.body.appendChild(a); a.target = "_blank"; a.click(); >> else < window.location = downloadUrl; >> > catch (ex) < console.log(ex); >> >); 
4,767 8 8 gold badges 34 34 silver badges 45 45 bronze badges answered Jan 6, 2017 at 18:17 231 2 2 silver badges 2 2 bronze badges you are my HERO. Thank you :) Commented Mar 4, 2019 at 8:07 5 hours and about 30 other attributes added to .ajax(<>). and xhrFields fixed it. Thank you so much! Commented Jul 15, 2019 at 3:15

For those looking a more modern approach, you can use the fetch API . The following example shows how to download a PDF file. It is easily done with the following code.

fetch(url, < body: JSON.stringify(data), method: 'POST', headers: < 'Content-Type': 'application/json; charset=utf-8' >, >) .then(response => response.blob()) .then(response => < const blob = new Blob([response], ); const downloadUrl = URL.createObjectURL(blob); const a = document.createElement("a"); a.href = downloadUrl; a.download = "file.pdf"; document.body.appendChild(a); a.click(); >) 

I believe this approach to be much easier to understand than other XMLHttpRequest solutions. Also, it has a similar syntax to the jQuery approach, without the need to add any additional libraries.

Of course, I would advise checking to which browser you are developing, since this new approach won't work on IE. You can find the full browser compatibility list on the following [link][1].

Important: In this example I am sending a JSON request to a server listening on the given url . This url must be set, on my example I am assuming you know this part. Also, consider the headers needed for your request to work. Since I am sending a JSON, I must add the Content-Type header and set it to application/json; charset=utf-8 , as to let the server know the type of request it will receive.