diff --git a/SumatraPDF/NOTICE.txt b/SumatraPDF/NOTICE.txt new file mode 100644 index 0000000..4e3ec34 --- /dev/null +++ b/SumatraPDF/NOTICE.txt @@ -0,0 +1,8 @@ +SumatraPDF 3.6.1 (64-bit, portable) + +来源: https://www.sumatrapdfreader.org/ +许可: (A)GPLv3 —— https://www.sumatrapdfreader.org/docs/SumatraPDF-license +用途: 本程序以独立进程 + 命令行参数方式调用它做 PDF 静默打印(-print-to / -print-settings / -silent), + 未修改其源码,也未与其静态链接。 + +如需替换版本,直接覆盖 SumatraPDF.exe 即可;也可在 config.json 的 pdfPrint.exePath 中指定其它路径。 diff --git a/SumatraPDF/SumatraPDF.exe b/SumatraPDF/SumatraPDF.exe new file mode 100644 index 0000000..3f1d761 Binary files /dev/null and b/SumatraPDF/SumatraPDF.exe differ diff --git a/build.ps1 b/build.ps1 index 44bffdd..51dc6fc 100644 --- a/build.ps1 +++ b/build.ps1 @@ -352,7 +352,7 @@ function Ensure-PackagedResources() { Copy-Item -Path $iconSourcePath -Destination $iconTargetPath -Force } - foreach ($dirName in @('frpc')) { + foreach ($dirName in @('frpc', 'SumatraPDF')) { $sourcePath = Join-Path $root $dirName $targetPath = Join-Path $resourcesDir $dirName @@ -411,7 +411,34 @@ function Prepare-Stage { $manifest | ConvertTo-Json -Depth 4 | Set-Content -Path (Join-Path $tempPackagingDir 'preflight-check.json') -Encoding UTF8 } +function Ensure-ElectronNativeModules { + # better-sqlite3 必须匹配 Electron 的 ABI;否则安装后后端起不来 + # (Node 24 = 137,Electron 37 = 136,用系统 Node 的预编译产物会 dlopen 失败) + $electronPkg = Join-Path $root 'node_modules\electron\package.json' + $betterSqliteDir = Join-Path $root 'node_modules\better-sqlite3' + if (-not (Test-Path $electronPkg) -or -not (Test-Path $betterSqliteDir)) { + Write-Log 'WARN skip electron native module check: electron/better-sqlite3 not installed' + return + } + + $electronVersion = [string]((Get-Content $electronPkg -Raw | ConvertFrom-Json).version) + Write-Log "electron native modules: prebuild-install -r electron -t $electronVersion" + + Push-Location $betterSqliteDir + try { + & npx.cmd prebuild-install -r electron -t $electronVersion + if ($LASTEXITCODE -ne 0) { + Write-Log 'WARN prebuild-install for electron failed; packaged app may fail to load better-sqlite3' + } + } catch { + Write-Log ("WARN prebuild-install for electron error: " + $_.Exception.Message) + } finally { + Pop-Location + } +} + function App-Stage { + Ensure-ElectronNativeModules $builderFailed = $false try { diff --git a/config.packaged.json b/config.packaged.json index 9de4351..9b57d78 100644 --- a/config.packaged.json +++ b/config.packaged.json @@ -6,6 +6,13 @@ "logLevel": "info", "printerDefault": "", "maxPrintJobs": 10, + "pdfPrint": { + "exePath": "", + "paper": "", + "papers": {}, + "scale": "noscale", + "timeoutMs": 60000 + }, "isService": false, "remoteWs": { "url": "ws://printer.wms.gztbyc.com/ws", diff --git a/core/wsServer.js b/core/wsServer.js index e26799a..439a63c 100644 --- a/core/wsServer.js +++ b/core/wsServer.js @@ -52,6 +52,9 @@ class WSServer { this._eventHandlers.printerList = (data) => { this.broadcast({ success: true, method: 'printer.getWindowsPrinters', result: data }); }; + this._eventHandlers.pdfPrintProgress = (data) => { + this.broadcast({ success: true, method: 'printer.pdfPrintProgress', result: data }); + }; this._eventHandlers.updateDownloadProgress = (data) => { this.broadcast({ success: true, method: 'update.downloadProgress', result: data }); }; @@ -69,6 +72,7 @@ class WSServer { this.app.on('wsClientStatusChange', this._eventHandlers.wsClientStatusChange); this.app.on('generateCode', this._eventHandlers.generateCode); this.app.on('printerList', this._eventHandlers.printerList); + this.app.on('pdfPrintProgress', this._eventHandlers.pdfPrintProgress); this.app.on('updateDownloadProgress', this._eventHandlers.updateDownloadProgress); this.app.on('infoChanged', this._eventHandlers.infoChanged); this.app.on('frpcStatusChange', this._eventHandlers.frpcStatusChange); @@ -92,6 +96,9 @@ class WSServer { if (this._eventHandlers.printerList) { this.app.off('printerList', this._eventHandlers.printerList); } + if (this._eventHandlers.pdfPrintProgress) { + this.app.off('pdfPrintProgress', this._eventHandlers.pdfPrintProgress); + } if (this._eventHandlers.updateDownloadProgress) { this.app.off('updateDownloadProgress', this._eventHandlers.updateDownloadProgress); } diff --git a/package-lock.json b/package-lock.json index 5f49799..61cba49 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "printserver", - "version": "1.0.39", + "version": "1.0.41", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "printserver", - "version": "1.0.39", + "version": "1.0.41", "hasInstallScript": true, "license": "ISC", "dependencies": { diff --git a/package.json b/package.json index ee32902..367cde2 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "printserver", - "version": "1.0.39", + "version": "1.0.41", "main": "electron/main.cjs", "scripts": { "start": "node index.js", @@ -79,6 +79,10 @@ { "from": "frpc", "to": "frpc" + }, + { + "from": "SumatraPDF", + "to": "SumatraPDF" } ], "win": { diff --git a/services/printer.js b/services/printer.js index 9ec50cc..39f8a22 100644 --- a/services/printer.js +++ b/services/printer.js @@ -5,6 +5,11 @@ import path from 'path'; import { pathToFileURL } from 'url'; import lodopUtil from '../utils/lodop.js'; import { isRecordingMode } from '../utils/runtime.js'; +import { + collectPdfJobs, + printPdfJobs, + resolveSumatraExe +} from '../utils/pdfPrint.js'; // 打印机服务类 class PrinterService extends service { @@ -12,6 +17,7 @@ class PrinterService extends service { super(); this.getWindowsPrinters = this.getWindowsPrinters.bind(this); // 确保上下文绑定 this.print = this.print.bind(this); // 确保上下文绑定 + this.printPdf = this.printPdf.bind(this); // 确保上下文绑定 } // 录制模式守卫:非 Windows 或纯录制模式拒绝打印相关操作 @@ -203,6 +209,88 @@ class PrinterService extends service { return; } } + /** + * 打印 PDF(静默,Windows 专用) + * data 两种形态: + * 1) 直接给业务数据数组:printer 取配置默认值 + * [{ wave_id, wave_no, platforms: [{ platform, order_ids, orders: [{ pdf_base64 }] }] }] + * [{ platform, order_ids, orders: [{ pdf_base64 }] }] + * 2) 带请求参数的对象(可显式指定打印机): + * { printer, paper?, scale?, copies?, printId?, payload: [ ...上面的数组... ] } + * 优先级:波次/平台/订单上的 printer/paper > 请求上的 printer/paper + * 打印机必须由请求提供(不读配置默认值),避免误打到默认打印机。 + */ + async printPdf(data) { + this._guardRecordingMode(); + if (process.platform !== 'win32') { + throw new Error('PDF 打印仅支持 Windows'); + } + + const pdfCfg = this.config.pdfPrint || {}; + const options = (data && !Array.isArray(data) && typeof data === 'object') ? data : {}; + const payload = options.payload || options.waves || data; + + const jobs = collectPdfJobs(payload); + if (jobs.length === 0) { + throw new Error('未找到可打印的 pdf_base64 数据'); + } + + const exe = resolveSumatraExe(pdfCfg.exePath); + if (!exe) { + throw new Error('未找到 SumatraPDF.exe,请放到 SumatraPDF\\SumatraPDF.exe 或配置 pdfPrint.exePath'); + } + + const defaultPrinter = String(options.printer || '').trim(); + const defaultPaper = String(options.paper || pdfCfg.paper || '').trim(); + const papers = pdfCfg.papers || {}; + const scale = String(options.scale || pdfCfg.scale || 'noscale').trim(); + const copies = Number(options.copies) > 0 ? Number(options.copies) : 1; + const timeoutMs = Number(options.timeoutMs) > 0 ? Number(options.timeoutMs) : (Number(pdfCfg.timeoutMs) || 60000); + const printId = String(options.printId || options.requestID || jobs[0].waveNo || `pdf-${Date.now()}`); + + const resolvedJobs = jobs.map(job => { + const printer = String(job.printer || defaultPrinter || '').trim(); + const paper = String(job.paper || (printer && papers[printer]) || defaultPaper || '').trim(); + return { ...job, printer, paper }; + }); + + const missingPrinter = resolvedJobs.find(job => !job.printer); + if (missingPrinter) { + throw new Error('未指定打印机:请在请求中传 printer,或在波次/平台/订单上带 printer'); + } + + this.app.printTasks = this.app.printTasks || new Map(); + this.app.printTasks.set(printId, 'pending'); + + const result = await printPdfJobs({ + exe, + printer: defaultPrinter, + paper: defaultPaper, + scale, + copies, + timeoutMs, + jobs: resolvedJobs, + printId, + onResult: (detail) => { + this._emitPdfPrintProgress(printId, detail); + } + }); + + this.app.printTasks.set(printId, result.failed === 0 ? 'printed' : 'failed'); + return result; + } + + _emitPdfPrintProgress(printId, detail) { + this.app.emit('pdfPrintProgress', { + printId, + orderId: detail.orderId, + index: detail.index, + printer: detail.printer, + status: detail.ok ? 'success' : 'failed', + message: detail.ok ? 'PDF 打印成功' : detail.error + }); + } + //渲染自定义打印内容,返回HTML字符串 renderCustomPrintContent(data) { const lodop = new lodopUtil(); diff --git a/utils/pdfPrint.js b/utils/pdfPrint.js new file mode 100644 index 0000000..01f51a1 --- /dev/null +++ b/utils/pdfPrint.js @@ -0,0 +1,305 @@ +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 };