Electron打印
2017-08-19 本文已影响0人
环零弦
Electron打印
需求及思路
需求中是要求一种是静默打印,一种是预览打印。两者的思路是,在页面中触发一个IPC,向Electron主线程中发送要打印的数据URL和要使用的样式标识。然后Electron主线程另开一个窗口,传入相关参数,发起网络请求获得数据。如果是预览打印,则在网络请求的回调函数中调用打印函数,如果是静默打印,则向主线程发消息,要求静默打印,主线程收到消息后,执行静默打印函数,所以:
预览打印
据说Chrome中的打印预览是Chromium自己写的,所以Electron中的内核并不包含这个打印预览的模块,自己写又不太现实,Electron调用的是系统打印的接口,是不带预览的,所以不得不拿那个要打印的页作为预览。
代码
in .html
<button (click)="printSilent()">静默</button>
<button (click)="printPreview()">预览</button>
in .ts
printSilent() {
this.electronService.send('print-silent', "http://localhost:3000/");
}
printPreview() {
this.electronService.send('print-preview', "http://localhost:3000/");
}
in main
ipcMain.on("print-preview", (event, arg) => {
winprintp = new BrowserWindow({width: 790, height: 800});
winprintp.loadURL(`file://${__dirname}/assets/updates/print-preview.html`);
winprintp.setMenu(null);
winprintp.webContents.on('did-finish-load', () => {
winprintp.webContents.send('request', arg);
});
});
ipcMain.on("print-silent", (event, arg) => {
winprints = new BrowserWindow({show: false});
winprints.loadURL(`file://${__dirname}/assets/updates/print-silent.html`);
winprints.webContents.on('did-finish-load', () => {
winprints.webContents.send('request', arg);
});
ipcMain.on("print", (event, arg) => {
winprints.webContents.print({silent: true, printBackground: true});
});
});
in print-slinet.html
const ipcRenderer = require('electron').ipcRenderer;
ipcRenderer.on('request', function (event, arg) {
doGet(arg);
});
let xmlHttp = null;
function callback() {
if (xmlHttp.readyState === 4 && xmlHttp.status === 200) {
let d = xmlHttp.responseText;
console.log(d);
ipcRenderer.send('print', '');
}
}
function doGet(url) {
xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", url, true);
xmlHttp.onreadystatechange = callback;
xmlHttp.send();
}
in print-preview.html
const ipcRenderer = require('electron').ipcRenderer;
ipcRenderer.on('request', function (event, arg) {
doGet(arg);
});
let xmlHttp = null;
function callback() {
if (xmlHttp.readyState === 4 && xmlHttp.status === 200) {
let d = xmlHttp.responseText;
console.log(d);
window.print();
}
}
function doGet(url) {
xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", url, true);
xmlHttp.onreadystatechange = callback;
xmlHttp.send();
}