Skip to content

Instantly share code, notes, and snippets.

@mcfearsome
Created July 14, 2019 14:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mcfearsome/6a5f19c0095e689a29b24a793c706f3f to your computer and use it in GitHub Desktop.
Save mcfearsome/6a5f19c0095e689a29b24a793c706f3f to your computer and use it in GitHub Desktop.
Electron launch and print a hidden webview
import { ipcRenderer } from 'electron'
ipcRenderer.send('print', { device: 'printer name', width: 210 })
// imported from main/index.js
import { BrowserWindow, ipcMain } from 'electron'
const isDev = process.env.NODE_ENV === 'development'
const baseUrl = isDev
? 'http://localhost:9080#'
: `file://${__dirname}/index.html#`
ipcMain.on('print', (event, payload) => {
// multiple printers are in use so printer name is sent in as "device"
const { device, width } = payload
let win = new BrowserWindow({ width, height: 1000, show: isDev })
if (!isDev) win.once('ready-to-show', () => win.hide())
win.loadURL(`${baseUrl}/print?device=${device}`)
win.webContents.on('did-finish-load', () => {
win.webContents.print({ silent: true, deviceName: device }, (success) => {
win.close()
win = null
})
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment