How to connect stream using pdfkit using node js

Prior to PDFkit 0.5 - they worked for me (creating pdf via pdfkit / printing via ipp for 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 PDFkit 0.5 - the method is outputdeprecated - but I can not find an example of using the new method pipewith my script. If I don’t use a browser, do I still need a module, for example blob-stream ?

+4
source share
1 answer

Since pdfkit PDFDocument is now a stream, you need 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 :

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();
+8
source

Source: https://habr.com/ru/post/1541353/


All Articles