Downloading base64 PDF in Javascript / React
Trying to download a base64 PDF/File from an API request with one click?
I ran into this problem while trying to download a PDF from an API response and figured I'd create a post that solves this for myself and other Front-End developers.
The Problem
Files could be saved in the backend as base64 encoded strings, this is to ensure that the data remains intact without modification during transport. Base64 is commonly used in a number of applications. So how do we download a file sent from the Backend as base 64 as it's just a string usually in this format (data:application/pdf;base64,[base64]..)
The Solution
In a situation whereby the user isn't making any request to an endpoint, the base64 file could be downloaded just like so (using the typical HTML anchor tag):
<a href="data:application/pdf;base64,[base64]" download="file_name.pdf">
Otherwise, In a situation whereby the user has to fetch data from an endpoint and pass data onClick
, this can be done simply by creating a function that accepts the base64 encoded stringand creating the anchor
tag element with the file link as an href
attribute, adds a download
attribute and clicks on the created anchor
element.
let pdf = {
file: "data:application/pdf;base64,[base64]......",
file_name: "Purchase Invoice"
}
function downloadPDF(pdf) {
const pdfLink = `${pdf.file}`;
const anchorElement = document.createElement('a');
const fileName = `${pdf.file_name}.pdf`;
anchorElement.href = pdfLink;
anchorElement.download = fileName;
anchorElement.click();
}
I hope I'm able to help with this implementation, let me know in the comments.
Read more articles from me: blog.abdulqudus.com