Base64 representing PDF to blob - JavaScript

Viewed 52102

I have a Base64 string representing a PDF file. I want to convert it to a file with the Blob object using javascript. After it's done i want to save the blob as a PDF file using FileSaver.js.

Here is my code:

var base64PDF = JVBERi0xLjQNCiW0t..; // This is a huge string.
var blob = new Blob([base64PDF], { type: 'application/pdf' });
saveAs(blob, "test.pdf");

This code doesn't work. It saves a test.pdf that says it can't open this pdf because there was en error in the decoding.

I've also tried to do this:

var base64PDF = JVBERi0xLjQNCiW0t..; // This is a huge string.
var decode = atob(screen.prp_wcfria_ExternalFile.pdfFile);
var blob = new Blob([decode], { type: 'application/pdf' });
saveAs(blob, "test.pdf");

This code also doesn't work. How do i do this?

4 Answers
const b64toUrl = async (base64Data) => {
  const r = await fetch(base64Data);
  const blob = await r.blob();
  return URL.createObjectURL(blob);
}

base64Data string should include the "data:application/pdf;base64,...." part.

Easiest way, use the Fetch API to convert base64 to blob.

here's the code...

    const pdfstr = await fetch(pdf);   \\pdf is the base64 string
    const blobFromFetch= await pdfstr.blob();

  
    var blob = new Blob([blobFromFetch], {type: "application/pdf"});
    
    const blobUrl = URL.createObjectURL(blob);
  

  window.open(blobUrl,"_blank");

hope it helps!

Related