简体   繁体   中英

how to convert byte array to pdf and download

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. 截图

And here is what I am doing.

 let blob = new Blob([response.data], { type: 'application/pdf' })
 FileSaver.saveAs(blob, 'foo.pdf')

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')
  });

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM