2016-09-28 114 views
1

我一直在尝试http://electron.atom.io一段时间。我遵循http://electron.atom.io/docs/tutorial/quick-start/,并且相对成功,我设法使用Bootstrap和Jquery创建了一个“应用程序”。如何从渲染器进程调用Electron API方法?

但是现在,我试图使用Electron API方法,但没有成功。

我创建了一个浏览器窗口,并在该窗口中添加了一个新的JS文件。在该文件中,我试图调用printToPDF方法在这里:http://electron.atom.io/docs/api/web-contents/#contentsprinttopdfoptions-callback

它只是不工作,并在控制台记录以下:

未捕获的ReferenceError:主窗口没有被定义

的码,就如同:

main.js

const electron = require('electron') 
const app = electron.app 
const BrowserWindow = electron.BrowserWindow 

let mainWindow 

function createWindow() { 
mainWindow = new BrowserWindow({width: 800, height: 600}) 
mainWindow.loadURL(`file://${__dirname}/index.html`) 
mainWindow.webContents.openDevTools() 

mainWindow.on('closed', function() { 
    mainWindow = null 
}) 
} 

app.on('ready', createWindow) 

app.on('window-all-closed', function() { 
if (process.platform !== 'darwin') { 
    app.quit() 
} 
}) 

app.on('activate', function() { 
if (mainWindow === null) { 
    createWindow() 
} 
}) 

我ndex.html

<!DOCTYPE html> 
<html> 
<head> 
<meta charset="UTF-8"> 
<title>Hello World!</title> 
<link rel="stylesheet" type="text/css" href="./css/bootstrap.min.css"> 
</head> 
<body> 
</body> 

<script>window.$ = window.jQuery = require('jquery');</script> 
<script type="text/javascript" src="./js/bootstrap.min.js"></script> 
<script> 
require('./app.js'); 
</script> 
</html> 

app.js

$(function() { 
mainWindow.webContents.printToPDF(); 
}); 
+0

您提供的HTML/JS你没有访问到'main.js'什么。你可以在'app.js'中创建一个函数来发出一个事件,然后在你的'main.js'中你可以监听这个事件,并在事件触发时调用'mainWindow.webContents.printToPDF();'。 –

回答

2

看看工控模块,ipcMainipcRenderer。 ipc模块允许你发送和接收main和render进程之间的同步和异步消息。

此处打印为ELECTRON API DEMOS应用程序的PDF示例。

渲染过程

const ipc = require('electron').ipcRenderer 

const printPDFBtn = document.getElementById('print-pdf') 

printPDFBtn.addEventListener('click', function (event) { 
    ipc.send('print-to-pdf') 
}) 

ipc.on('wrote-pdf', function (event, path) { 
    const message = `Wrote PDF to: ${path}` 
    document.getElementById('pdf-path').innerHTML = message 
}) 

主要工艺流程

const fs = require('fs') 
const os = require('os') 
const path = require('path') 
const electron = require('electron') 
const BrowserWindow = electron.BrowserWindow 
const ipc = electron.ipcMain 
const shell = electron.shell 

ipc.on('print-to-pdf', function (event) { 
    const pdfPath = path.join(os.tmpdir(), 'print.pdf') 
    const win = BrowserWindow.fromWebContents(event.sender) 
    // Use default printing options 
    win.webContents.printToPDF({}, function (error, data) { 
    if (error) throw error 
    fs.writeFile(pdfPath, data, function (error) { 
     if (error) { 
     throw error 
     } 
     shell.openExternal('file://' + pdfPath) 
     event.sender.send('wrote-pdf', pdfPath) 
    }) 
    }) 
}) 
+0

谢谢。这正是我想要的。我仍然试图找出这个'模块'模式。 – ricardolobo