You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Electron-Vite(React)迁移后纵向打印失效,始终横向输出求助

问题分析与解决方案

核心问题定位

从Electron 22升级到25后,打印行为出现两个异常:强制横向输出、字体尺寸极小。结合你打印外部页面也出现横向问题的情况,问题根源大概率是Electron 23+版本对打印参数的处理逻辑变更,而非electron-vite本身。


分步解决方案

1. 修正打印选项:明确指定纸张尺寸

Electron 23+对landscape参数的优先级做了调整,仅设置landscape: false不足以强制纵向,需要配合pageSize明确指定小票纸尺寸(80mm宽):

const printOptions = {
  silent: true,
  preview: false, // 关闭预览模式,避免干扰实际打印参数
  printBackground: true,
  color: true,
  margin: {
    top: 0,
    bottom: 0,
    left: 0,
    right: 0 // 手动设置边距为0,替代printableArea(新版行为不稳定)
  },
  landscape: false,
  // 80mm小票纸转CSS像素(Electron默认96DPI)
  pageSize: { 
    width: 80 * 96 / 25.4, 
    height: 1000 // 足够长的高度适配小票内容
  },
  pagesPerSheet: 1,
  collate: false,
  copies: 1
}

2. 调整BrowserWindow创建参数

新版设置的width:302可能干扰打印视口适配,建议移除固定宽度,同时适配Electron 25的默认配置:

ipcMain.on('toMain', async (event, url) => {
  console.log('print invoked', url)
  const win = new BrowserWindow({ 
    show: false,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false // Electron25默认开启该选项,需关闭才能配合nodeIntegration使用
    }
  })

  win.loadURL(url)

  // 改用dom-ready+延迟触发,确保页面完全渲染
  win.webContents.on('dom-ready', () => {
    setTimeout(() => {
      win.webContents.print(printOptions, (success, failureReason) => {
        console.log('Print Initiated in Main...')
        if (!success) console.log('ERR', failureReason)
        win.close() // 打印完成后关闭窗口,避免内存泄漏
      })
    }, 200)
  })

  return true
})

3. 页面端添加打印专属样式

在打印页面的CSS中添加@media print规则,强制适配小票纸尺寸:

@media print {
  @page {
    size: 80mm auto;
    margin: 0;
  }
  body {
    width: 80mm;
    margin: 0;
    padding: 5mm;
    font-size: 12pt; /* 明确字体大小,避免自动缩放 */
  }
}

排查验证步骤

  1. 先移除BrowserWindow的width参数,测试是否恢复纵向打印
  2. 若问题仍存在,添加pageSize参数并调整数值
  3. 检查页面是否存在强制横向的CSS规则(比如transform: rotate(90deg))

内容的提问来源于stack exchange,提问作者Anandu Babu

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.08 07:15:09