How to pipe a stream using pdfkit with node js

China☆狼群 提交于 2019-11-28 01:14:29

问题


Before PDFkit 0.5 - the following worked for me (generating a pdf via pdfkit/printing via ipp to CUPS):

var ipp = require("ipp");
var PDFDocument = require("pdfkit");

var doc = new PDFDocument;
doc.text("Hello World");

doc.output(function(pdf)){
    var printer = ipp.Printer("http://127.0.0.1:631/printers/1");
    var file = {
        "operation-attributes-tag":{
            "requesting-user-name": "User",
        "job-name": "Print Job",
        "document-format": "application/pdf"
        },
        data: new Buffer(pdf, "binary")
    };

    printer.execute("Print-Job", file, function (err, res) {
        console.log("Printed: "+res.statusCode);
    });
}

As of PDFkit 0.5 - the output method is deprecated - but I can't seem to find an example of using the new pipe method with my scenario. If I'm not using a browser, do I still need a module like blob-stream?


回答1:


Since pdfkit PDFDocument now is a stream, you have to buffer the data coming from the buffer:

var ipp = require("ipp");
var PDFDocument = require("pdfkit");

var doc = new PDFDocument;
doc.text("Hello World");

var buffers = [];
doc.on('data', buffers.push.bind(buffers));
doc.on('end', function () {
    var printer = ipp.Printer("http://127.0.0.1:631/printers/1");
    var file = {
        "operation-attributes-tag":{
            "requesting-user-name": "User",
        "job-name": "Print Job",
        "document-format": "application/pdf"
        },
        data: Buffer.concat(buffers)
    };

    printer.execute("Print-Job", file, function (err, res) {
        console.log("Printed: "+res.statusCode);
    });
});
doc.end();

Or you can use something like concat-stream module:

var ipp = require("ipp");
var PDFDocument = require("pdfkit");
var concat = require("concat-stream");

var doc = new PDFDocument;
doc.text("Hello World");

doc.pipe(concat(function (data) {
    var printer = ipp.Printer("http://127.0.0.1:631/printers/1");
    var file = {
        "operation-attributes-tag":{
            "requesting-user-name": "User",
        "job-name": "Print Job",
        "document-format": "application/pdf"
        },
        data: data
    };

    printer.execute("Print-Job", file, function (err, res) {
        console.log("Printed: "+res.statusCode);
    });
}));
doc.end();


来源:https://stackoverflow.com/questions/23771085/how-to-pipe-a-stream-using-pdfkit-with-node-js

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