Search code examples
javascriptprintjs

Printing a Base64 file using Print.js


So I am trying to print a Base64 file but im not sure why it doesn't print the file.

function convertToBase64() {

var selectedFile = document.getElementById("inputFile").files;

if (selectedFile.length > 0) {

    var fileToLoad = selectedFile[0];

    var fileReader = new FileReader();
    var base64;

    fileReader.onload = function (fileLoadedEvent) {
        base64 = fileLoadedEvent.target.result;

        const pdfBlob = new Blob([base64], { type: "application/pdf" });
        const url = URL.createObjectURL(pdfBlob);
        printJS({
            printable: url,
            type: "pdf",
            base64: true
        });
    };
    fileReader.readAsDataURL(fileToLoad);
}

}

I pass it a pdf file that I select and convert it to Base64.Now I want to print the Base64 using Print.js but I can't make it work.


Solution

  • Your code isn't actually passing the base64 data to the print function, but instead, a URL.

    If you want to keep your current code, just remove the base64 flag from the print params.

    printJS({
      printable: url,
      type: 'pdf',
    });
    

    Otherwise, you could instead just pass the base64 var to the print function without creating the blog and url, the print library will handle that for you.

    Ex.:

    Assuming base64Data is a variable with valid base64 data.

    printJS({
      printable: base64Data,
      type: 'pdf',
      base64: true
    });