kanishka kumarasiri
kanishka kumarasiri

Reputation: 23

How to silently print a React component on the default printer using react-to-print with Electron

import { useReactToPrint } from 'react-to-print';  

const printsRef = useRef()

  const handlePrint = useReactToPrint({
    content: () => printsRef.current,
    pageStyle: `
    @page {
      size: auto; 
      width: 80mm; 
      height: 1000mm; 
      margin-top: 0cm; 
      margin-right: 0mm;
      margin-bottom: 0cm;
      margin-left: 0cm;
    }
    `
  })

In return function :

<table border={0} ref={printsRef}>
</table>

Suppose I'm using a button for the handlePrint function.

Upvotes: 0

Views: 1058

Answers (1)

Matthew Herbst
Matthew Herbst

Reputation: 32043

If you pass a custom function to the optional print options on useReactToPrint you will get access to the iframe which you can then do whatever you want with. Can't say I know how to call the printer directly from Electron, but this should get you started:

const handlePrint = useReactToPrint({
    content: () => printsRef.current,
    print: async (iframe: HTMLIframeElement) => {
        // react-to-print would normally call `window.print` on the iframe
        // Instead, by passing this function, now you can do whatever you
        // want with the iframe, something like:
        // https://www.electronjs.org/docs/latest/api/web-contents#contentsgetprintersasync

        // NOTE: treat this like pseudocode, I don't know Electron well
        const { webContents } = require('electron');
        const iframeWebContents = webContents.fromFrame(iframe)
        const printerList = await iframeWebContents.getPrintersAsync();
        const defaultPrinter = printerList.find(printer => printer.isDefault);
        iframeWebContents.print({ deviceName: defaultPrinter.name });
    },
});

Upvotes: 0

Related Questions