Electron打印
需求及思路
需求中是要求一種是靜默打印,一種是預(yù)覽打印。兩者的思路是挨措,在頁面中觸發(fā)一個IPC,向Electron主線程中發(fā)送要打印的數(shù)據(jù)URL和要使用的樣式標(biāo)識崩溪。然后Electron主線程另開一個窗口浅役,傳入相關(guān)參數(shù),發(fā)起網(wǎng)絡(luò)請求獲得數(shù)據(jù)伶唯。如果是預(yù)覽打印觉既,則在網(wǎng)絡(luò)請求的回調(diào)函數(shù)中調(diào)用打印函數(shù),如果是靜默打印乳幸,則向主線程發(fā)消息瞪讼,要求靜默打印,主線程收到消息后粹断,執(zhí)行靜默打印函數(shù)符欠,所以:
預(yù)覽打印
據(jù)說Chrome中的打印預(yù)覽是Chromium自己寫的,所以Electron中的內(nèi)核并不包含這個打印預(yù)覽的模塊瓶埋,自己寫又不太現(xiàn)實希柿,Electron調(diào)用的是系統(tǒng)打印的接口,是不帶預(yù)覽的养筒,所以不得不拿那個要打印的頁作為預(yù)覽曾撤。
代碼
in .html
<button (click)="printSilent()">靜默</button>
<button (click)="printPreview()">預(yù)覽</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();
}