Print from an Electron application

坚强是说给别人听的谎言 提交于 2019-12-02 19:20:34

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!