简体   繁体   中英

sapui5 encoded base64 string to pdf

I have a base64 string and I want to convert it to a PDF file. I am using the SAP UI5 framework. I already tried it with atob(), but the pdf does not open. Any suggestions how to do that? BR, ajsnub

Here is my coding:

onClick: function(oEvent) {
                var base64 = "JVBERi0xLjUNCi...." //shortend

                var sDecodedFile = window.atob(base64);
                var sFileName = "test.pdf"

                var saveData = (function() {
                    var a = document.createElement("a");
                    document.body.appendChild(a);
                    a.style = "display: none";

                    return function(data, fileName) {
                        var json = JSON.stringify(data),
                            blob = new Blob([json], {
                                type: "data:application/pdf;base64"
                            }),
                            url = window.URL.createObjectURL(blob);
                        a.href = url;
                        a.download = fileName;
                        a.click();
                        window.URL.revokeObjectURL(url);
                    };
                }());

                var data = sDecodedFile,
                    fileName = sFileName;

                saveData(data, fileName);

            }

Update with jsPDF:

var base64 = "JVBERi0xLjUNCi...." //shortend                    
var doc = new jsPDF();
                    var SampleData = 'data:application/pdf;base64,' + base64;
                    //doc.image(SampleData, 10, 10);
                    doc.save('test_document.pdf');

Use the 'download' property of an <a> tag Here the docu

The real benefit of a[download] will be when working with blob: URLs and filesystem: URLs URLs. It'll give users a way to download content created/modified within your app.

So set up your base64 blob in the href

Review this as well: How to download PDF automatically using js?

Use sap.ui.core.HTML control to wrap your <a> tag

Check this ...

$(document).ready(function () {

    var base64 = "VGhpcyBpcyB0ZXh0IGZvciBwZGYgZG9j" //shortend
    var sDecodedFile = window.atob(base64);
    var doc = new jsPDF();
    doc.text(20, 20, sDecodedFile);
    doc.addPage();
    doc.text(20, 20, 'Do you like that?');

// Output as Data URI
    var datat = doc.output('datauri');
    var fileName = 'test.pdf';
    var a = document.createElement("a");
    document.body.appendChild(a);
    a.style = "display: none";
    a.href = datat;
    a.download = fileName;
    a.click();
    window.URL.revokeObjectURL(datat);

}); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM