Base64 representing PDF to blob - JavaScript

后端 未结 2 466
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-25 15:10

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

相关标签:
2条回答
  • 2020-12-25 15:20

    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);
    
    0 讨论(0)
  • 2020-12-25 15:28

    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.

    0 讨论(0)
提交回复
热议问题