Repository navigation
Expand file tree
/
Copy pathindex.js
More file actions
142 lines (122 loc) · 4.86 KB
/
Copy pathindex.js
File metadata and controls
142 lines (122 loc) · 4.86 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
"use strict";
import path from "path";
import fs from "fs";
import MersenneTwister from "mersenne-twister";
import PDFDocument from "pdfkit-table";
import { Book, books } from "./book.js";
const clamp = (v, low, high) => Math.min(Math.max(v, low), high);
const minmax = (x, y) => [Math.min(x, y), Math.max(x, y)];
export async function fetchFont() {
const ttf = path.join(import.meta.dirname, ".cache", "BIZUDPGothic-Regular.ttf");
try {
await fs.promises.access(ttf);
} catch (e) {
const URL =
"https://github.com/googlefonts/morisawa-biz-ud-gothic/raw/refs/heads/main/fonts/ttf/BIZUDPGothic-Regular.ttf";
console.log(`モリサワの BIZ UD ゴシックを ${URL} からダウンロード中...`);
const font = await (await fetch(URL)).arrayBuffer();
await fs.promises.mkdir(path.dirname(ttf), { recursive: true });
await fs.promises.writeFile(ttf, Buffer.from(font));
}
return ttf;
}
export async function generateExam(
words,
id,
name = "英単語テスト",
range0 = Infinity,
range1 = 1,
num = 50,
seed = null,
) {
const [left, right] = minmax(clamp(range0, 1, words.length), clamp(range1, 1, words.length));
const n = clamp(num, 1, right - left + 1);
const s = seed || Math.floor(Math.random() * 0xffff) + 1;
const mt19937 = new MersenneTwister(s);
const seedStr = s.toString(16).toUpperCase().padStart(4, "0");
const defaultFileName = `enwords-${id}-${left.toString().padStart(4, "0")}-${right.toString().padStart(4, "0")}-${n.toString().padStart(3, "0")}-${seedStr}.pdf`;
const title = `${name} ${left}\u{FF5E}${right} (SEED:${seedStr})`;
const w = words
.map((word) => ({ ...word, r: mt19937.random() }))
.filter((word) => word.id >= left && word.id <= right)
.sort((a, b) => a.r - b.r)
.slice(0, n);
return {
defaultFileName,
title,
en2jp: w.map(({ id, en, jp }) => [`${id}`, en, "\u{3000}".repeat(jp.length)]),
jp2en: w.map(({ id, en, jp }) => [
`${id}`,
en.match(/\s/) ? `\n${en.replace(/(?<=\w)\w/g, "___")}\n\n` : `(${en[0]})`,
jp,
]),
answer: w.map(({ id, en, jp }) => [`${id}`, en, jp]),
};
}
export async function writePDF(exam, stream = null) {
const doc = new PDFDocument({ margin: 16, size: "A4" });
if (stream) doc.pipe(stream);
doc.info.Title = exam.title;
doc.font(await fetchFont());
const n = exam.answer.length;
let isLeft = true;
for (const name of ["en2jp", "jp2en", "answer"]) {
if (!isLeft) doc.addPage();
doc
.fontSize(16)
.text(`\n${exam.title}【${{ en2jp: `和訳編`, jp2en: `英訳編`, answer: `解答編` }[name]}】`, { align: "center" });
doc.fontSize(9).text(`\n\n${name === "answer" ? n * 2 : ""}/${n * 2}\n`, { align: "right" });
const wordAlign = name === "jp2en" ? "left" : "center";
const headerCommon = { valign: "center", headerColor: "white" };
const headers = [
{ label: "番号", width: 30, align: "right", ...headerCommon },
{ label: "単語・熟語", width: 100, align: wordAlign, ...headerCommon },
{ label: "意味", width: 150, align: "left", ...headerCommon },
{ label: "番号", width: 30, align: "right", ...headerCommon },
{ label: "単語・熟語", width: 100, align: wordAlign, ...headerCommon },
{ label: "意味", width: 150, align: "left", ...headerCommon },
];
const minRowHeight = clamp(560 / Math.ceil(exam[name].length / 2), 20, 40);
// pdfkit-table 0.2 は既定でページ残り 10% 未満になると改ページするため、
// 1 行分 (+ 余白) が収まらなくなったときだけ改ページするよう閾値を指定する
const pageContentHeight = doc.page.height - doc.page.margins.top - doc.page.margins.bottom;
const endOfPageThreshold = (minRowHeight + 16) / pageContentHeight;
const rows = exam[name]
.reduce(
(rows, row) =>
rows.length === 0 || rows.at(-1).length >= 6
? [...rows, row]
: [...rows.slice(0, rows.length - 1), [...rows.at(-1), ...row]],
[],
)
.map((row) => [...row, ...new Array(6 - row.length)]);
await doc.table(
{ headers, rows },
{
divider: {
header: { disabled: false, width: 1, opacity: 1.0 },
horizontal: { disabled: false, width: 0.5, opacity: 1.0 },
vertical: { disabled: false, width: 0.25, opacity: 1.0 },
},
padding: 4,
minRowHeight,
endOfPageThreshold,
prepareHeader: () => doc.fontSize(10),
prepareRow: (row, i, _j, _rectRow, { x, y, width, height }) => {
(i === 0 ? [0, width] : [width]).forEach((dx) =>
doc
.lineWidth(0.5)
.moveTo(x + dx, y)
.lineTo(x + dx, y + height)
.stroke(),
);
doc.fontSize([7, 9, 8][i % 3]);
},
},
);
isLeft = false;
}
doc.end();
return doc;
}
export { Book, books };