我想听听主流程触发的printPDF事件。 尽管我的主要目的是在电子中打印Div内容,所以我在stackoverflow(How to print a DIV in ElectronJS)上获得了此代码段,但我不知道如何在渲染器进程中侦听来自主进程的事件。下面是我的代码:
我已经在我的electronic.service.ts文件中尝试了以下代码,但是没有用:
ipcRenderer.on("printPDF", (event, content) => {
document.body.innerHTML = content;
ipcRenderer.send("readyToPrintPDF");
})
这是每个文件的代码段:
main.ts
个文件
import { app, BrowserWindow, screen, ipcMain, shell } from 'electron';
import * as path from 'path';
import * as url from 'url';
import * as os from 'os';
import * as fs from 'fs';
let workerWindow: Electron.BrowserWindow = undefined;
let win,serve;
serve = args.some(val => val === '--serve');
async function createWindow() {
const electronScreen = screen;
const size = electronScreen.getPrimaryDisplay().workAreaSize;
// Create the browser window.
win = new BrowserWindow({
x: 0,
y: 0,
width: size.width,
height: size.height,
webPreferences: {
nodeIntegration: true,
},
});
if (serve) {
require('electron-reload')(__dirname, {
electron: require(`${__dirname}/node_modules/electron`)
});
win.loadURL('http://localhost:4200');
} else {
win.loadURL(url.format({
pathname: path.join(__dirname, 'dist/index.html'),
protocol: 'file:',
slashes: true
}));
}
if (serve) {
win.webContents.openDevTools();
}
// Emitted when the window is closed.
win.on('closed', () => {
win = null;
});
workerWindow = new BrowserWindow();
workerWindow.loadURL('http://github.com');
// workerWindow.hide();
workerWindow.webContents.openDevTools();
workerWindow.on("closed", () => {
workerWindow = undefined;
});
// retransmit it to workerWindow
ipcMain.on("printPDF", (event: any, content: any) => {
console.log(content);
workerWindow.webContents.send("printPDF", content);
//Start Test Action Here
//End Test Action Here
});
// when worker window is ready
ipcMain.on("readyToPrintPDF", (event) => {
const pdfPath = path.join(os.tmpdir(), 'print.pdf');
// Use default printing options
workerWindow.webContents.printToPDF({}, function (error, data) {
if (error) throw error
fs.writeFile(pdfPath, data, function (error) {
if (error) {
throw error
}
shell.openItem(pdfPath)
event.sender.send('wrote-pdf', pdfPath)
})
})
});
};
try {
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow);
// Quit when all windows are closed.
app.on('window-all-closed', () => {
// On OS X it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('activate', () => {
// On OS X it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (win === null) {
createWindow();
}
});
} catch (e) {
// Catch Error
// throw e;
}
electron.service.ts
文件
import { Injectable } from '@angular/core';
// If you import a module but never use any of the imported values other than as TypeScript types,
// the resulting javascript file will look as if you never imported the module at all.
import { ipcRenderer, webFrame, remote, PrintOptions } from 'electron';
import * as childProcess from 'child_process';
import * as fs from 'fs';
import * as path from 'path';
import * as os from 'os';
const { BrowserWindow, dialog, shell } = remote;
@Injectable()
export class ElectronService {
ipcRenderer: typeof ipcRenderer;
webFrame: typeof webFrame;
remote: typeof remote;
childProcess: typeof childProcess;
fs: typeof fs;
path: typeof path;
os: typeof os;
constructor() {
// Conditional imports
if (this.isElectron()) {
this.ipcRenderer = window.require('electron').ipcRenderer;
this.webFrame = window.require('electron').webFrame;
this.remote = window.require('electron').remote;
this.childProcess = window.require('child_process');
this.fs = window.require('fs');
this.path = window.require('path');
this.os = window.require('os');
}
}
isElectron = () => {
return window && window.process && window.process.type;
}
sendCommandToWorker(content: any) {
if (this.isElectron()) {
this.ipcRenderer.send("printPDF", content);
}
}
//I Want to listen to this event fired from the main process.
ipcRenderer.on("printPDF", (event, content) => {
document.body.innerHTML = content;
ipcRenderer.send("readyToPrintPDF");
})
}
print.component.ts
文件
@Component({
selector: 'app-hardware-setup',
templateUrl: './hardware-setup.component.html',
styleUrls: ['./hardware-setup.component.scss']
})
export class HardwareSetupComponent implements OnInit {
constructor( ) { }
ngOnInit() {}
onSendCommandToWorker(){
return this.electronService.sendCommandToWorker("<h1> hello </h1>");
}
}
以防万一我的方法是错误的,我真的很欣赏在电子角中打印Div内容的更好方法。
链接到角电子https://github.com/maximegris/angular-electron
通过打印,我的意思是将文档发送到打印机,然后再打印到纸张上。
谢谢
答案 0 :(得分:1)
假设您有一个可打印为PDF的按钮。如果要打印组件的所有HTML内容,请遵循。
print.component.html
<!-- Other HTML -->
<button id='print-pdf' (click)="saveToPDF()">Save to PDF</button>
<!-- Other HTML -->
print.component.ts
const ipc = require('electron').ipcRenderer;
saveToPDF() {
ipc.on('write-pdf-complete', (event, path) => {
console.log('pdf writing complete');
})
}
// Add listener for Printing to PDF in ngOnInit()
ngOnInit(){
this.printPDFButton = document.getElementById('print-pdf');
this.printPDFButton.addEventListener('click', event => {
console.log('event listener added.');
ipc.send('print-to-pdf');
});
}
在main.ts
文件中,我们获取通过打印组件发送的Web内容,并使用电子的printToPDF函数。在printToPDF中可以使用各种选项,我在这里使用默认选项。
main.ts
import * as path from 'path';
import { app, BrowserWindow, screen } from 'electron';
const electron = require('electron')
const ipc = electron.ipcMain;
const shell = electron.shell;
ipc.on('print-to-pdf', event => {
console.log('called Print to PDF');
let date = new Date().toISOString();
var filePDFName = 'pdf_export' + date + '.pdf';
var DonwloadsPath = path.resolve(app.getPath("downloads"), (filePDFName));
const pdfPath = path.join(DonwloadsPath, '');
const win = BrowserWindow.fromWebContents(event.sender);
win.webContents.printToPDF({}).then(data => {
console.log('within electron\'s printpdf');
fs.writeFile(pdfPath, data, err => {
if (err) return console.log(err.message);
shell.openExternal('file://' + pdfPath);
event.sender.send('write-pdf-complete', pdfPath);
console.log('written pdf');
})
}).catch(error => {
console.log(error)
})
});
成功写入PDF后,“ write-pdf-complete”事件将发送回打印组件。