在 NW.js 跨端应用中 调用打印机循环打印PDF文件

179 阅读1分钟

项目背景

前端使用 NW.js + Vue3 实现跨端桌面应用开发(不要问我为什么选用NW.js 而不是Electron,项目历史背景导致的,换做我自己我会选Electron)

打印方法封装

// 导入 gui
const gui = require("nw.gui");
export const windPrint = async (data: any) => {
  // 本地打印文件路径 调试用 需要本地放置对应文件
  // const Url = "C://xxxx.pdf";

  // 接受文件流
  const blob = new Blob([data], {
    type: "application/pdf",
  });

  // 生成临时url
  const Url = URL.createObjectURL(blob);

  try {
    // 调用 nw
    // 打开一个新窗口,并设置焦点为false
    gui.Window.open(Url, { focus: false }, (wind: any) => {
      // 定义一个打印设置的变量
      const printSetting = {
        autoprint: true, // 自动打印
        silent: false, // 静默模式
      };
      if (wind) {
        // 不开启打印预览
        const handleLoaded = () => {
          wind.removeListener("loaded", handleLoaded);
          // 打印窗口最小化
          wind.minimize(true);
          // 打印
          wind.print(printSetting);
          // 延迟关闭窗口
          setTimeout(() => {
            if (wind) wind.close(true);
            // 清理对象 URL
            URL.revokeObjectURL(Url);
          }, 8000); // 8秒后关闭窗口
        };
        // 监听加载完成事件,当加载完成时调用handleLoaded函数
        wind.on("loaded", handleLoaded);
      }
    });
  } catch (error) {
    console.log("error", error);
  }
};

调用打印方法

// 单次打印
const onPrint = async (id: any) => {
  // 通过接口获取打印数据
  const data = await getPrintData(id);
  // 调用打印方法
  windPrint(data);
};

//打印数据的id集合 
const printDataIdList = [id1,id2,id3,id4]

// 打印功能触发
const handlePrint = async async () => {
 // 定义当前打印次数
 let times = 0;
  for (const item of printDataIdList) {
    await onPrint(item);
    times++;
  }
  
  // 根据自己的业务逻辑做处理
  if (times === printDataIdList.length){
      console.log("结束打印");
  }
};