加 PDF 构建:pandoc 转 typst 排版,A4 按书排,目录带页码、书签到条目级

This commit is contained in:
albert4719
2026-09-19 09:41:13 +08:00
parent e374f486c2
commit 260bdde2df
2 changed files with 171 additions and 0 deletions
+97
View File
@@ -0,0 +1,97 @@
// 把 README + book/*.md + docs/*.md 排成一本 PDF:pandoc 把 Markdown 转成 typst,typst 排版。
// 用法:node tools/pdf/build.mjs [输出路径] 默认输出 dist/HowToLiveBetter.pdf
// 需要 pandoc(≥3.1,要有 typst 输出)和 typst(≥0.13)在 PATH 上,或用环境变量 PANDOC、TYPST 指路径。
// 版面在 tools/pdf/template.typ 里;正文一个字都不改,只做三件事:
// 去掉「← 回总目录」、给每节的标题挂上锚点、把仓库内的链接改成书内跳转或 GitHub 网址。
import { writeFileSync, mkdirSync, statSync } from 'node:fs';
import { resolve, dirname, posix, basename } from 'node:path';
import { execFileSync } from 'node:child_process';
import { ROOT, REPO, SITE, TITLE, read, readBook, gitCommit, stripBackLink } from '../lib/book.mjs';
const OUT = resolve(ROOT, process.argv[2] ?? 'dist/HowToLiveBetter.pdf');
const WORK = resolve(ROOT, 'dist/pdf-build.md');
const PANDOC = process.env.PANDOC ?? 'pandoc';
const TYPST = process.env.TYPST ?? 'typst';
const DATE = new Date().toISOString().slice(0, 10);
const COMMIT = gitCommit();
const { description, frontMd, contentsMd, bookFiles, docFiles } = readBook();
// ---------- 页(每页一个一级标题,一级标题在 typst 里另起一页) ----------
const anchorOf = new Map();
bookFiles.forEach(f => anchorOf.set(f, 'sec-' + (basename(f).match(/^\d+/)?.[0] ?? anchorOf.size + 1)));
docFiles.forEach((f, i) => anchorOf.set(f, `doc-${i + 1}`));
const pages = [
{ src: 'README.md', md: `# 前言\n\n${description}\n\n${frontMd}`, anchor: 'front' },
{ src: 'README.md', md: contentsMd.replace(/^## 目录/, '# 各节简介'), anchor: 'contents' },
...[...bookFiles, ...docFiles].map(src => ({ src, md: stripBackLink(read(src)), anchor: anchorOf.get(src) })),
{ src: 'README.md', md: aboutMd(), anchor: 'about' },
];
function aboutMd() {
const commitLine = COMMIT ? `- 对应提交:${COMMIT.slice(0, 7)}\n` : '';
return `# 版本说明
这本 PDF 由仓库里的 Markdown 正文自动排版,正文一改就重新排一本。手里这本的版本:
- 生成日期:${DATE}
${commitLine}- 最新版下载、在线检索、提意见:${REPO}
- 在线检索页(按关键词、章节、证据等级和成本筛选,也能存成单文件离线看):${SITE}
正文里指向书内其他节的链接已改成书内跳转;指向核实记录、许可证这类没排进书的文件的链接改成了 GitHub 网址。
全书以 Unlicense 发布,属于公有领域,可以随意复制、修改、分发。`;
}
// ---------- 链接:书内的改成锚点,书外的改成绝对网址 ----------
function rewriteLinks(md, src) {
return md.replace(/\]\(([^)\s]+)(\s+"[^"]*")?\)/g, (all, href, title) => {
if (/^(https?:|mailto:)/.test(href)) return all;
// README 里指向自身小节的锚点(#目录 这种)在书里不一定有,指回 GitHub 上的 README
if (href.startsWith('#')) return `](${REPO}/blob/main/README.md${href}${title ?? ''})`;
const [path] = href.split('#');
const target = posix.normalize(posix.join(posix.dirname(src), path));
const anchor = anchorOf.get(target);
if (anchor) return `](#${anchor}${title ?? ''})`;
const kind = target.endsWith('/') ? 'tree' : 'blob';
return `](${REPO}/${kind}/main/${target}${title ?? ''})`;
});
}
const body = pages.map(p => {
const md = rewriteLinks(p.md, p.src)
.replace(/<!--[\s\S]*?-->/g, '') // 成本标签这类 HTML 注释不进 PDF
.replace(/^(# .+?)\s*$/m, `$1 {#${p.anchor}}`); // 给这一页的一级标题挂锚点
if (!md.includes(`{#${p.anchor}}`)) throw new Error(`${p.src} 里没找到一级标题,挂不上锚点`);
return md.trim();
}).join('\n\n');
mkdirSync(dirname(OUT), { recursive: true });
writeFileSync(WORK, body);
// ---------- pandoc → typst → pdf ----------
const run = (cmd, args) => {
try {
return execFileSync(cmd, args, { cwd: ROOT, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] });
} catch (err) {
if (err.code === 'ENOENT') throw new Error(`找不到 ${cmd},装上它或用环境变量 ${cmd === PANDOC ? 'PANDOC' : 'TYPST'} 指到可执行文件`);
throw new Error(`${cmd} 失败:\n${err.stderr || err.stdout || err.message}`);
}
};
const typFile = resolve(ROOT, 'dist/pdf-build.typ');
run(PANDOC, [
'--from=gfm+attributes', '--to=typst', '--wrap=none',
`--template=${resolve(ROOT, 'tools/pdf/template.typ')}`,
'-V', `booktitle=${TITLE}`, '-V', `subtitle=${description}`,
'-V', `builddate=${DATE}`, '-V', `commit=${COMMIT.slice(0, 7) || '未知'}`,
'-V', `site=${SITE}`, '-V', `repo=${REPO}`,
'-o', typFile, WORK,
]);
const log = run(TYPST, ['compile', typFile, OUT, '--root', ROOT]);
if (log.trim()) console.log(log.trim());
const entries = pages.filter(p => bookFiles.includes(p.src))
.reduce((n, p) => n + p.md.split('\n').filter(l => l.startsWith('### ')).length, 0);
console.log(`已生成 ${OUT}:${bookFiles.length} 节 ${entries} 条,附录 ${docFiles.length} 篇,${(statSync(OUT).size / 1048576).toFixed(1)} MB`);
+74
View File
@@ -0,0 +1,74 @@
$--
$-- pandoc 的 typst 模板(只认 $body$ 和几个 -V 变量),不用 pandoc 自带的 conf():
$-- 自带模板把页面设置锁在 conf() 里,改不了页眉页脚,所以这里自己排。
$-- 开头到 divider 那段是 pandoc 生成的正文要用的辅助定义,照抄自 `pandoc -D typst`,别删。
$--
#set terms(hanging-indent: 1.5em)
#set table(inset: 6pt, stroke: none)
// pandoc 把表格塞进 align(center) 里,单元格会跟着居中,中文表格左对齐才好读
#show table.cell: it => align(left, it)
#let horizontalRule = line(start: (25%, 0%), end: (75%, 0%))
#let divider = if "divider" in std { divider } else { horizontalRule }
#show figure.where(kind: table): set figure.caption(position: top)
#show figure.where(kind: image): set figure.caption(position: bottom)
// 长表格要能跨页,否则整块挤不下就留一页白
#show figure: set block(breakable: true)
#set smartquote(enabled: false)
// ---------- 版面 ----------
#set document(title: "$booktitle$", author: "eternity4719")
#set text(
// 西文用 typst 自带的 Libertinus,中文按可用性往后找:CI 上是 Noto,本机是雅黑
font: ("Libertinus Serif", "Noto Serif CJK SC", "Noto Serif SC", "Source Han Serif SC", "Noto Sans CJK SC", "Microsoft YaHei", "SimSun"),
size: 10.5pt, lang: "zh", region: "cn",
)
#set par(justify: false, leading: 0.78em, spacing: 0.9em)
#set list(indent: 0.6em, spacing: 0.75em)
#show raw: set text(font: ("DejaVu Sans Mono", "Noto Sans Mono CJK SC", "Consolas"), size: 9pt)
#show link: set text(fill: rgb("#1a4fb4"))
#show heading: set block(sticky: true, above: 1.5em, below: 0.65em)
#show heading.where(level: 1): set text(19pt)
#show heading.where(level: 2): set text(14pt)
#show heading.where(level: 3): set text(11.5pt)
// 每节另起一页;weak 保证前一页正好排满时不多出一张空页
#show heading.where(level: 1): it => { pagebreak(weak: true); it }
// 页眉:左边书名,右边当前节名;一节的头一页不打页眉
#let running-head = context {
let next = query(selector(heading.where(level: 1)).after(here())).at(0, default: none)
if next != none and next.location().page() == here().page() { return }
let seen = query(selector(heading.where(level: 1)).before(here()))
if seen.len() == 0 { return }
set text(8.5pt, fill: luma(120))
grid(columns: (1fr, auto), align(left)[$booktitle$], align(right)[#seen.last().body])
v(-7pt)
line(length: 100%, stroke: 0.4pt + luma(215))
}
// ---------- 封面 ----------
#set page(paper: "a4", margin: (x: 2.2cm, top: 2.2cm, bottom: 2cm), header: none, footer: none)
#align(center + horizon)[
#image("/og.png", width: 100%)
#v(1.2cm)
#block(width: 80%)[#text(11.5pt, fill: luma(60))[$subtitle$]]
#v(2cm)
#text(10pt, fill: luma(90))[
生成于 $builddate$ · 正文提交 $commit$ \
正文每天都在改,以在线版为准:$site$ \
在线检索、EPUB 与本 PDF 的最新版都在 $repo$
]
]
// ---------- 目录 ----------
#pagebreak()
#outline(title: [目录], depth: 1, indent: 1em)
// ---------- 正文 ----------
#pagebreak(weak: true)
#set page(header: running-head, footer: context align(center, text(8.5pt, fill: luma(120))[#counter(page).at(here()).first() / #counter(page).final().first()]))
#counter(page).update(1)
$body$