Base64 representing PDF to blob - JavaScript

46,182

Solution 1

This javascript converts a base64 string to a blob object:

// base64 string
var base64str = result.pdf;

// decode base64 string, remove space for IE compatibility
var binary = atob(base64str.replace(/\s/g, ''));
var len = binary.length;
var buffer = new ArrayBuffer(len);
var view = new Uint8Array(buffer);
for (var i = 0; i < len; i++) {
    view[i] = binary.charCodeAt(i);
}

// create the blob object with content-type "application/pdf"               
var blob = new Blob( [view], { type: "application/pdf" });
var url = URL.createObjectURL(blob);

Solution 2

You have to convert the base64 string back into the original binary data. Using atob is not sufficient, you'll have to run it through a loop and convert it to an array buffer - Convert base64 string to ArrayBuffer
Then use that to create the blob.

Share:
46,182
user3461486
Author by

user3461486

Updated on July 05, 2022

Comments

  • user3461486
    user3461486 almost 2 years

    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?