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

[Bug]: Silent print was incorrect paper layout with webContents.print, but layout was correct when I use print dailog #39179

Closed
3 tasks done
tyhour opened this issue Jul 21, 2023 · 24 comments · Fixed by #41811
Assignees
Labels

Comments

@tyhour
Copy link

tyhour commented Jul 21, 2023

Preflight Checklist

Electron Version

25.3.1

What operating system are you using?

Windows

Operating System Version

Window 10 Pro Version 10.0.19045 Build 19045

What arch are you using?

x64

Last Known Working Electron version

25.3.1

Expected Behavior

This preview image I was use with dialog print. It shows exactly width and height that response from my URL. But I want to use with silent print.
image

Here is my code

ipcMain.handle('printComponent', async (_, url, printer_name, copies) => {
    let win = new BrowserWindow({
      show: false,
    });
    win.loadURL(url);
    let _printer = printer_name;
    let list = await win.webContents.getPrintersAsync();
    let check = list.filter((r) => r.name === _printer);
    if (check.length === 0) {
      check = list.filter((r) => r.isDefault);
      if (check.length > 0) {
        _printer = check[0].name;
      }
    }

    win.webContents.on('did-finish-load', () => {
      const printOptions: WebContentsPrintOptions = {
        deviceName: _printer,
        silent: false,
        margins: {
          marginType: 'default',
        },
        landscape: false,
        pagesPerSheet: 1,
        collate: false,
        copies,
      };
      win.webContents.print(printOptions, (success, failureReason) => {
        console.log('Print Initiated in Main...');
        if (!success) console.log(failureReason);
        // win.close();
        mainWindow?.focus();
      });
    });
  });

Actual Behavior

This preview image I was use with silent print. It shows too small that response from my URL.
image

Here is my code

ipcMain.handle('printComponent', async (_, url, printer_name, copies) => {
    let win = new BrowserWindow({
      show: false,
    });
    win.loadURL(url);
    let _printer = printer_name;
    let list = await win.webContents.getPrintersAsync();
    let check = list.filter((r) => r.name === _printer);
    if (check.length === 0) {
      check = list.filter((r) => r.isDefault);
      if (check.length > 0) {
        _printer = check[0].name;
      }
    }

    win.webContents.on('did-finish-load', () => {
      const printOptions: WebContentsPrintOptions = {
        deviceName: _printer,
        silent: true,
        margins: {
          marginType: 'default',
        },
        landscape: false,
        pagesPerSheet: 1,
        collate: false,
        copies,
      };
      win.webContents.print(printOptions, (success, failureReason) => {
        console.log('Print Initiated in Main...');
        if (!success) console.log(failureReason);
        // win.close();
        mainWindow?.focus();
      });
    });
  });

Testcase Gist URL

https://gist.github.com/053de2471f74277e60fb908aaa3685ff

Additional Information

No response

@tyhour
Copy link
Author

tyhour commented Jul 21, 2023

Everything work fine with "electron": "^24.6.4" for layout paper printing but I want to upgrade with new version and now I stuck on that problem. Thanks for help

@Hedwig188
Copy link

@codebytere Is this broken by the fix #39095?

@Hedwig188
Copy link

Any update with this issue? It also prevents us from upgrading to v25 and we haven't figured out a way to work around it.

@mgalla10
Copy link

mgalla10 commented Aug 2, 2023

If it helps, you can use this gist to easily reproduce the issue: https://gist.github.com/053de2471f74277e60fb908aaa3685ff. Just click Print, save the PDF to any location, and then view it and see how tiny the printed contents are.

@firsttabz
Copy link

@tyhour i have the same issue with electron@24.6.4 in silent mode, did you know how to solve it?

@Hedwig188
Copy link

Hedwig188 commented Aug 18, 2023

Setting the dpi:{ horizontal: 600, vertical: 600 } on the printOptions can workaround the issue.

@acutus
Copy link

acutus commented Sep 13, 2023

Ran into this as well when trying to upgrade to 25.x (and 26.x). I was able to adjust the output size with the mentioned dpi-setting, but layout still differs from 24.x or non-silent printing. Had to downgrade back to 24.x because of this. E.g. 24.8.3 still works fine with silent printing.

@lmt20
Copy link

lmt20 commented Oct 25, 2023

It seems this error still exists until the latest version 27.0.2.

The print function with option { silent: true } still works well toward version 24.8.8, and started having errors on version 25.0.0, this function starts working again in version 25.3.1 after this fix #39095 by @codebytere but make another error that causing prints to be very tiny.

Has anyone solved this problem other than the trick above?

Setting the dpi:{ horizontal: 600, vertical: 600 } on the printOptions can workaround the issue.

@testing4teks
Copy link

testing4teks commented Oct 30, 2023

Is there any update on this?

I'm using Zebra Printer ZD 230 with 4inch X 6inch roll.

How to calculate the dpi?

With silent: true in print option, is causing prints to be very tiny.

I'm on electron 26.2.1

@Hedwig188
Copy link

My current workaround for windows is to utilize PrinterResolution class get the printer resolution and pass the dpi to the printer to print. I've noticed some printer drivers(Canon generic printer driver) could return dpi values <=0. You'd need to filter them out and only pass the positive one to webContent.print. Otherwise, you could encounter this issue.

@Sebastien-Lampazona
Copy link

Sebastien-Lampazona commented Nov 9, 2023

I have exactly the same issue, and the 600 dpi workaround not working for me.
I had try to use an HTML page and render an with @page css options ... but not better ...

@aortmannm
Copy link

My current workaround for windows is to utilize PrinterResolution class get the printer resolution and pass the dpi to the printer to print. I've noticed some printer drivers(Canon generic printer driver) could return dpi values <=0. You'd need to filter them out and only pass the positive one to webContent.print. Otherwise, you could encounter this issue.

But then you need to switch to C# Code or?

The webContents.gerPrintersAsync() function didn't have the necessary DPI information right?

Have the same problem with 27.1.0

@Hedwig188
Copy link

My current workaround for windows is to utilize PrinterResolution class get the printer resolution and pass the dpi to the printer to print. I've noticed some printer drivers(Canon generic printer driver) could return dpi values <=0. You'd need to filter them out and only pass the positive one to webContent.print. Otherwise, you could encounter this issue.

But then you need to switch to C# Code or?

The webContents.gerPrintersAsync() function didn't have the necessary DPI information right?

Have the same problem with 27.1.0

Yes, I switched to C# to get the printer resolution and sent back to Electron's webContents.print() function.

@conteit
Copy link

conteit commented Dec 1, 2023

I have the same issue also on Electron 28.x.

A thing I was able to discover is that, on Windows, pageSize is interpreted in the wrong way. To be able to print at full page I had to multiply by 10 the width and heights in microns, by means of the pageSize parameter.
Instead of doing webContents.print({silent: true, pageSize: "A4"}, callback), I invoked webContents.print({silent: true, pageSize: {width: 2100000, height: 2970000}}, callback).

By means of that, the content is still printed small, but moves to the top-left corner and the print is able to span to the full page. To get to a normal printing size I can set dpi: {horizontal: 544, vertical: 544} or, alternatively, apply a CSS zoom: 750% on the page content, but that is not the right thing to do. Apart from the insane magnitude of the parameters, AFAIK increasing dpi settings so much could cause the printer to refuse the job, and using zoom breaks the ability to print the same page from a browser.

I also verified that printing the page from Chrome or Chromium doesn't present the same issue, but I struggle to find where the problem is in the Electron code base. It seems like, by doing a silent print request, some parameter doesn't get initialized properly.

FYI: On macOS everything is fine

@Wexoo
Copy link

Wexoo commented Dec 13, 2023

Having the same issue, I checked different versions today and can confirm the previous commenters.
Silent printing by version (built with electron-packager v17.1.2 on MacOS and run on Win11 ARM in Parallels Desktop):
25.3.1-29.0.0-alpha.3 -> working but shrunk content on PDF
25.0.0-25.3.0 -> not working at all
24.8.8 -> working, correct size

Would be great to have this fixed, since 24.x is already end of life, but this forces me to stay on that version.

@mozainuddin
Copy link

mozainuddin commented Feb 11, 2024

Having the same issue, I checked different versions today and can confirm the previous commenters. Silent printing by version (built with electron-packager v17.1.2 on MacOS and run on Win11 ARM in Parallels Desktop): 25.3.1-29.0.0-alpha.3 -> working but shrunk content on PDF 25.0.0-25.3.0 -> not working at all 24.8.8 -> working, correct size

Would be great to have this fixed, since 24.x is already end of life, but this forces me to stay on that version.

Thank you @Wexoo, I downgraded to 24.8.8 and it works perfectly

@priyabratap
Copy link

We recently upgraded to the latest version and facing the font size issue while printing out. It's very tiny. We tried changing the DPI, but the printer is not printing at all. while removing it's working with a tiny font size.

Need help/some work around to fix this issue.

@RohitSaroj
Copy link

@codebytere Do we have a timeline or a specific Electron version targeted for fixing this issue?

@CavenRE
Copy link

CavenRE commented Mar 18, 2024

I have tried SEVERAL versions and this is still very much an issue.
I have tried everything from Web Print, Image to PDF print, PDF print and NOTHING.
Nothing is working, I think this is not a tiny issue, this a MAJOR issue, to point that if I was aware of this before I started my project, I would of never used Electron, but now I'm locked in trying to solve a bug that shouldn't exist.
This needs way more attention than it is getting now.
Until then, I straight up refuse to use Electron till this is issue CONFIRMED to have been fixed.

I mean my current fix attempt on printing an image is:

ipcMain.handle("print-image", async (_, imagePath) => {
  let imageWin = new BrowserWindow({ 
    show: false, 
    webPreferences: {
      images: true
    }
  });

  imageWin.loadFile(imagePath);

  return new Promise<void>((resolve, reject) => {
    imageWin.webContents.on("did-finish-load", () => {
      const options: Electron.WebContentsPrintOptions = {
        silent: true,
        landscape: true,
        pageSize: "A6",
        margins: {
          marginType: "none" as const,
        },
        pagesPerSheet: 1,
        dpi: {
          horizontal: 600,
          vertical: 600,
        },
        collate: false,
        copies: 1,
      };
      
      imageWin.webContents.print(options, (success, failureReason) => {
        if (success) {
          resolve();
        } else {
          console.error(failureReason);
          reject(new Error(failureReason));
        }
        imageWin.close();
      });
    });
  });
});

The thing is... I can somewhat get it working. But for some magical reason, everything is stuck at the A4 scale, regardless of what page size I attempt to use or however I try enforce my settings, this one of many and I mean many attempts.
But it simple seems to be impossible to resolve this. I have tried ever version that has said it has "fixed" this issue.

I'm just over it now.

@michel-smarticket
Copy link

@codebytere any news on this?
We're stuck on 24.8.8 for quite a while now.

@nurik24
Copy link

nurik24 commented Apr 4, 2024

I have the same issue, added
dpi: { horizontal: 600, vertical: 600, },
its working for now, but would be great to have it fixed. I'm on version 26.2.2

@sridharpg
Copy link

This issue is actually not fixed. The pdf is generated fine but the prints are not triggered with proper layout in silent mode. #41928 explains it.

@EL-MEHDI-ESSAADI
Copy link

Yes, it's not fixed yet, there is still the same issue in 31.0.0-alpha.2

@sridharpg
Copy link

For now, I have resorted back to https://www.npmjs.com/package/pdf-to-printer. While its not perfect, it helps me with most of the cases. I faced an issue with orientation, and only for Windows, I had to provide an additional orientation setting in my app, which overcame this issue.

I think this ticket needs to be reopened till the printing issue is resolved.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
No open projects
Status: Unsorted Items
Status: 👍 Does Not Block Stable
Status: 👍 Does Not Block Stable
Development

Successfully merging a pull request may close this issue.