PrintService.ts 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. import { printRecordService } from './database/PrintRecordService'
  2. import { getMainWindow } from 'ee-core/electron/window'
  3. import { logger } from 'ee-core/log'
  4. import { BrowserWindow } from 'electron'
  5. import {Event} from '../utils/Event'
  6. import {PrintEvent} from "../event/PrintEvent";
  7. import {Channel} from "../channel/Channel";
  8. /**
  9. * 打印服务
  10. */
  11. class PrintService {
  12. constructor() {
  13. }
  14. _init() {
  15. Event.on(PrintEvent.PRINT_DATA, async (res) => {
  16. await this.printData(res)
  17. })
  18. }
  19. /**
  20. * 获取本地打印机列表
  21. */
  22. async listLocalPrinters(): Promise<Electron.PrinterInfo[]> {
  23. return getMainWindow().webContents.getPrintersAsync();
  24. }
  25. async printData(data: any) {
  26. getMainWindow().webContents.send(Channel.PRINT_START)
  27. const printWindow = new BrowserWindow({ show: false });
  28. const printData = `<html><body>${data.html}</body></html>`
  29. getMainWindow().webContents.send(Channel.PRINT_DATA, printData)
  30. await printWindow.loadURL(`data:text/html, ${printData}`);
  31. printWindow.webContents.on('did-finish-load', () => {
  32. getMainWindow().webContents.send(Channel.PRINT_PROGRESS)
  33. printWindow.webContents.print({
  34. silent: true,
  35. printBackground: true,
  36. deviceName: data.deviceName ,
  37. margins:data.margins||{
  38. marginType :'none'
  39. },
  40. landscape:data.landscape||false,
  41. copies:data.copies||1,
  42. dpi:data.dpi,
  43. header:data.header,
  44. footer:data.footer,
  45. pageSize:data.pageSize //A4,Legal | {height:}
  46. }, (success: boolean, failureReason: string) => {
  47. logger.info('打印结果:', success, failureReason)
  48. getMainWindow().webContents.send(Channel.PRINT_RESULT, {
  49. success,
  50. failureReason
  51. })
  52. printRecordService.add({
  53. printerName: data.deviceName,
  54. printHtml: data.html,
  55. printStatus: success ? 'success' : 'failure',
  56. failureReason: failureReason
  57. })
  58. printWindow.close();
  59. }); // 静默打印
  60. });
  61. }
  62. }
  63. PrintService.toString = () => '[class PrintService]'
  64. const printService = new PrintService()
  65. export {
  66. PrintService,
  67. printService
  68. }