簡體   English   中英

從 Electron 應用程序打印

[英]Print from an Electron application

我正在嘗試從 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-printer使用本機綁定並根據文檔

Electron 支持原生 Node 模塊,但由於 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-callback

如果這個 api 不夠用,而你仍然想利用node-printer模塊,請告訴我,我將編輯這個響應,並提供關於如何分叉和修復node-printer以使其與電子兼容的更長答案。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM