Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

window.print() only works once #14705

Closed
owlstronaut opened this issue Sep 19, 2018 · 38 comments
Closed

window.print() only works once #14705

owlstronaut opened this issue Sep 19, 2018 · 38 comments

Comments

@owlstronaut
Copy link

  • Output of node_modules/.bin/electron --version: v3.0.0-beta.13
  • Operating System (Platform and Version): Windows 10
  • Output of node_modules/.bin/electron --version on last known working Electron version (if applicable): ?

Expected Behavior
window.print() should print the window on each subsequent call

Actual behavior
window.print() will work once, but fail from there on. This looks like a regression of #1532?
The device selection always comes up successfully. I've tried printing both to "Microsoft Print to PDF", which only gives you the "save location" dialog once, and my local printer, which will print once, then does nothing.

To Reproduce
Create a barebones electron app that can call window.print() as desired. Repository included.

clone: https://github.com/michaelsmitha/print-test

  • Run npm install
  • Run .\node_modules\electron\dist\electron.exe .
  • Clicking on the document will trigger a window.print()

Attempting to print the window after the first time fails.

@welcome
Copy link

welcome bot commented Sep 19, 2018

👋 Thanks for opening your first issue here! If you're reporting a 🐞 bug, please make sure you include steps to reproduce it. We get a lot of issues on this repo, so please be patient and we will get back to you as soon as we can.

To help make it easier for us to investigate your issue, please follow the contributing guidelines.

@maddhruv
Copy link

@michaelsmitha works fine for me every time
electron version - v2.0.10

@owlstronaut
Copy link
Author

Right, it doesn't in v3.0.0-beta.13

@maddhruv
Copy link

@MarshallOfSound are we seeing this in v3.x

@kevinsalerno
Copy link

kevinsalerno commented Oct 12, 2018

Same here. Yes this is a bug in v3 on Windows. Printer works fine on a fresh restart, very inconsistent with following calls.

Windows 10
"electron": "^3.0.0"

@ryansolida
Copy link

Anyone know of any workarounds for the moment on this bug?

@damianaiamad
Copy link

damianaiamad commented Oct 17, 2018

I'm seeing this bug in 3.0.4, Windows 10. Works ok on macOS.

Agree first print works after starting app. No printing thereafter.

Unfortunately a show stopper for us. Downgrading to 2.0...

@daikiuk
Copy link

daikiuk commented Oct 19, 2018

Total showstopper for us, must downgrade to 2.0

@damianaiamad
Copy link

Anyone know of any workarounds for the moment on this bug?

Closest I can suggest is to use webContents.printToPDF(), save to temp file, then shell.openExternal(). Then user has to print the PDF. Not a great workaround but kinda sorta gets you there...

@damianaiamad
Copy link

Retested with Electron 4.0.0-beta.4 / Windows 10: app now crashes after clicking Print button on print dialog.

@BeatriceThalo
Copy link

BeatriceThalo commented Oct 25, 2018

I'm on electron 1.8.8, here is a bit of off-topic rambling, which hopefully would spark some ideas as to what the cause may or may not be.

Before learning about ipc, I had some main-side print code:
client.ts

document.body.addEventListener('my-doc-rendered', (e: CustomEvent) => {
  window.open('', '_self'); // Call custom handler to print outside of angular, synchronous
  window.history.back();
}, {once: true});

electron.js

brWin.webContents.on('new-window', (event, urlParam, frameName) => {
  if (frameName === '_self') {
    event.preventDefault();
    win.webContents.print(); // synchronous (?)
  }
});

The actual behavior was happily blocking and synchronous for either a Cancel or Print choice in the print dialog. Windows and Ubuntu.

Then I learned about ipc and refactored to use renderer-side code:
client.ts

document.body.addEventListener('my-doc-rendered', (e: CustomEvent) => {
  window.print(); // asynchronous, w3schools says no arguments or return value
  window.close();
}, {once: true});

The observed behavior on Windows 10 is that the printDialog opens, then (likely before or) immediately after the user choice is made, the close method is executed, then (I imagine the blackbox as) printToPrinter or printToFile method is called, and creates a print job as seen in the printer's queue momentarily or does save a pdf file, but opening the pdf says something along the lines that it is empty or wrong, and the physical printer never spits out any paper.

In my attempts to refactor with the correct synchronicity, I went back to the electron way still on the renderer-side,
client.ts

document.body.addEventListener('my-doc-rendered', (e: CustomEvent) => {
  window.require('electron').remote.getCurrentWebContents().print(); // asynchronous
  window.close();
}, {once: true});

Back on Ubuntu 18.04, the browser window closes before the print dialog is ever seen. Not sure if my event chain made it seem synchronous before, or the non-remote method is different than the remote one.

Utilizing the callback,
client.ts

document.body.addEventListener('my-doc-rendered', (e: CustomEvent) => {
  window.require('electron').remote.getCurrentWebContents().print({}, (success: boolean) => { // my linter requires types and arrow syntax, idk if it matters
    console.log('success?', success) // no semicolon, idk if it matters
    window.close();
  });
  console.log('after print call line'); // shows in console behind open print dialog
}, {once: true});

The print dialog opened, [not sure /] I chose Cancel or Print to file maybe, the dialog closed, the window stayed open [/], and my entire machine froze, needing to be forcibly shut down. I was also running Slack in a Firefox tab at the time. I am on wifi and have about 10 network printers that do sometimes take a while to appear in the print dialog's device list.

With no Slack tab open, this works as expected when the Print choice is made, but the callback does not execute if the Cancel choice is made. So if that is intended, I recommend changing the webContents documentation to refer to it as a successCallback instead of a callback with a success/error boolean argument.

I also noticed that for example, Paint, on Windows 10, if you open two pngs, there can be two print dialogs open at the same time; never a problem on Ubunutu. But on Windows 10, if I spawn 2 browser windows which open printDialogs at the same time, only 1 dialog opens.

@brenca brenca moved this from Needs Review to Active in 3.0.x / 3.1.x Oct 25, 2018
@brenca brenca self-assigned this Oct 25, 2018
@brenca brenca moved this from Active to PR in Flight in 3.0.x / 3.1.x Oct 25, 2018
@brenca brenca moved this from PR in Flight to Fixed for Next Release in 3.0.x / 3.1.x Oct 29, 2018
@brenca brenca closed this as completed Oct 29, 2018
@lubo08
Copy link

lubo08 commented Jun 26, 2019

electron 5.0.5 again this bug is there in 3.1.8 or 4.X.X wasn't

@paulbennet
Copy link

paulbennet commented Jul 18, 2019

Also happening in electron 5.0.7 .. Fyi

To add. For my case, If I click Cancel on OS print dialog no other DOM events work after that. It was weird !

OS: macOS Mojave


Can it be the above PR was missed to be merged in 5.x.x versions ?! @brenca

@jainprashul
Copy link

Happening in electron 5.0.8

@mystaroll
Copy link

Happening in electron 6.0.0

@aneesijaz
Copy link

It's also in electron 5.0.6 👎

@paulbennet
Copy link

I guess we should open a new issue for this instead of commenting on an year old conversation ?!

@purocean
Copy link

6.0.0 too

@Jaifroid
Copy link

After issuing window.print() inside an electron app, the app crashes after user has chosen "print" in the dialog box. It sometimes also crashes after user chooses Cancel. Windows 10.

@vkiranmaniya
Copy link

vkiranmaniya commented Aug 15, 2019

Application is crashing after print or save as pdf in v6.0.1 too. have you found any solution?
Here is the crash log https://drive.google.com/file/d/1hh9pwGqhY_uDWhU2xfM5ZoBOU-5mEQ9L/view?usp=sharing

@mystaroll
Copy link

Could we just open a new issue instead??

@courageDeveloper
Copy link

Was previously using electron version 6 and my processes crashed immediately after printing. I had to downgrade to electron 2.0.2. One thing i noticed is that in electron 2.0.2, i had to !-- Insert this line above script imports -->

<script>if (typeof module === 'object') {window.module = module; module = undefined;}</script>

and also

<script>if (window.module) module = window.module;</script>

for most cases involving using Jquery scripts or Javascript. I thought about what if in Version 6 adding those scripts above could probably stop the process from crashing. You can try it out before downgrading, as for me i have a projects to deliver so i will just stick with my downgraded version as it works fine, at least for now and hopefully through deployment.

@TristonJ
Copy link

TristonJ commented Oct 18, 2019

This is a pretty old issue, but I am running into it on electron 7.0.0-beta.7 (Linux) and I am unable to execute window.print() more than once.

I have a workaround that appears to function in my case. You can spawn a new hidden BrowserWindow, load the HTML / CSS to be printed, and execute window.print() on that window. For example:

const printRawHtml = html => {
  const win = new BrowserWindow({ show: false });
  win.loadURL(`data:text/html;charset=UTF-8,${
    encodeURIComponent(`<html><body>${html}</body></html>`)
  }`);
  win.webContents.on('did-finish-load', () => {
    win.webContents.executeJavaScript(
      'window.print(); setTimeout(() => window.close());',
    );
  });
};

This of course only works if you are easily able to retrieve the necessary css/html from the page you would like to be printed. This was only tested on Ubuntu 19.04.

@DoYourUX
Copy link

This is still an issue in 7.0.0

@barbalex
Copy link

Yep, I can reproduce this in 7.0.0 on Windows

@avivsalman
Copy link

Any updates for this bug? I am in production and it's still in 7.0.0 on windows...

@InfiniteLukeOne
Copy link

InfiniteLukeOne commented Nov 14, 2019

Having this issue in electron v7.1.1 on Windows 7. Printer selection window is displayed after the first try, but printing only works the first time.

Steps to reproduce like in original Post with a npm install electron@latest before starting.

@m-zig
Copy link

m-zig commented Dec 2, 2019

Still an issue in electron v7.1.2 on Windows 10. Same behavior as described by @InfiniteLukeOne

@InfiniteLukeOne
Copy link

Still an issue in electron v7.1.2 on Windows 10. Same behavior as described by @InfiniteLukeOne

Take a look at #21195. There's a workaround in the comments which worked for me.

@celodauane
Copy link

I am facing exactly the same issue. The only workaround that worked for me was downgrading to electron version 3.

@peacegroup
Copy link

Same here. Yes this is a bug in v3 on Windows. Printer works fine on a fresh restart, very inconsistent with following calls.

Windows 10
"electron": "^3.0.0"

Ubuntu 18 experiences the same issue

@Suroor-Ahmmad
Copy link

Is this issue resolved? I'm facing same issue in Electron 10.1.0

@karlitos
Copy link

karlitos commented Sep 4, 2020

I face the same issue in Electron 9.1.2. on MacOs with the printToPDF method

@patrickrobbins
Copy link

patrickrobbins commented Sep 4, 2020 via email

@Jaifroid
Copy link

Jaifroid commented Sep 4, 2020

It was solved for me in Electron 9.0.5 when I last implemented this in an Electron version of the WikiMed app. There I can print as many times as I like without a crash (just tested the same app again). I hope they haven't re-introduced the bug since 9.0.5.

@karlitos
Copy link

It was solved for me in Electron 9.0.5 when I last implemented this in an Electron version of the WikiMed app. There I can print as many times as I like without a crash (just tested the same app again). I hope they haven't re-introduced the bug since 9.0.5.

I just tried with electron 9.0.5. and I was able to print multiple times to PDF without any problems.

@Suroor-Ahmmad
Copy link

Can someone check on Electron 10.1.0, I'm facing similar kind of issue, opened separate issue and it's tagged as bug #25327

@mad1009
Copy link

mad1009 commented Mar 3, 2023

A work around for previous versions, based On @TristonJ answer

  // Create a new window to handle printing
  const printWin = new BrowserWindow({ show: false });
  // Load current window url
  printWin.loadURL(BrowserWindow.getFocusedWindow().webContents.getURL());
  // Make sure the content fully loaded
  printWin.webContents.on('did-finish-load', () => {
      printWin.on("close",()=>{
        console.log("print window closed")
      })
      // Handle printing logic and notify the mainWindow
      printWin.webContents.print(printingOptions,(success, err) => {
          if(success){
            mainWindow.webContents.send("print:success")
            printWin.close()
          }else{
            mainWindow.webContents.send("print:failed",{error:err})
            printWin.close()
          }
          console.log('err :>> ', err);
        });
  });

When printing on the same window, mainWindow.print() will work only one time, and the callback will always return a success value.
To avoid this bug, before printing always create a hidden window, load the current url, and print.
Note that in the callback function the print window always notify the main window about the print status and close the print window to avoid memory leaks.
Note: When printing an HTML page make sure to use @media print{...} and other css tools to controle your printing view

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
No open projects
3.0.x / 3.1.x
Fixed (3.0.7)
Development

No branches or pull requests