从Electron应用程序打印

Print from an Electron application

本文关键字:打印 应用程序 Electron      更新时间:2023-09-26

我正试图从Electron应用程序中使用节点打印机,但一旦添加了使用打印机的行,应用程序就会崩溃。

控制台输出:

[1]    9860 segmentation fault (core dumped)  node_modules/electron-prebuilt/dist/electron.

这是我正在运行的应用程序:

var app = require('app');
var BrowserWindow = require('browser-window');
var printer = require('printer');
require('crash-reporter').start();
app.on('ready', function() {
  var mainWindow = new BrowserWindow({width: 800, height: 600});
  mainWindow.loadUrl('file://' + __dirname + '/app/index.html');
  mainWindow.openDevTools();
  printer.printDirect({data:"print from Node.JS buffer" // or simple String: "some text"
      , printer:'HP-Deskjet-F4400-series' // printer name, if missing then will print to default printer
      , type: 'TEXT' // type: RAW, TEXT, PDF, JPEG, .. depends on platform
      , success:function(jobID){
          console.log("sent to printer with ID: "+jobID);
      }
      , error:function(err){console.log(err);}
  });      
});

我是不是错过了什么?

我自己尝试了node打印机,成功地打印了一些胡言乱语的文本。

node-printer使用本机绑定,并根据文档:

本地Node模块由Electron支持,但由于Electron正在使用与官方Node不同的V8版本,您必须在构建时手动指定Electron标头的位置本机模块。

我想这就是你得到seg fault的原因。尝试根据文档中提到的电子头构建模块:

npm install --save-dev electron-rebuild
# Every time you run npm install, run this too
./node_modules/.bin/electron-rebuild
app.on('ready', () => {
  let win = new BrowserWindow({width: 800, height: 600, resizable: false})
  win.loadURL('file://' + __dirname + '/index.html')
  win.webContents.on('did-finish-load', () => {
    win.webContents.printToPDF({marginsType: 2, pageSize: "A3", landscape: false}, (error, data) => {
      if (error) throw error
      fs.writeFile('output.pdf', data, (error) => {
        //getTitle of Window
        console.log(win.webContents.getTitle())
        //Silent Print
        if (error) throw error
        console.log('Write PDF successfully.')
      })
    })
  })
})

否则,您也可以使用以下行

win.webContents.print({silent:true, printBackground:true})

node-printer模块中有C++代码。这意味着你必须使用与电子使用的节点相同的版本来编译它。这实际上是可行的,但相当复杂。

另一方面,Electron已经在其中打印了API:

https://electronjs.org/docs/api/web-contents#contentsprintoptions-回调

如果这个api还不够,并且您仍然想利用node-printer模块,请告诉我,我将用一个关于如何分叉和固定node-printer以使其与电子兼容的更长答案来编辑这个响应。