feat(在学练习): 概率论第5讲(大数定律与CLT)+第6讲(数理统计) 整套;第3讲中高难度卷;md2pdf 工具链
新增 - 在学练习/概率论-第5讲-大数定律与中心极限定理/:README + 01考点手册 + 02试题(16题) + 03解析 + PDF×3 - 在学练习/概率论-第6讲-数理统计/:README + 01考点手册 + 02试题(18题) + 03解析 + PDF×3 - 在学练习/概率论-第3讲.../05-试题-中高难度.md、06-解析-中高难度.md + 平板版 PDF×6(四件套 + 中高难度) - .workbuddy/tools/md2pdf/:md2pdf.js(Markdown→KaTeX→Edge 无头打印 A4,含 answer 留白模式)、shot.js(渲染验收截图) - .workbuddy/memory/:2026-10-14.md、2026-10-16.md、MEMORY.md 更新 - .gitignore:新增忽略 md2pdf/build/(HTML 内联字体,体积大) - 总览.md:目录树同步(第5/6讲、第3讲中高难度卷、PDF 清单) - 第3讲 01-考点手册/02-试题/README:中高难度卷接入与索引回填 说明:PDF 为 KaTeX 矢量公式渲染的平板书写版(试题逐题留白),由 md2pdf.js 从 .md 可重建。
This commit is contained in:
@@ -0,0 +1,259 @@
|
||||
#!/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' : '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, '"')}">${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, '<')}</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 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) : 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, '<')}</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); });
|
||||
@@ -0,0 +1,21 @@
|
||||
'use strict';
|
||||
const path = require('path');
|
||||
const fs = require('fs');
|
||||
const NM = 'C:/Users/Wang Ling/.workbuddy/binaries/node/workspace/node_modules';
|
||||
const puppeteer = require(path.join(NM, 'puppeteer-core'));
|
||||
const EDGE = 'C:/Program Files (x86)/Microsoft/Edge/Application/msedge.exe';
|
||||
|
||||
(async () => {
|
||||
const html = process.argv[2];
|
||||
const outPng = process.argv[3];
|
||||
const startPx = parseInt(process.argv[4] || '0', 10);
|
||||
const heightPx = parseInt(process.argv[5] || '1123', 10);
|
||||
const browser = await puppeteer.launch({ executablePath: EDGE, headless: 'new', args: ['--no-sandbox', '--allow-file-access-from-files'] });
|
||||
const page = await browser.newPage();
|
||||
await page.setViewport({ width: 794, height: 1123, deviceScaleFactor: 1.6 });
|
||||
await page.goto('file:///' + path.resolve(html).replace(/\\/g, '/'), { waitUntil: 'load', timeout: 120000 });
|
||||
const total = await page.evaluate(() => document.body.scrollHeight);
|
||||
await page.screenshot({ path: outPng, clip: { x: 0, y: startPx, width: 794, height: Math.min(heightPx, total - startPx) } });
|
||||
console.log('html height px =', total, ' -> screenshot', outPng);
|
||||
await browser.close();
|
||||
})().catch(e => { console.error(e); process.exit(1); });
|
||||
Reference in New Issue
Block a user