how to convert byte array to pdf and download

13,056

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')
  });
Share:
13,056
texas697
Author by

texas697

Junior Web Developer

Updated on July 15, 2022

Comments

  • texas697
    texas697 almost 2 years

    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')
    
    • Admin
      Admin over 6 years
      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?
    • texas697
      texas697 over 6 years
      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
      texas697 over 6 years
    • texas697
      texas697 over 6 years
      is it a base64 response? That is what I assumed at first
    • Admin
      Admin over 6 years
      Ah Ok, the string base-64 encoded. Simply decode it via f.ex. via fetch/XMLHttpRequest