How to pipe a stream using pdfkit with node js

2019-01-25 21:21发布

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条回答
孤傲高冷的网名
2楼-- · 2019-01-25 21:40

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();
查看更多
登录 后发表回答