Open In App

Printing in ElectronJS

ElectronJS is an Open Source Framework used for building Cross-Platform native desktop applications using web technologies such as HTML, CSS, and JavaScript which are capable of running on Windows, macOS, and Linux operating systems. It combines the Chromium engine and NodeJS into a Single Runtime.

In certain desktop applications, developers would like to provide a feature wherein the user can download or print the contents from within the application. For example, in a banking application, the user would like to print his/her account statement being displayed on the screen. Electron, in addition to saving the contents as a PDF file, also provides a way by which we can directly print the contents using the BrowserWindow object and the webContents property. The webContents property provides us with certain Instance Events and methods by which we can either print the contents of the BrowserWindow Instance being displayed, print the contents of a remote URL or print a file from the local system. This tutorial will demonstrate how to print content in Electron.



We assume that you are familiar with the prerequisites as covered in the above-mentioned link. For Electron to work, node and npm need to be pre-installed in the system.

Example: We will start by building the basic Electron Application by following the given steps.



Printing in Electron: The BrowserWindow Instance and webContents Property are part of the Main Process. To import and use BrowserWindow in the Renderer Process, we will be using Electron remote module. For more details on the remote module, Refer this link.

To get the current BrowserWindow Instance in the Renderer Process, we can use some of the Static Methods provided by the BrowserWindow object.

index.html: Add the following snippet in that file.




<br><br>
   <button id="current">
    Print Current Content of Page
   </button>

index.js: Add the following snippet in that file.




const electron = require('electron')
// Importing BrowserWindow from Main
const BrowserWindow = electron.remote.BrowserWindow;
  
var current = document.getElementById('current'); 
var options = {
    silent: false,
    printBackground: true,
    color: false,
    margin: {
        marginType: 'printableArea'
    },
    landscape: false,
    pagesPerSheet: 1,
    collate: false,
    copies: 1,
    header: 'Header of the Page',
    footer: 'Footer of the Page'
}
  
current.addEventListener('click', (event) => {
    let win = BrowserWindow.getFocusedWindow();
    // let win = BrowserWindow.getAllWindows()[0];
  
    win.webContents.print(options, (success, failureReason) => {
        if (!success) console.log(failureReason);
  
        console.log('Print Initiated');
    });
});

Output:


Printable Page:

  • Approach 2: Print the contents of a remote URL or a file from the local System by loading the contents in a BrowserWindow Instance.

    In this case we have created a new BrowserWindow Instance and set the show property to false. Hence the newly created window will never be shown. We have used the win.loadURL(path) method to load the contents of the External URL in the BrowserWindow. The url path can be a remote address specified by http:// protocol or a path to a file in the local System specified by using the file:// protocol. This method returns a Promise and it is resolved when the page has finished loading and the did-finish-load Event of webContents property is Emitted. For more detailed Information, Refer this link.

    The did-finish-load Instance Event belongs to the webContents Property. It is emitted when the navigation is done and the page is completely loaded. This happens when the spinner of the page has stopped spinning, and the onload event has been dispatched. In case, this event emitter is not used and the webContents.print() method is called, the printed page will be a blank document since the content did not finish loading in the BrowserWindow.

    index.html: Add the following snippet in that file.




    <br><br>
      <button id="url">Print Google.com Homepage</button>
    
    

    index.js: Add the following snippet in that file.




    const electron = require('electron')
    // Importing BrowserWindow from Main
    const BrowserWindow = electron.remote.BrowserWindow;
      
    var url = document.getElementById('url');
    var options = {
        silent: false,
        printBackground: true,
        color: false,
        margin: {
            marginType: 'printableArea'
        },
        landscape: false,
        pagesPerSheet: 1,
        collate: false,
        copies: 1,
        header: 'Header of the Page',
        footer: 'Footer of the Page'
    }
      
    url.addEventListener('click', (event) => {
        // Defining a new BrowserWindow Instance
        let win = new BrowserWindow({
            show: false,
            webPreferences: {
                nodeIntegration: true
            }
        });
        win.loadURL('https://www.google.com/');
      
        win.webContents.on('did-finish-load', () => {
            win.webContents.print(options, (success, failureReason) => {
                if (!success) console.log(failureReason);
                console.log('Print Initiated');
            });
        });
    });
    
    

    Output:


  • Article Tags :