Categories
JavaScript Answers

How to save base64 string as PDF at client side with JavaScript?

Spread the love

Sometimes, we want to save base64 string as PDF at client side with JavaScript.

In this article, we’ll look at how to save base64 string as PDF at client side with JavaScript.

How to save base64 string as PDF at client side with JavaScript?

To save base64 string as PDF at client side with JavaScript, we create a link.

For instance, we write

const downloadPDF = (pdf) => {
  const linkSource = `data:application/pdf;base64,${pdf}`;
  const downloadLink = document.createElement("a");
  const fileName = "abc.pdf";
  downloadLink.href = linkSource;
  downloadLink.download = fileName;
  downloadLink.click();
};

to define the downloadPDF function.

In it, we create a link with createElement.

Then we set its href property to the path with the PDF.

Next, we set the download property to the name of the downloaded file.

Then we call click to download the file.

Conclusion

To save base64 string as PDF at client side with JavaScript, we create a link.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *