Downloading base64 PDF in Javascript / React
Trying to download a base64 PDF/File from an API request with one click?

Search for a command to run...
Trying to download a base64 PDF/File from an API request with one click?

No comments yet. Be the first to comment.
A guide to building a production-ready API with modular architecture, database integration using Prisma, automated API docs with Swagger & Docker.

We all come across chatbots when visiting various sites, while some of them operate behind real-human interaction, others are powered by AI. In this article, we'll walk through building a simple AI-powered chatbot using TensorFlow and JavaScript. The...

Running localhost on your mobile phone can be a valuable tool for developers and tech enthusiasts alike. With localhost, you can test and run applications and websites on your mobile device, without the need for an external server. This of course is ...

An explanation of the debounce function and how to use it in your React Application

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