Files

311 lines
13 KiB
JavaScript
Raw Permalink Normal View History

#!/usr/bin/env node
'use strict';
/**
* md2pdf.js —— 把 Obsidian 风格 Markdown(含 $..$ / $$..$$ 公式)转成适合打印/平板书写的 PDF
*
* 依赖(安装在托管 node 工作区): katex / markdown-it / puppeteer-core
* 渲染链: 公式保护 -> markdown-it -> KaTeX(服务端) -> 内联字体 CSS -> Edge(Chromium) 无头打印
*
* 用法:
* node md2pdf.js --in a.md --out a.pdf --title "标题" [--mode plain|answer] [--subtitle "..."]
*/
const fs = require('fs');
const path = require('path');
const NODE_WS = 'C:/Users/Wang Ling/.workbuddy/binaries/node/workspace';
const NM = path.join(NODE_WS, 'node_modules');
const MarkdownIt = require(path.join(NM, 'markdown-it'));
const katex = require(path.join(NM, 'katex'));
const puppeteer = require(path.join(NM, 'puppeteer-core'));
const EDGE = 'C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe';
/* ------------------------------ 参数解析 ------------------------------ */
function parseArgs(argv) {
const a = {};
for (let i = 2; i < argv.length; i++) {
const k = argv[i];
if (k.startsWith('--')) a[k.slice(2)] = (argv[i + 1] && !argv[i + 1].startsWith('--')) ? argv[++i] : true;
}
return a;
}
const ARGS = parseArgs(process.argv);
if (!ARGS.in || !ARGS.out) { console.error('缺少 --in / --out'); process.exit(1); }
const MODE = ARGS.mode === 'answer' ? 'answer' : (ARGS.mode === 'exam' ? 'exam' : 'plain');
/* ------------------------------ KaTeX CSS(内联字体) ------------------------------ */
function buildKatexCss() {
const cssPath = path.join(NM, 'katex/dist/katex.min.css');
const fontsDir = path.join(NM, 'katex/dist/fonts');
let css = fs.readFileSync(cssPath, 'utf8');
// 去掉 woff / ttf 备选,只保留 woff2(Chromium 全支持),减小体积
css = css.replace(/,\s*url\(fonts\/[^)]+\.woff\)\s*format\('woff'\)/g, '');
css = css.replace(/,\s*url\(fonts\/[^)]+\.ttf\)\s*format\('truetype'\)/g, '');
const cache = {};
css = css.replace(/url\(fonts\/([^)]+?)\)/g, (m, file) => {
const base = file.replace(/\.(woff2|woff|ttf)$/, '');
const f = path.join(fontsDir, base + '.woff2');
if (!fs.existsSync(f)) return m;
if (!cache[base]) cache[base] = 'data:font/woff2;base64,' + fs.readFileSync(f).toString('base64');
return `url(${cache[base]})`;
});
return css;
}
/* ------------------------------ 公式保护 / 渲染 ------------------------------ */
const PUA_S = '\uE000';
const PUA_E = '\uE001';
function renderTex(tex, display) {
try {
return katex.renderToString(tex.trim(), {
displayMode: !!display, throwOnError: false, strict: false, trust: false,
macros: { '\\d': '\\mathrm{d}' }
});
} catch (e) {
return `<span class="tex-err" title="${String(e.message).replace(/"/g, '&quot;')}">${tex}</span>`;
}
}
/** 把 $..$ / $$..$$ 换成占位符,返回 {text, store} */
function protectMath(src) {
const store = [];
let out = '';
let i = 0;
const push = (tex, display) => {
const id = store.length;
store.push(renderTex(tex, display));
return PUA_S + id + PUA_E;
};
while (i < src.length) {
const c = src[i];
if (c === '\\' && src[i + 1] === '$') { out += '\\$'; i += 2; continue; }
if (c === '$' && src[i + 1] === '$') {
const end = src.indexOf('$$', i + 2);
if (end !== -1) { out += push(src.slice(i + 2, end), true); i = end + 2; continue; }
}
if (c === '$') {
let j = i + 1, close = -1;
while (j < src.length && src[j] !== '\n') {
if (src[j] === '\\') { j += 2; continue; }
if (src[j] === '$') { close = j; break; }
j++;
}
if (close !== -1 && close > i + 1) { out += push(src.slice(i + 1, close), false); i = close + 1; continue; }
}
out += c; i++;
}
return { text: out, store };
}
function restoreMath(html, store) {
return html.replace(new RegExp(PUA_S + '(\\d+)' + PUA_E, 'g'), (m, id) => store[+id] || '');
}
/* ------------------------------ Markdown 预处理 ------------------------------ */
function stripFrontmatter(md) {
const m = md.match(/^---\r?\n[\s\S]*?\r?\n---\r?\n?/);
return m ? md.slice(m[0].length) : md;
}
/** Obsidian 双链 [[x|y]] / [[x]] -> 纯文本 */
function unlinkWikilinks(s) {
return s.replace(/\[\[([^\]|]+)(?:\|([^\]]+))?\]\]/g, (m, a, b) => (b || a));
}
/* ------------------------------ HTML 模板 ------------------------------ */
function pageCss() {
return `
@page { size: A4; }
* { box-sizing: border-box; }
html, body { margin: 0; padding: 0; }
body {
font-family: "Microsoft YaHei", "PingFang SC", "Hiragino Sans GB", "Segoe UI Emoji", "Segoe UI Symbol", sans-serif;
font-size: 11.4pt; line-height: 1.78; color: #14181f;
-webkit-print-color-adjust: exact; print-color-adjust: exact;
}
.doc > *:first-child { margin-top: 0; }
h1 { font-size: 17pt; line-height: 1.4; margin: 0 0 3mm; letter-spacing: .3px; }
h2 { font-size: 13.6pt; margin: 7mm 0 3mm; padding-bottom: 1.6mm; border-bottom: 1.6px solid #2b4a7d; color: #17325c; break-after: avoid; page-break-after: avoid; }
h3 { font-size: 12.2pt; margin: 5mm 0 2mm; color: #1f3763; break-after: avoid; page-break-after: avoid; }
h4 { font-size: 11.6pt; margin: 4mm 0 1.5mm; color: #2b4368; break-after: avoid; page-break-after: avoid; }
p { margin: 1.6mm 0; }
ul, ol { margin: 1.6mm 0; padding-left: 6.5mm; }
li { margin: .9mm 0; }
blockquote { margin: 2.4mm 0; padding: 1.6mm 3.2mm; border-left: 3px solid #9fb6d6; background: #f3f6fb; color: #24313f; border-radius: 0 3px 3px 0; }
blockquote p { margin: .8mm 0; }
hr { border: none; border-top: 1px solid #d5dde8; margin: 4.5mm 0; }
table { border-collapse: collapse; width: 100%; margin: 2.6mm 0; font-size: 10.4pt; break-inside: avoid; page-break-inside: avoid; }
th, td { border: 1px solid #c2cddd; padding: 1.3mm 2.2mm; text-align: left; vertical-align: top; }
th { background: #eaf0f8; font-weight: 700; color: #17325c; }
code { font-family: Consolas, "Courier New", monospace; font-size: .92em; background: #eef2f7; padding: 0 1px; border-radius: 2px; }
pre { background: #f5f7fa; border: 1px solid #dde4ee; border-radius: 4px; padding: 2.4mm; font-size: 9.6pt; overflow-x: auto; break-inside: avoid; }
strong { color: #0f1720; }
img { max-width: 100%; }
/* 公式 */
.katex { font-size: 1.04em; }
.katex-display { margin: 2.4mm 0 !important; overflow-x: auto; overflow-y: hidden; padding: 1px 0; }
.katex-display > .katex { white-space: normal; }
.tex-err { color: #b00020; background: #ffe9ec; padding: 0 2px; }
/* 答题版 */
.q { break-inside: avoid; page-break-inside: avoid; margin: 0 0 5mm; }
.q-stem { }
.q-space { border: 1px dashed #b9c6d8; border-radius: 6px; margin-top: 3.4mm; background: repeating-linear-gradient(to bottom, #fff 0, #fff 9.4mm, #eef3f9 9.4mm, #eef3f9 9.5mm); }
.q-space.half { height: 88mm; }
.q-space.full { height: 178mm; }
.q-tag { display: inline-block; font-size: 8.2pt; color: #7c8aa0; border: 1px solid #cfd8e5; border-radius: 999px; padding: 0 2mm; margin-left: 2mm; vertical-align: 1px; }
.group-head { margin-top: 6mm; }
`;
}
function htmlShell(title, body) {
return `<!DOCTYPE html>
<html lang="zh-CN"><head><meta charset="utf-8"><title>${title.replace(/</g, '&lt;')}</title>
<style>${buildKatexCss()}</style>
<style>${pageCss()}</style>
</head><body><main class="doc">${body}</main></body></html>`;
}
/* ------------------------------ 渲染器 ------------------------------ */
function makeMd() {
return new MarkdownIt({ html: true, breaks: true, linkify: false, typographer: false });
}
function mdToHtml(md, store) {
const mdit = makeMd();
return restoreMath(mdit.render(md), store);
}
/* 试题答题版:按题切分,逐题留白 */
function buildAnswerBody(rawMd) {
const lines = unlinkWikilinks(stripFrontmatter(rawMd)).split(/\r?\n/);
const blocks = []; // {type:'md'|'q', group, num, text}
let buf = [];
let group = { level: 2, title: '' };
let cur = null;
const flushMd = () => { if (buf.join('\n').trim()) blocks.push({ type: 'md', text: buf.join('\n') }); buf = []; };
const flushQ = () => { if (cur) { cur.text = cur.text.join('\n').trim(); blocks.push(cur); cur = null; } };
for (const line of lines) {
const gh = line.match(/^##\s+(.*)$/);
const qh = line.match(/^\*\*(\d+)\.\*\*\s*(.*)$/);
if (gh) { flushQ(); flushMd(); group = { level: 2, title: gh[1] }; buf.push(line); continue; }
if (qh) { flushQ(); flushMd(); cur = { type: 'q', group: group.title, num: +qh[1], text: [line] }; continue; }
if (cur) cur.text.push(line); else buf.push(line);
}
flushQ(); flushMd();
// 组名里含 C/拔高 或 B/中等 -> 整页留白;A/基础 -> 半页
const spaceOf = (g) => (/C\s*组|拔高|★★★/.test(g) ? 'full' : /B\s*组|中等|★★☆/.test(g) ? 'full' : 'half');
const out = [];
for (const b of blocks) {
const { text, store } = protectMath(b.text);
if (b.type === 'md') { out.push(mdToHtml(text, store)); continue; }
const html = mdToHtml(text, store);
const sp = spaceOf(b.group);
out.push(
`<section class="q">${html}` +
`<div class="q-space ${sp}"></div></section>`
);
}
return out.join('\n');
}
/* 模拟卷打印版:客观题不留白(答案写在括号/横线里),解答题按分值留白并独占一页 */
function buildExamBody(rawMd) {
const lines = unlinkWikilinks(stripFrontmatter(rawMd)).split(/\r?\n/);
const blocks = [];
let buf = [];
let group = { title: '' };
let cur = null;
const flushMd = () => { if (buf.join('\n').trim()) blocks.push({ type: 'md', text: buf.join('\n') }); buf = []; };
const flushQ = () => { if (cur) { cur.text = cur.text.join('\n').trim(); blocks.push(cur); cur = null; } };
for (const line of lines) {
const gh = line.match(/^##\s+(.*)$/);
const qh = line.match(/^\*\*(\d+)\.\*\*\s*(.*)$/);
if (gh) { flushQ(); flushMd(); group = { title: gh[1] }; buf.push(line); continue; }
if (qh) { flushQ(); flushMd(); cur = { type: 'q', group: group.title, num: +qh[1], text: [line] }; continue; }
if (cur) cur.text.push(line); else buf.push(line);
}
flushQ(); flushMd();
const BRK = 'break-before:page;page-break-before:always;';
const out = [];
let pendingBreak = false;
for (const b of blocks) {
const { text, store } = protectMath(b.text);
if (b.type === 'md') {
const html = mdToHtml(text, store);
// 部分边界(解答题、交卷后)另起一页;标题与紧接着的首题留在同一页
if (/^##\s/.test(b.text.trim()) && /解答题|交卷后/.test(b.text)) {
out.push(`<div style="${BRK}">${html}</div>`);
pendingBreak = true;
} else {
out.push(html);
}
continue;
}
const html = mdToHtml(text, store);
if (/选择题/.test(b.group)) { out.push(`<section class="q">${html}</section>`); continue; }
if (/填空题/.test(b.group)) { out.push(`<section class="q" style="min-height:10mm">${html}</section>`); continue; }
const brk = pendingBreak ? '' : BRK;
pendingBreak = false;
// 解答题:每题独占一页,留白框弹性撑满剩余高度(短题干就多给纸)
out.push(
`<section class="q" style="${brk}display:flex;flex-direction:column;min-height:245mm;">${html}` +
`<div class="q-space" style="flex:1 1 auto;min-height:70mm"></div></section>`
);
}
return out.join('\n');
}
/* 普通版 */
function buildPlainBody(rawMd) {
const { text, store } = protectMath(unlinkWikilinks(stripFrontmatter(rawMd)));
return mdToHtml(text, store);
}
/* ------------------------------ 主流程 ------------------------------ */
(async () => {
const inPath = path.resolve(ARGS.in);
const outPath = path.resolve(ARGS.out);
const raw = fs.readFileSync(inPath, 'utf8');
const title = ARGS.title || path.basename(inPath, '.md');
const body = MODE === 'answer' ? buildAnswerBody(raw)
: MODE === 'exam' ? buildExamBody(raw)
: buildPlainBody(raw);
const html = htmlShell(title, body);
const buildDir = path.join(__dirname, 'build');
fs.mkdirSync(buildDir, { recursive: true });
fs.mkdirSync(path.dirname(outPath), { recursive: true });
const tmpHtml = path.join(buildDir, path.basename(outPath).replace(/\.pdf$/i, '.html'));
fs.writeFileSync(tmpHtml, html, 'utf8');
const footer = `<div style="width:100%;font-size:8pt;color:#98a4b5;padding:0 12mm;font-family:'Microsoft YaHei',sans-serif;display:flex;justify-content:space-between;">
<span>${(ARGS.subtitle || title).replace(/</g, '&lt;')}</span>
<span><span class="pageNumber"></span> / <span class="totalPages"></span></span></div>`;
const browser = await puppeteer.launch({
executablePath: EDGE,
headless: 'new',
args: ['--no-sandbox', '--disable-gpu', '--allow-file-access-from-files', '--font-render-hinting=none'],
});
try {
const page = await browser.newPage();
await page.goto('file:///' + tmpHtml.replace(/\\/g, '/'), { waitUntil: 'load', timeout: 120000 });
await page.emulateMediaType('print');
await page.pdf({
path: outPath, format: 'A4', printBackground: true, preferCSSPageSize: true,
displayHeaderFooter: true, headerTemplate: '<div></div>', footerTemplate: footer,
margin: { top: '12mm', bottom: '14mm', left: '13mm', right: '13mm' },
});
const st = fs.statSync(outPath);
console.log(`OK ${path.basename(outPath)} ${(st.size / 1024).toFixed(0)} KB [mode=${MODE}]`);
} finally {
await browser.close();
}
})().catch(e => { console.error('FAIL:', e); process.exit(1); });