3

I have a fetch request that returns an HTML doc

<!DOCTYPE html><html lang="en"><head>..../body></html>

The next thing I'm trying to do is pass it to an API that will let me download it as a PDF

fetch("data:application/pdf;base64,"+encoded_data...)

I saw that I can use window.btoa() to encode a string into base64. However I'm stuck trying to turn the HTML file into a string, to pass into btoa()

fetch("https://www.website.com/cap/people/streamPdf/1214192793"})
.then(resp => {return resp.text()})
.then(data => {
   //this is the HTML file
    var x = String(data)
    console.log(x)
    var base64 = window.btoa(x)
    // console.log(base64)
})

I'm getting this error:

Uncaught (in promise) DOMException: Failed to execute 'btoa' on 'Window': The string to be encoded contains characters outside of the Latin1 range.
    at <anonymous>:21:25

I'm assuming this is because what I'm passing btoa isn't a string?

Morgan Allen
  • 3,291
  • 8
  • 62
  • 86

2 Answers2

3

Replace the html content with a string and try encoding it with base64.

btoa() //base64 encoding
atob() //base64 decoding

zero86
  • 172
  • 9
  • yes, that is my question. what am I doing wrong? I thought I was converting it to a string – Morgan Allen Sep 13 '20 at 17:35
  • @Morgan Allen Please refer to this! https://stackoverflow.com/questions/23223718/failed-to-execute-btoa-on-window-the-string-to-be-encoded-contains-characte – zero86 Sep 13 '20 at 17:39
1

Does this answer your question?

fetch("https://example.com")
.then(response => {
    return response.text()  
})
.then(html => {
    return window.btoa(html)
})
.then(base64 => {
    return "data:text/html;base64," + base64
})
.then(result => {
    console.log(result)
})
Marco
  • 7,007
  • 2
  • 19
  • 49