import fs from 'fs'; import os from 'os'; import path from 'path'; import { spawn } from 'child_process'; import { ensureDirectory, getProjectRoot, getResourcePath } from './runtime.js'; import { getPrinterPaperSizes, selectPaperForPage } from './printerPaper.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/paperSetting 含空格时必须作为单个 argv 传入,因此这里只返回数组。 */ export function buildPrintArgs({ printer, paper, paperSetting, scale, copies, appDataDir, pdfPath }) { const settings = []; const paperPart = paperSetting || (paper ? `paper=${paper}` : ''); if (paperPart) settings.push(paperPart); 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 > autoPaper 自动选纸。 * @param {object} options * @param {string} options.exe SumatraPDF.exe 路径 * @param {string} [options.printer] 默认目标打印机 * @param {string} [options.paper] 默认纸张(如 "104mm x 110mm"),空则用 autoPaper 或驱动默认 * @param {boolean} [options.autoPaper] 未指定纸张时按 PDF 页面尺寸自动匹配驱动纸张(默认 true) * @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 = '', autoPaper = true, 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 page = readPageSizePt(buf); let paperSetting = ''; let effectiveScale = scale; let autoPaperInfo = null; if (!jobPaper && autoPaper && page) { const sizes = await getPrinterPaperSizes(jobPrinter); const selection = selectPaperForPage(page, sizes); if (selection) { paperSetting = selection.setting; if (!selection.fits) effectiveScale = 'shrink'; autoPaperInfo = { name: selection.name, rawKind: selection.rawKind, fits: selection.fits }; } else if (sizes.length === 0) { autoPaperInfo = { name: null, reason: '未读取到驱动纸张列表,使用驱动默认纸' }; } } const args = buildPrintArgs({ printer: jobPrinter, paper: jobPaper, paperSetting, scale: effectiveScale, copies, appDataDir, pdfPath: filePath }); const result = await spawnSumatraPrint({ exe, args, timeoutMs }); detail = { ...base, ok: result.ok, size: buf.length, page, autoPaper: autoPaperInfo, scale: effectiveScale, exitCode: result.exitCode, ms: result.ms, error: result.error }; const paperLabel = autoPaperInfo?.name ? `${autoPaperInfo.name}${autoPaperInfo.fits ? '' : '(自动缩小)'}` : (jobPaper || '(驱动默认)'); logger.log(`[PDF] 第 ${i + 1}/${jobs.length} 张 ${result.ok ? '成功' : '失败'},printer=${jobPrinter}, paper=${paperLabel}, scale=${effectiveScale}, 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, autoPaper, scale, total: details.length, printed, failed, details }; } export { MAX_PDF_BYTES };