Write Base64(pdf) to File (pdf) in UI Builder

Is there a way to create a PDF from Base64 in UI Builder?
I tried to convert to bytes but the created PDF is a blank white page.

Hi @Ben

Make sure your base64 string is valid, the logic above should work

Regards, Vlad

My Base64 String is valid. But it still gives me only a white image or pdf.
I build a test page check it out: pagename: bktest and App ID A64366E6-49A2-CBBC-FF22-93A591AEF200

I see,

The server expects a file instance where the file type is specified

so to save a pdf file you need

  1. convert your base64 to bytes array
  2. create a Blob instance with application/pdf
  3. send it to the server

code of the custom code block:


function _base64ToArrayBuffer(data) {
    var binary_string = window.atob(data);
    var len = binary_string.length;
    var bytes = new Uint8Array(len);
    
    for (var i = 0; i < len; i++) {
        bytes[i] = binary_string.charCodeAt(i);
    }
    
    return bytes.buffer;
}

var pdfData = _base64ToArrayBuffer(base64);

return new Blob([pdfData], {type:'application/pdf'});

and make sure your base64 string doesn’t start with data:.. nor base64,...

Thanks for your detailed answer the code and UI Example. I appreciate it and will test and use this!

Thats a lot for this simple task. If we could use node modules in uibuillder-custom-code this one-liner should work:

const fs = require("fs-extra");
async function convertAndPrint(fileName, b64) {
fs.writeFile(`./assets/${fileName}`, b64, { encoding: "base64" })
}

Maybe this will work someday?

no, it won’t work because fs-extra is a nodejs module which works directly with FS (FileSystem of OS)

from the client, you do not have a direct access to the FS, that’s why we use API for transferring data from/to the server

Ok thanks for the clarification, now I get it! :sunglasses:

1 Like