Convert Blob data to Raw buffer in javascript or node

為{幸葍}努か 提交于 2020-12-29 04:13:23

问题


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.


回答1:


           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.




回答2:


Try:

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



回答3:


For me, it worked with the following:

const buffer=Buffer.from(blob,'binary');

So, this buffer can be stored in Google Cloud Storage and local disk with fs node package.

I used blob file, to send data from client to server through ddp protocol (Meteor), so, when this file arrives to server I convert it to buffer in order to store it.



来源:https://stackoverflow.com/questions/34158497/convert-blob-data-to-raw-buffer-in-javascript-or-node

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!