0

I'm trying to create a dynamic template for students registration form and I'm trying to print it,

the problem is while pressing the print button for the first time, it prints and everything works fine but after the second time it's not working until restarting the server itself although it shows the print window.

Here is main.js

$('#elemID').submit(function(e) {
    e.preventDefault();
    var x = $('#numberOfStudents').val();
    var output = [];
    for (var i = 1; i <= x; i++) {
        output.push(`<div><p> student number #0${i} </p></div>`);
    }
    var data = `
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css">
    </head>
    <body>

     <h4>Registation Form</h4>

     <h5>Full Name:</h5>
     <h5>gender:</h5>
     .
     .
     .
    </body>
    </html>
    `
    $.print(data);
})

print.ejs

<form id="elemID">
      <input type="number" id="numberOfStudents" placeholder="Number of students eg. 1....2....3">

      <button type="submit" id="printApplication">Print Application</button>

</form>

index.js (server side)

const {app, BrowserWindow, Menu } = require('electron')


// express
const express = require('express'),
      expApp = express(),
      server = require('http').createServer(expApp),
      db = require('./db/mongoose'),
      parentRoutes = require('./routes/parents'),
      studentRoutes = require('./routes/students'),
      port = process.env.PORT || 3000

let mainWindow

// load the url on listening
function onListening() {
    mainWindow.loadURL('http://localhost:3000')
}

// Function create a window
function createWindow() {

    // create a new window for main window
    mainWindow = new BrowserWindow({
        webPreferences: {
            nodeIntegration: true
        }
    })

    // express usage
    expApp.set('port', port)
    expApp.use(parentRoutes)
    expApp.use(studentRoutes)
    expApp.use(express.static('../semantic'))

    // listening to port
    server.listen(port, () => {console.log(`listening to port ${port}`);})
    server.on('listening', onListening)
    }

app.on('ready', createWindow);

I'm using jquery.print.js

Everything works fine on the first submit ut on the second time the print function doesn't work whatever printing or saving the file except if I restart the server.

I don't know what's wrong ?...please tell me if something not clear.

so please could you help me on this?

2 Answers2

0

You probably don't need the interprocess communication features; do you have any reason not to disable nodeIntegration ?

Nathan Hawks
  • 557
  • 4
  • 14
  • Thanks Nathan for your fast reply, I put nodeIntegration: true because I tried to require jquery on my ejs file and it triggers this error “Uncaught ReferenceError: require is not defined” but now when I disabled nodeIntegration still the same problem It prints one time only until I restart the server. – Yehia Fouad Dec 25 '19 at 06:15
  • Yeah on the client side you don't use `require` but rather old-fashioned ` – Nathan Hawks Dec 25 '19 at 06:26
  • Sorry Nathan for late reply, I tried a lot to find a solution and finally I got it with `ipcRenderer` on electron, I will post what I did now....Thanks a lot for your help – Yehia Fouad Dec 25 '19 at 16:35
  • Glad you got it! – Nathan Hawks Dec 25 '19 at 16:53
  • Thanks a lot Nathan...Appreciate it – Yehia Fouad Dec 25 '19 at 17:41
0

I got the solution of my problem with another way is use {ipcRenderer} = require('electron');.

I found this answer and it's so useful for me How to print a DIV in ElectronJS

What I did after pressing print button to send content to server side by a function sendDataToServer(data)

main.js

// create a function to send data to server.
function sendDataToServer(content) {
    ipcRenderer.send('printPDF', content);
}

$('#elemID').submit(function(e) {
    e.preventDefault();
    var x = $('#numberOfStudents').val();
    var output = [];
    for (var i = 1; i <= x; i++) {
        output.push(`<div><p> student number #0${i} </p></div>`);
    }
    var data = `
       <h4>Registation Form</h4>

     <h5>Full Name:</h5>
     <h5>gender:</h5>
     .
     .
     .
   `
    // call the function
    sendDataToServer(data);
})

index.js (server side)

const {app, BrowserWindow, Menu } = require('electron')


// express
const express = require('express'),
      expApp = express(),
      server = require('http').createServer(expApp),
      db = require('./db/mongoose'),
      parentRoutes = require('./routes/parents'),
      studentRoutes = require('./routes/students'),
      port = process.env.PORT || 3000

let mainWindow

// load the url on listening
function onListening() {
    mainWindow.loadURL('http://localhost:3000')
}

// Function create a window
function createWindow() {

    // create a new window for main window
    mainWindow = new BrowserWindow({
        webPreferences: {
            nodeIntegration: true
        }
    })
    //create hidden window 
    win = new BrowserWindow({
        show: false,
        webPreferences: {
            nodeIntegration: true
        }
    });
    // hide the hidden window on ready to show
    win.once('ready-to-show', () => win.hide())
    win.loadURL('file://' + views + '/printApp.html');

    // send data to hidden window
    ipcMain.on('printPDF', (event, content ) => {
        win.webContents.send('printPDF', content);
    });

    // create the pdf and printing options once hidden window finish rendering
    ipcMain.on('readyToPrintPDF', (e) => {
        const pdfPath = path.join(os.tmpdir(), 'print.pdf');

        // Use default printing options
        win.webContents.print({}, function (err, data) {
            if (err) throw err
            fs.writeFile(pdfPath, data, function (error) {
                if (error) throw error
                shell.openItem(pdfPath)
                event.sender.send('wrote-pdf', pdfPath)
            })
        })
    })

    // express usage
    expApp.set('port', port)
    expApp.use(parentRoutes)
    expApp.use(studentRoutes)
    expApp.use(express.static('../semantic'))

    // listening to port
    server.listen(port, () => {console.log(`listening to port ${port}`);})
    server.on('listening', onListening)
    }

    app.on('ready', createWindow);

printApp.html

<head>
    <link rel="stylesheet" href="./css/main.css">
</head>
<body>

    <script>
        const ipcRenderer = require('electron').ipcRenderer;

        ipcRenderer.on('printPDF', (e, content) =>{
            document.body.innerHTML = content;
            // I set a timeout to take time for rendering the page
            setTimeout(() => {
                ipcRenderer.send('readyToPrintPDF')

            }, 2000)
        })
    </script>
</body>