printServer/utils/printerPaper.js
liufumingren ee054f039a feat(printer): PDF 打印支持按驱动纸张自动选纸
- 新增 utils/printerPaper.js:读取驱动 PaperSizes(名称/尺寸/DMPAPER id),按打印机缓存 10 分钟
- 按 PDF 首页尺寸匹配纸张:精确 → 能容纳的最小纸 → 装不下时取最大纸并自动改 shrink
- 纸张参数优先 paper=<驱动纸名>,纯数字或含逗号时回退 paperkind=<RawKind>;User defined 不参与匹配
- 新增配置 pdfPrint.autoPaper(默认 true),显式 papers/请求参数仍优先
- SumatraPDF-settings.txt 加入 .gitignore(运行期生成)
- 版本 1.0.42

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

121 lines
4.6 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 { spawn } from 'child_process';
const CACHE_TTL_MS = 10 * 60 * 1000;
const NEGATIVE_TTL_MS = 60 * 1000;
const DMPAPER_USER = 256;
const cache = new Map(); // printerName -> { at, sizes }
/**
* 读取 Windows 驱动支持纸张列表(名称 + 1/100 英寸尺寸 + DMPAPER id)
* 打印机名通过环境变量传入,避免拼进 PowerShell 命令字符串。
*/
export function getPrinterPaperSizes(printerName) {
const key = String(printerName || '');
const hit = cache.get(key);
if (hit && Date.now() - hit.at < (hit.sizes.length > 0 ? CACHE_TTL_MS : NEGATIVE_TTL_MS)) {
return Promise.resolve(hit.sizes);
}
const script = [
'Add-Type -AssemblyName System.Drawing;',
'$ps = New-Object System.Drawing.Printing.PrinterSettings;',
'$ps.PrinterName = $env:PS_PRINTER;',
'if (-not $ps.IsValid) { "[]"; exit 0 };',
'$ps.PaperSizes | ForEach-Object { [PSCustomObject]@{ Name=$_.PaperName; Width=$_.Width; Height=$_.Height; RawKind=$_.RawKind } } | ConvertTo-Json -Compress'
].join(' ');
return new Promise((resolve) => {
let child;
try {
child = spawn('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', script], {
windowsHide: true,
env: { ...process.env, PS_PRINTER: key }
});
} catch (_) {
cache.set(key, { at: Date.now(), sizes: [] });
resolve([]);
return;
}
const chunks = [];
child.stdout.on('data', (c) => chunks.push(c));
child.on('error', () => {
cache.set(key, { at: Date.now(), sizes: [] });
resolve([]);
});
child.on('exit', () => {
let parsed = [];
try {
const text = Buffer.concat(chunks).toString('utf8').trim();
if (text) {
const json = JSON.parse(text);
parsed = (Array.isArray(json) ? json : [json])
.filter(p => p && p.Name)
.map(p => ({
name: String(p.Name),
width: Number(p.Width) || 0,
height: Number(p.Height) || 0,
rawKind: Number(p.RawKind) || 0
}));
}
} catch (_) { /* 解析失败按无纸处理 */ }
cache.set(key, { at: Date.now(), sizes: parsed });
resolve(parsed);
});
});
}
/**
* 按页面尺寸挑纸:精确匹配 → 能容纳的最小纸 → 都装不下时取最大纸(需配合 shrink)
* @param {{widthPt:number,heightPt:number}} page 来自 readPageSizePt
* @returns {{name:string,rawKind:number,fits:boolean,setting:string}|null}
*/
export function selectPaperForPage(page, paperSizes) {
if (!page || !Array.isArray(paperSizes) || paperSizes.length === 0) return null;
const target = { w: page.widthPt / 72 * 100, h: page.heightPt / 72 * 100 };
const candidates = paperSizes.filter(p => p.width > 0 && p.height > 0 && p.rawKind !== DMPAPER_USER);
if (candidates.length === 0) return null;
const tolerance = 8; // 1/100 inch
let exact = null;
let smallestFitting = null;
let largest = null;
for (const paper of candidates) {
const area = paper.width * paper.height;
if (!largest || area > largest.area) largest = { paper, area };
const fitsDirect = paper.width >= target.w - 2 && paper.height >= target.h - 2;
const fitsRotated = paper.height >= target.w - 2 && paper.width >= target.h - 2;
if (fitsDirect || fitsRotated) {
if (!smallestFitting || area < smallestFitting.area) smallestFitting = { paper, area };
}
if (Math.abs(paper.width - target.w) <= tolerance && Math.abs(paper.height - target.h) <= tolerance) {
exact = paper;
}
}
const chosen = exact || smallestFitting?.paper || largest?.paper;
if (!chosen) return null;
return {
name: chosen.name,
rawKind: chosen.rawKind,
fits: Boolean(exact || smallestFitting),
setting: buildPaperSetting(chosen)
};
}
/**
* 生成 -print-settings 里的纸张片段。
* 名称含逗号会破坏逗号分隔的参数列表,纯数字名称可能被 Sumatra 误解析,这两种情况改用 paperkind。
*/
export function buildPaperSetting(paper) {
const name = String(paper.name || '').trim();
const usable = name && !name.includes(',') && /[A-Za-z]/.test(name);
if (usable) return `paper=${name}`;
if (paper.rawKind) return `paperkind=${paper.rawKind}`;
return '';
}