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

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

About this issue

  • Original URL
  • State: closed
  • Created 3 years ago
  • Reactions: 2
  • Comments: 38 (1 by maintainers)

Most upvoted comments

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

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.

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

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.

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

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.

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

Hello everyone, the best solution that I found is showing a pdf preview of the document that I want to print, the preview will have a print button by default, that can print the document perfectly

Here is how I show the pdf preview

/**
 * IPC handler for previewing a component/webpage as PDF
 * @param {PrintData} data - Configuration data for PDF preview
 * @param {string} data.url - The URL of the document (html url) to preview
 * @param {boolean} data.landscape - Whether to use landscape orientation
 * @param {string} data.pageSize - The page size for the PDF (e.g., 'A4', 'Letter')
 * @returns {Promise<string>} A promise that resolves with success/error message
 */
ipcMain.handle("printComponentToPDF", async (_, data: PrintData) => {
  // Create hidden browser window for PDF generation
  const win = new BrowserWindow({
    title: "Preview",
    show: false,
    autoHideMenuBar: true,
  });

  win.loadURL(data.url);

  const response = await new Promise((res, rej) => {
    // Wait for the page to load before generating PDF
    win.webContents.once("did-finish-load", async () => {
      try {
        // Generate PDF with specified settings
        const pdf = await win.webContents.printToPDF({
          printBackground: true,
          margins: {
            marginType: "printableArea",
          },
          landscape: data.landscape,
          pageSize: data.pageSize,
        });

        // Convert PDF to base64 for preview
        const buf = Buffer.from(pdf);
        const pdfData = buf.toString("base64");

        // Create data URL and show preview window
        const url = "data:application/pdf;base64," + pdfData;
        win.webContents.on("dom-ready", () => {
          win.show();
          win.setTitle("Preview");
        });
        win.loadURL(url);
        res("Print successful");
      } catch (error) {
        rej(error);
      }
    });
  });

  return response;
});

Here is how I generate data.url

function getElementContentUrl(target: HTMLElement): string | null {
    console.log("generating URL for element content...");

    const data = target.outerHTML;
    if (!data) return null;

    const fullHtml = `
        <!DOCTYPE html>
        <html>
            <head>
                <meta charset="utf-8">
                <title>Element Content</title>
            </head>
            <body>
                ${data}
            </body>
        </html>
    `;

    const blob = new Blob([fullHtml], { type: "text/html;charset=utf-8" });
    return URL.createObjectURL(blob);
}

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

The issue doesn’t show up on all printers afaik. I found a different solution. If we pass the right page dimensions, prints came out right(without needing the external module pdf-to-printer) on the Zebra printers(tested on zd621 and zc10l).

pageSize: {
    height: dim.pageHeight*1000,
    width: dim.pageWidth*1000
}

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.

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.

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.

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