Convert Blob data to Raw buffer in javascript or node

Kamaldeep Singh picture Kamaldeep Singh · Dec 8, 2015 · Viewed 19.7k times · Source

I am using a plugin jsPDF which generates PDF and saves it to local file system. Now in jsPDF.js, there is some piece of code which generates pdf data in blob format as:-

var blob = new Blob([array], {type: "application/pdf"});

and further saves the blob data to local file system. Now instead of saving I need to print the PDF using plugin node-printer.

Here is some sample code to do so

var fs = require('fs'),
var dataToPrinter;

fs.readFile('/home/ubuntu/test.pdf', function(err, data){
    dataToPrinter = data;
}

var printer = require("../lib");
printer.printDirect({
    data: dataToPrinter,
    printer:'Deskjet_3540',
    type: 'PDF',
    success: function(id) {
        console.log('printed with id ' + id);
    },
    error: function(err) {
        console.error('error on printing: ' + err);
    }
})

The fs.readFile() reads the PDF file and generates data in raw buffer format.

Now what I want is to convert the 'Blob' data into 'raw buffer' so that I can print the PDF.

Answer

Kamaldeep Singh picture Kamaldeep Singh · Dec 10, 2015
           var blob = new Blob([array], {type: "application/pdf"});

            var arrayBuffer, uint8Array;
            var fileReader = new FileReader();
            fileReader.onload = function() {
                arrayBuffer = this.result;
                uint8Array  = new Uint8Array(arrayBuffer);

                var printer = require("./js/controller/lib");
                printer.printDirect({
                    data: uint8Array,
                    printer:'Deskjet_3540',
                    type: 'PDF',
                    success: function(id) {
                        console.log('printed with id ' + id);
                    },
                    error: function(err) {
                        console.error('error on printing: ' + err);
                    }
                })
            };
            fileReader.readAsArrayBuffer(blob);

This is the final code which worked for me. The printer accepts uint8Array encoding format.