Adam Parkin
Adam Parkin

Reputation: 18680

PDF from PUT in new window via Blob URI

I have an API endpoint which on a PUT serves a PDF with Content-Type "application/pdf" (you might ask "why a PUT and not a GET?" and the answer to that is "it’s complicated and I can’t change it").

I want to (client side), request that PDF and display the result in a window.open() call (ie display the PDF in a new window). Previously I used a data URI to do this, ie:

window.open('data:application/pdf,<the data payload from the response>');

but in Chrome 60 this no longer works (you can’t use a data URI in a window.open, see https://bugs.chromium.org/p/chromium/issues/detail?id=751135 ).

I have now changed the client side code to do a fetch() of the same endpoint, create a blob from the response, call URL.createObjectURL() on the blob to get a url, and pass that url to the window.open() call. Ie I have something like:

fetch('http://somedomain.com/rest/getMyPdf', {
    method: 'PUT', 
    ... some headers & the body ...
}).then(function(response) {
    return response.blob();
}).then(function(blob) {
    window.open(URL.createObjectURL(blob));
});

This works in Firefox (I get a PDF in a new window), but in Chrome you just see the raw ASCII of the PDF contents (ie %PDF-1.3.....).

I’m guessing this is some sort of content-type issue, ie if I could set the content type on the url, then Chrome would interpret the response as a PDF. Any suggestions on how to do that?

Upvotes: 1

Views: 433

Answers (1)

yms
yms

Reputation: 10418

Try

var data = response.arraybuffer();

Then create a Blob from there with the right content type

var = new Blob(data, 'application/pdf');

Upvotes: 1

Related Questions