#!/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 `${tex}`; } } /** 把 $..$ / $$..$$ 换成占位符,返回 {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 `