printServer/utils/pdfPrint.js
liufumingren b3ae701d3a feat(printer): 新增 printer.printPdf 静默打印 PDF(内置 SumatraPDF)
- 17301 新增 printer.printPdf:接收波次/平台/订单结构,逐张串行静默打印
- printer 必传(请求参数或波次/平台/订单字段),纸张按 pdfPrint.papers 匹配打印机
- 内置 SumatraPDF 3.6.1 便携版,extraResources 随包分发;仅 win32,录制模式拒绝
- wsServer 广播 printer.pdfPrintProgress(仅本机客户端,不串到远端通道)
- build.ps1 新增 Ensure-ElectronNativeModules,修复 better-sqlite3 ABI 与 Electron 不匹配导致打包后后端起不来
- 版本 1.0.41

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-24 23:32:14 +08:00

306 lines
11 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import fs from 'fs';
import os from 'os';
import path from 'path';
import { spawn } from 'child_process';
import { ensureDirectory, getProjectRoot, getResourcePath } from './runtime.js';
const MAX_PDF_BYTES = 20 * 1024 * 1024;
const EXIT_CODE_TEXT = {
0: '成功',
2: '无法打开文件(文件不存在或格式不支持)',
3: '文档禁止打印',
4: '打印机不存在',
5: '打印机驱动或设备错误',
6: '打印被策略禁用'
};
/**
* 定位 SumatraPDF.exe:配置路径 → 打包 resources → 项目根目录
*/
export function resolveSumatraExe(configuredPath) {
const candidates = [];
if (typeof configuredPath === 'string' && configuredPath.trim()) {
candidates.push(configuredPath.trim());
}
candidates.push(getResourcePath('SumatraPDF', 'SumatraPDF.exe'));
candidates.push(path.join(getProjectRoot(), 'SumatraPDF', 'SumatraPDF.exe'));
for (const candidate of candidates) {
try {
if (fs.existsSync(candidate) && fs.statSync(candidate).isFile()) {
return candidate;
}
} catch (_) { /* 忽略单个候选路径的异常 */ }
}
return null;
}
/**
* 解码并校验 base64 PDF:兼容 data URI 前缀、空白、URL-safe 字符集
*/
export function decodePdfBase64(input) {
if (typeof input !== 'string') {
throw new Error('pdf_base64 必须是字符串');
}
let text = input.trim();
const dataUri = /^data:[^;,]*;base64,/i.exec(text);
if (dataUri) {
text = text.slice(dataUri[0].length);
}
text = text.replace(/\s+/g, '');
if (!text) {
throw new Error('pdf_base64 为空');
}
if (/[-_]/.test(text)) {
text = text.replace(/-/g, '+').replace(/_/g, '/');
}
if (!/^[A-Za-z0-9+/]+={0,2}$/.test(text)) {
throw new Error('pdf_base64 含非法字符');
}
const estimatedBytes = Math.floor(text.length * 3 / 4);
if (estimatedBytes > MAX_PDF_BYTES) {
throw new Error(`PDF 过大: 约 ${estimatedBytes} 字节,上限 ${MAX_PDF_BYTES} 字节`);
}
const buf = Buffer.from(text, 'base64');
if (buf.length < 5 || buf.subarray(0, 5).toString('latin1') !== '%PDF-') {
throw new Error('不是有效的 PDF(缺少 %PDF- 文件头)');
}
return buf;
}
/**
* 从波次/平台/订单结构中收集待打印任务。
* 支持:
* [{ wave_id, wave_no, platforms: [{ platform, order_ids, orders: [{ pdf_base64 }] }] }]
* [{ platform, order_ids, orders: [{ pdf_base64 }] }]
* { platforms: [...] } / { orders: [...] }
*/
export function collectPdfJobs(payload) {
const jobs = [];
const addOrder = (order, ctx) => {
if (!order || typeof order !== 'object') return;
const base64 = order.pdf_base64;
if (typeof base64 !== 'string' || !base64.trim()) return;
jobs.push({
waveId: ctx.waveId ?? null,
waveNo: ctx.waveNo ?? null,
platform: ctx.platform ?? null,
platformName: ctx.platformName ?? null,
orderId: order.order_id ?? order.orderId ?? order.id ?? ctx.orderIds?.[0] ?? null,
printer: order.printer ?? ctx.printer ?? null,
paper: order.paper ?? ctx.paper ?? null,
base64
});
};
const visitPlatform = (platform, ctx) => {
if (!platform || typeof platform !== 'object') return;
const platformCtx = {
...ctx,
platform: platform.platform ?? null,
platformName: platform.platform_name ?? null,
orderIds: Array.isArray(platform.order_ids) ? platform.order_ids : [],
printer: platform.printer ?? ctx.printer ?? null,
paper: platform.paper ?? ctx.paper ?? null
};
const orders = Array.isArray(platform.orders) ? platform.orders : [];
for (const order of orders) addOrder(order, platformCtx);
};
const waves = Array.isArray(payload) ? payload : [payload];
for (const wave of waves) {
if (!wave || typeof wave !== 'object') continue;
const waveCtx = {
waveId: wave.wave_id ?? null,
waveNo: wave.wave_no ?? null,
printer: wave.printer ?? null,
paper: wave.paper ?? null
};
if (Array.isArray(wave.platforms)) {
for (const platform of wave.platforms) visitPlatform(platform, waveCtx);
} else if (Array.isArray(wave.orders)) {
visitPlatform(wave, waveCtx);
}
}
return jobs;
}
/**
* 读取 PDF 首页尺寸(MediaBox),用于日志与校验
*/
export function readPageSizePt(buf) {
const head = buf.toString('latin1', 0, Math.min(buf.length, 5 * 1024 * 1024));
const match = /\/MediaBox\s*\[\s*(-?[\d.]+)\s+(-?[\d.]+)\s+(-?[\d.]+)\s+(-?[\d.]+)\s*\]/.exec(head);
if (!match) return null;
const widthPt = Math.abs(parseFloat(match[3]) - parseFloat(match[1]));
const heightPt = Math.abs(parseFloat(match[4]) - parseFloat(match[2]));
if (!Number.isFinite(widthPt) || !Number.isFinite(heightPt)) return null;
return {
widthPt: Math.round(widthPt * 100) / 100,
heightPt: Math.round(heightPt * 100) / 100,
widthMm: Math.round(widthPt / 72 * 25.4 * 10) / 10,
heightMm: Math.round(heightPt / 72 * 25.4 * 10) / 10
};
}
/**
* 组装 SumatraPDF 命令行参数。
* paper/settings 含空格时必须作为单个 argv 传入,因此这里只返回数组。
*/
export function buildPrintArgs({ printer, paper, scale, copies, appDataDir, pdfPath }) {
const settings = [];
if (paper) settings.push(`paper=${paper}`);
if (scale) settings.push(scale);
if (Number(copies) > 1) settings.push(`${Math.floor(Number(copies))}x`);
const args = ['-print-to', printer];
if (settings.length > 0) args.push('-print-settings', settings.join(','));
args.push('-silent');
if (appDataDir) args.push('-appdata', appDataDir);
args.push(pdfPath);
return args;
}
/**
* 静默打印单个 PDF,用退出码判定结果
*/
export function spawnSumatraPrint({ exe, args, timeoutMs = 60000 }) {
return new Promise((resolve) => {
const startedAt = Date.now();
let child;
try {
child = spawn(exe, args, { windowsHide: true, stdio: 'ignore' });
} catch (e) {
resolve({ ok: false, exitCode: null, error: e.message, ms: 0 });
return;
}
let settled = false;
const timer = setTimeout(() => {
try { child.kill(); } catch (_) { /* 进程可能已退出 */ }
finish({ ok: false, exitCode: null, error: `打印超时(${timeoutMs}ms)` });
}, timeoutMs);
function finish(result) {
if (settled) return;
settled = true;
clearTimeout(timer);
resolve({ ...result, ms: Date.now() - startedAt });
}
child.on('error', (err) => finish({ ok: false, exitCode: null, error: err.message }));
child.on('exit', (code) => {
if (code === 0) {
finish({ ok: true, exitCode: 0 });
return;
}
const text = EXIT_CODE_TEXT[code] || `未知退出码 ${code}`;
finish({ ok: false, exitCode: code, error: `SumatraPDF 打印失败: ${text}` });
});
});
}
export function getPdfWorkDirs() {
const root = path.join(os.tmpdir(), 'printServer-pdf');
return {
tmpDir: ensureDirectory(path.join(root, 'tmp')),
appDataDir: ensureDirectory(path.join(root, 'sumatra'))
};
}
/**
* 串行打印一组 PDF 任务(jobs 来自 collectPdfJobs)。
* 打印机 / 纸张优先级:job 自带的 printer/paper > 入参 printer/paper。
* @param {object} options
* @param {string} options.exe SumatraPDF.exe 路径
* @param {string} [options.printer] 默认目标打印机
* @param {string} [options.paper] 默认纸张(如 "104mm x 110mm"),空则用驱动默认
* @param {string} [options.scale] noscale/fit/shrink/stretch
* @param {number} [options.copies]
* @param {number} [options.timeoutMs]
* @param {Array} options.jobs [{ base64, printer?, paper?, orderId, platform, waveNo }]
* @param {string} [options.printId]
* @param {Function} [options.onResult] 单张完成回调,参数为 detail
*/
export async function printPdfJobs({
exe,
printer = '',
paper = '',
scale = 'noscale',
copies = 1,
timeoutMs = 60000,
jobs,
printId = `pdf-${Date.now()}`,
onResult,
logger = console
}) {
const { tmpDir, appDataDir } = getPdfWorkDirs();
const details = [];
logger.log(`[PDF] 开始打印,printId=${printId}, scale=${scale}, 共 ${jobs.length} 张`);
for (let i = 0; i < jobs.length; i++) {
const job = jobs[i];
const jobPrinter = String(job.printer || printer || '').trim();
const jobPaper = String(job.paper || paper || '').trim();
const safeName = `${printId}-${i + 1}.pdf`.replace(/[\\/:*?"<>|]/g, '_');
const filePath = path.join(tmpDir, safeName);
const base = {
index: i + 1,
orderId: job.orderId,
platform: job.platform,
waveNo: job.waveNo,
printer: jobPrinter || null,
paper: jobPaper || null
};
let detail;
try {
if (!jobPrinter) {
throw new Error('未指定打印机');
}
const buf = decodePdfBase64(job.base64);
fs.writeFileSync(filePath, buf);
const args = buildPrintArgs({ printer: jobPrinter, paper: jobPaper, scale, copies, appDataDir, pdfPath: filePath });
const result = await spawnSumatraPrint({ exe, args, timeoutMs });
detail = {
...base,
ok: result.ok,
size: buf.length,
page: readPageSizePt(buf),
exitCode: result.exitCode,
ms: result.ms,
error: result.error
};
logger.log(`[PDF] 第 ${i + 1}/${jobs.length} 张 ${result.ok ? '成功' : '失败'},printer=${jobPrinter}, paper=${jobPaper || '(驱动默认)'}, exitCode=${result.exitCode}, ${result.ms}ms${result.error ? ', ' + result.error : ''}`);
} catch (e) {
detail = { ...base, ok: false, error: e.message };
logger.error(`[PDF] 第 ${i + 1}/${jobs.length} 张处理失败: ${e.message}`);
} finally {
try { fs.unlinkSync(filePath); } catch (_) { /* 文件可能未创建 */ }
}
details.push(detail);
if (typeof onResult === 'function') {
try { onResult(detail); } catch (_) { /* 回调异常不影响后续打印 */ }
}
}
const printed = details.filter(d => d.ok).length;
const failed = details.length - printed;
return {
ok: failed === 0,
printId,
printers: [...new Set(details.map(d => d.printer).filter(Boolean))],
paper: paper || null,
scale,
total: details.length,
printed,
failed,
details
};
}
export { MAX_PDF_BYTES };