使用Node.js在cups上执行打印操作

7

我希望能够通过Node.js的http请求来打印文档。是否有一种方法可以使用Node.js发送打印作业并查询CUPS服务器?在探索过程中,我发现了这个项目,它是唯一/正确的方法吗?


https://www.npmjs.com/search?q=cups - robertklep
2个回答

4

您可以使用shell来完成这个任务。我之前建立了一个项目,需要从Instagram读取特定的标签,并使用树莓派和照片打印机打印上传到该标签下的照片。

var fs = require('fs'),
    exec = require('child_process').exec;

exec("lp /path/to/somepic.jpg");

// get printer jobs
exec("lpq",function (error, stdout, stderr) {
    console.log('stdout: ' + stdout);
    console.log('stderr: ' + stderr);

    if (error !== null) {
      console.log('exec error: ' + error);
    }
});

lp /path/to/somepic.jpg 命令将 /path/to/somepic.jpg 发送到默认打印机。 lpq 命令显示打印队列。为了更好的使用,请阅读 CUPS 文档。


-1
以下代码片段似乎很有用。由于我已不再处理此问题,因此未尝试过它!但它可能对其他人有所帮助。原始来源:https://gist.github.com/vodolaz095/5325917
var ipp = require('ipp'); //get it from there - https://npmjs.org/package/ipp - $npm install ipp
var request = require('request'); //get it from there - https://npmjs.org/package/request - $npm install request
var fs = require('fs');

function getPrinterUrls(callback) {
    var CUPSurl = 'http://localhost:631/printers';//todo - change of you have CUPS running on other host
    request(CUPSurl, function (error, response, body) {
        if (!error && response.statusCode == 200) {
            var printersMatches = body.match(/<TR><TD><A HREF="\/printers\/([a-zA-Z0-9-^"]+)">/gm);//i know, this is terrible, sorry(
            var printersUrls = [];
            var i;
            if (printersMatches) {
                for (i = 0; i < printersMatches.length; i++) {
                    var a = (/"\/printers\/([a-zA-Z0-9-^"]+)"/).exec(printersMatches[i]);
                    if (a) {
                        printersUrls.push(CUPSurl + '/' + a[1]);
                    }
                }
            }
        }
        callback(error, printersUrls);
    });
};

function doPrintOnSelectedPrinter(printer, bufferToBePrinted, callback) {
    printer.execute("Get-Printer-Attributes", null, function(err, printerStatus){
        if(printerStatus['printer-attributes-tag']['printer-state']=='idle'){
            //printer ready to work
//*/
    printer.execute("Print-Job",
        {
            "operation-attributes-tag":{
                "requesting-user-name":"nap",
                "job-name":"testing"
            },
            "job-attributes-tag":{},
            data:bufferToBePrinted
        },
        function (err, res) {
            if (res.statusCode == 'successful-ok') {
                var jobUri = res['job-attributes-tag']['job-uri'];
                var tries = 0;
                var t = setInterval(function () {
                    printer.execute("Get-Job-Attributes",
                        {"operation-attributes-tag":{'job-uri':jobUri}},
                        function (err2, job) {
//                            console.log(job);
                            if (err2) throw err2;
                            tries++;
                            if (job && job["job-attributes-tag"]["job-state"] == 'completed') {
                                clearInterval(t);
//                                console.log('Testins if job is ready. Try N '+tries);
                                callback(null, job);//job is succesefully printed!
                            }
                            if (tries > 50) {//todo - change it to what you need!
                                clearInterval(t);
                                printer.execute("Cancel-Job", {
                                    "operation-attributes-tag":{
                                        //"job-uri":jobUri,  //uncomment this
//*/
                                        "printer-uri":printer.uri, //or uncomment this two lines - one of variants should work!!!
                                        "job-id":job["job-attributes-tag"]["job-id"]
//*/
                                    }
                                }, function (err, res) {
                                    if (err) throw err;
                                    console.log('Job with id '+job["job-attributes-tag"]["job-id"]+'is being canceled');
                                });

                                callback(new Error('Job is canceled - too many tries and job is not printed!'), null);

                            }
                        });
                }, 2000);
            } else {
                callback(new Error('Error sending job to printer!'), null);
            }
        });
//*/
        } else {
            callback(new Error('Printer '+printerStatus['printer-attributes-tag']['printer-name']+' is not ready!'),null);
        }
    });
}

function doPrintOnAllPrinters(data, callback) {
    var b = new Buffer(data, 'binary');
    getPrinterUrls(function (err, printers) {
        if (err) throw err;
        if (printers) {
            for (var i = 0; i < printers.length; i++) {
                var printer = ipp.Printer(printers[i]);
                doPrintOnSelectedPrinter(printer, b, callback);
            }
        } else {
            throw new Error('Unable to find printer. Do you have printer installed and accessible via CUPS?');
        }
    });
}

/*
 Example of usage
 */




fs.readFile('package.json', function (err, data) {
    doPrintOnAllPrinters(data, function (err, job) {
            if (err) {
                console.error('Error printing');
                console.error(err);
            } else {
                console.log('Printed. Job parameters are: ');
                console.log(job);
            }
        }
    );
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接