2

I am trying to do a simple task of downloading a http response to a pdf. I am generating a pdf file but I am getting an error of "Failed to open PDF".

Here is what the response looks like. screenshot

And here is what I am doing.

 let blob = new Blob([response.data], { type: 'application/pdf' })
 FileSaver.saveAs(blob, 'foo.pdf')
texas697
  • 5,609
  • 16
  • 65
  • 131
  • 1
    The response there doesn't look like a PDF file (PDF is a text file and should start with `%PDF.`). Have you checked that XMLHttpRequest uses the correct URI? –  Aug 24 '17 at 17:00
  • I am not sure what it is. I am trying out different ways of displaying it. here is a fiddle i forked and added the response. Maybe this will help figure it out? – texas697 Aug 24 '17 at 17:02
  • http://jsfiddle.net/8vzz8sk9/ – texas697 Aug 24 '17 at 17:02
  • is it a base64 response? That is what I assumed at first – texas697 Aug 24 '17 at 17:04
  • Ah Ok, the string base-64 encoded. Simply decode it via f.ex. via fetch/XMLHttpRequest –  Aug 24 '17 at 17:04

2 Answers2

7

The string from the response seem to be Base-64 encoded (ref. fiddle). You can decode it using fetch() (or XMLHttpRequest() for older browsers):

fetch("data:application/pdf;base64," + response.data)
  .then(function(resp) {return resp.blob()})
  .then(function(blob) {
    FileSaver.saveAs(blob, 'foo.pdf')
  });
1

If anyone looking for solution with same problem, here is the nice article with cross browser support.

Snippet from article:

const binaryString = window.atob(fileResponseData);
const bytes = new Uint8Array(binaryString.length);
const mappedData = bytes.map((byte, i) => binaryString.charCodeAt(i));
const blob = new Blob([mappedData], { type: 'application/pdf' });
FileSaver.saveAs(blob, 'foo.pdf')
RobC
  • 22,977
  • 20
  • 73
  • 80
Aakash Goplani
  • 1,150
  • 1
  • 19
  • 36