将Blob数据转换为JavaScript或节点中的Raw缓冲区 [英] Convert Blob data to Raw buffer in javascript or node

查看:117
本文介绍了将Blob数据转换为JavaScript或节点中的Raw缓冲区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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"});

并进一步将Blob数据保存到本地文件系统.现在,除了保存之外,我还需要使用插件 node-printer 打印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.

这里有一些示例代码

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);
    }
})

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

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

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

推荐答案

           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);

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

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

这篇关于将Blob数据转换为JavaScript或节点中的Raw缓冲区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆