Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/angular/26.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在Angular Electron中侦听从主进程到渲染器进程的事件_Javascript_Angular_Electron - Fatal编程技术网

Javascript 如何在Angular Electron中侦听从主进程到渲染器进程的事件

Javascript 如何在Angular Electron中侦听从主进程到渲染器进程的事件,javascript,angular,electron,Javascript,Angular,Electron,我要侦听从主进程触发的printPDF事件。 虽然我的主要目标是在electron中打印Div内容,所以我在stackoverflow()上得到了这个代码片段,但我不知道如何在渲染器进程中侦听来自主进程的事件。下面是我的代码: 我在我的electron.service.ts文件中尝试了以下代码,但不起作用: ipcRenderer.on("printPDF", (event, content) => { document.body.innerHTML = content

我要侦听从主进程触发的printPDF事件。 虽然我的主要目标是在electron中打印Div内容,所以我在stackoverflow()上得到了这个代码片段,但我不知道如何在渲染器进程中侦听来自主进程的事件。下面是我的代码:

我在我的electron.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;
}

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");
    })


}
 @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>");
  }

}
electron.service.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;
}

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");
    })


}
 @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>");
  }

}
print.component.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;
}

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");
    })


}
 @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>");
  }

}
@组件({
选择器:“应用程序硬件设置”,
templateUrl:“./hardware setup.component.html”,
样式URL:['./硬件设置.component.scss']
})
导出类HardwareSetupComponent实现OnInit{
构造函数(){}
ngOnInit(){}
onSendCommandToWorker(){
返回此.electronService.sendCommandToWorker(“你好”);
}
}
万一我的方法错了,我真的希望有一个更好的方法在电子表格中打印Div内容

链接到角电子

我所说的打印是指将文件发送到打印机,然后打印机再打印到纸张上


谢谢

假设您有一个打印为PDF的按钮。如果要打印组件的所有HTML内容,请按照以下步骤操作

print.component.html

<!-- Other HTML -->
<button  id='print-pdf' (click)="saveToPDF()">Save to PDF</button>
<!-- Other HTML -->
main.ts
文件中,我们获得通过打印组件发送的web内容,并使用electron的功能。printToPDF中有各种可用的选项,我在这里使用默认选项

main.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');
    });
}
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”事件将发送回打印组件