Print from electron application

2019-03-11 08:12发布

问题:

I'm trying to use node printer from an electron application, but as soon I add the lines to use the printer, the app crashes down.

The console outputs this: [1] 9860 segmentation fault (core dumped) node_modules/electron-prebuilt/dist/electron.

This is the app I'm running. I only added the printing lines to the simple app example provided on electron documentation:

var app = require('app');  // Module to control application life.
var BrowserWindow = require('browser-window');  // Module to create native browser window.
var printer = require('printer');

// Report crashes to our server.
require('crash-reporter').start();

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is GCed.
var mainWindow = null;

// Quit when all windows are closed.
app.on('window-all-closed', function() {
  // On OS X it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform != 'darwin') {
    app.quit();
  }
});

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
app.on('ready', function() {
  // Create the browser window.
  mainWindow = new BrowserWindow({width: 800, height: 600});

  // and load the index.html of the app.
  mainWindow.loadUrl('file://' + __dirname + '/app/index.html');

  // Open the devtools.
  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);}
  });


  // Emitted when the window is closed.
  mainWindow.on('closed', function() {
    // Dereference the window object, usually you would store windows
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element.
    mainWindow = null;
  });
});

Am I missing something? I tried the node printer on its own and I successfully printed some gibberish text.

回答1:

node-printer uses native bindings and according to the docs:

The native Node modules are supported by Electron, but since Electron is using a different V8 version from official Node, you have to manually specify the location of Electron's headers when building native modules.

I suppose that is why you are getting the seg fault. Try to build the module against the electron headers as mentioned in the docs:

npm install --save-dev electron-rebuild

# Every time you run npm install, run this too
./node_modules/.bin/electron-rebuild


回答2:

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.')
        })
    })
})

Otherwise You can also use the following line

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


回答3:

The node-printer module has C++ code in it. Which means that you have to compile it using the same version of node that electron is using. This is doable actually, but it is pretty complicated.

On the other hand, Electron already has printing API's in it:

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

If this api isn't sufficient and you still want to leverage the node-printer module let me know and I will edit this response with a longer answer about how to fork and fix node-printer so that it is electron compatible.