将 Blob 数据转换为 JavaScript 或节点中的原始缓冲区

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/34158497/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 17:19:55  来源:igfitidea点击:

Convert Blob data to Raw buffer in javascript or node

javascriptnode.jsprintingbufferjspdf

提问by Kamaldeep Singh

I am using a plugin jsPDFwhich 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:-

我正在使用插件jsPDF生成 PDF 并将其保存到本地文件系统。现在在 jsPDF.js 中,有一些代码可以生成 blob 格式的 pdf 数据,如下所示:-

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.

并进一步将 blob 数据保存到本地文件系统。现在我需要使用插件node-printer打印 PDF 而不是保存。

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.

fs.readFile()读取PDF文件,并生成原始缓冲区格式的数据。

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

现在我想要的是将“Blob”数据转换为“原始缓冲区”,以便我可以打印 PDF。

回答by Kamaldeep Singh

           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.

这是对我有用的最终代码。打印机接受 uint8Array 编码格式。

回答by Alexandr Lazarev

Try:

尝试:

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