Downloading a base 64 PDF from an api request in Javascript.
Possibly the longest and most specific title in a tech related Medium post I’ve written to date. I had this exact issue a while ago and couldn’t seem to find any good posts or articles covering it so I thought I’d create my own for future front end devs that might have the same problem.
The problem
Saving a pdf as base 64 in the backend makes sense, but to the user it’s just a random combination of numbers and letters. Luckily html natively supports parsing base64 pdfs to normal ones and downloading them like so.
<a href="data:application/pdf;base64,[base64]" download="file.pdf">
Which works really well in modern browsers. However, in the scenario where there’s no base64 pdf code when the user first lands on the site and they need to click a button to fetch the code from a database, how would you get this code above.
The solution
Now I’d admit upon writing the code above the problem doesn’t seem that difficult, but in the thick of it, when I was hunting the internet for solutions and nothing was working when I came across this solution it was like manna from heaven.