feat: 支持试卷与错题打印页导出 DOCX 文档

This commit is contained in:
margrop
2026-11-01 22:14:43 +08:00
parent 70e3714d35
commit 4eefc1bb77
12 changed files with 949 additions and 17 deletions

View File

@@ -99,7 +99,7 @@ Generated exams keep each source question's ID and show every attempt, so you ca
![An English demo exam with source IDs and sample results from multiple attempts](doc/screenshots/en/exam.png)
The print preview can include an answer page and sets the answer space below each question: automatic by question type (less for fill-in, choice and true/false questions, more for worked problems with extra room per sub-question) or a fixed none, small, medium or large; download it as HTML, print it, or save it as PDF from the browser.
The print preview can include an answer page and sets the answer space below each question: automatic by question type (less for fill-in, choice and true/false questions, more for worked problems with extra room per sub-question), a fixed none, small, medium or large, or manual per-question adjustment; export it as Word (DOCX), download it as HTML, print it, or save it as PDF from the browser.
![An English exam print preview with source IDs, answer page toggle and export options](doc/screenshots/en/exam-print.png)
@@ -158,7 +158,7 @@ Practice statistics show total practice, accuracy and active months, with distri
- **📈 Mastery probability**: AI estimates how likely you have mastered each question from the answer history of practice and exams. Questions fall into three states: **To Review** (no practice records yet), **Reviewing** (has records, probability below the mastered threshold) and **Mastered** (has records, probability at or above the threshold). The threshold is 50% by default and each user can adjust it in settings.
- **📅 Daily review**: each question is scheduled at Ebbinghaus intervals of 1, 2, 4, 7, 15 and 30 days. A correct answer moves it to the next interval; a wrong answer starts over. The **Review** page lists questions due today (earliest first), and the home page shows how many are due.
- **🧾 Mistake exams**: draw questions at random by notebook, knowledge point and mastery, and turn them into a printable exam of similar questions. After finishing, enter results per question; they are added to the original question's answer history.
- **🖨️ Print mistakes**: print filtered questions with your choice of question text or original image, answer, analysis and knowledge points, adjust image scale, then print or save as PDF.
- **🖨️ Print and export mistakes**: print filtered questions with your choice of question text or original image, answer, analysis and knowledge points, adjust image scale and global/per-question blank space, then print, save as PDF, or export as Word (DOCX).
### Management and statistics

View File

@@ -99,7 +99,7 @@
![已生成的真实错题试卷、来源 ID 和多次作答结果](doc/screenshots/exam.png)
打印预览可选择包含答案页,并设置每题下方的留白:按题型自动(填空、选择、判断题少留,解答题按小问数多留),或固定为不留白、小、中、大;支持下载 HTML、打印或通过浏览器保存为 PDF。
打印预览可选择包含答案页,并设置每题下方的留白:按题型自动(填空、选择、判断题少留,解答题按小问数多留),或固定为不留白、小、中、大,也可在单题下方手动调节留白高度;支持导出 Word(DOCX)、下载 HTML、打印或通过浏览器保存为 PDF。
![真实试卷的打印预览、来源 ID、答案页开关和导出入口](doc/screenshots/exam-print.png)
@@ -158,7 +158,7 @@
- **📈 掌握概率**:根据举一反三和试卷的作答历史,由 AI 评估每道题的已掌握概率。错题分为三种状态:没有举一反三记录的为「待复习」,有记录且掌握概率低于已掌握阈值的为「复习中」,达到阈值的为「已掌握」。阈值默认 50%,每个用户可在设置中单独调整。
- **📅 今日复习**:按 1、2、4、7、15、30 天的艾宾浩斯间隔安排每道错题的复习,做对进入下一轮间隔,做错从头开始。导航栏的「复习」页列出今天到期的错题(最早到期的在前),首页显示今日待复习数量。
- **🧾 错题试卷**:按错题本、知识点和掌握情况随机抽题,用举一反三生成一套可打印的试卷;做完后可按题录入结果,结果计入原题的作答历史。
- **🖨️ 错题打印**:筛选后打印错题,可选打印题目文字或原图、答案、解析、知识点,调节图片比例,可直接打印或保存为 PDF。
- **🖨️ 错题打印与导出**:筛选后打印错题,可选打印题目文字或原图、答案、解析、知识点,调节图片比例以及全局/单题留白高度,可直接打印、保存为 PDF 或导出为 Word(DOCX)文档。
### 管理与统计

View File

@@ -57,6 +57,7 @@
| 错题打印 | 对筛选结果打印,可选题目文字或原图、答案、解析、知识点及图片比例;不显示答案和解析时支持选择全局留白档位(按题型自动、不留白、小、中、大),并可在每道题下方通过滑块或 `-`/`+` 按钮单独手动微调留白高度(0~600 px) |
| 试卷打印 | 提供打印预览,可选择是否包含答案页,以及每题下方的留白:按题型自动(判断、选择、填空题约 0.3–0.4 cm,解答题约 6.3 cm,每多一个小问加约 3.2 cm,最多约 14.8 cm),或固定为不留白、小(约 1.6 cm)、中(约 3.2 cm)、大(约 6.3 cm),同时支持按题单独手动调节留白高度(0~600 px);全局模式选择会记在本机浏览器中。存在配图的试卷可按题逐个调整或全卷统一调整配图比例(10%~200%)与显示位置(居左/居中/居右,默认居中),保存后用于显示、打印与导出 |
| 下载 HTML | 保存试卷 HTML,再用浏览器打开 |
| 导出 Word (DOCX) | 在错题打印预览或试卷打印页一键导出 `.docx` 文档(包含题干、配图/原图、按当前设置生成的留白空行及答案解析),可在 Word / WPS 中自由编辑排版 |
| 保存 PDF | 在浏览器打印对话框中选择“保存为 PDF” |
打印前检查分页、公式和配图是否完整;纸张、缩放和页边距由浏览器打印设置控制。

View File

@@ -57,6 +57,7 @@ Exam papers keep the source question IDs so you can go back to the originals. Re
| Print questions | Prints the filtered questions, with question text or original image, answers, analysis, knowledge points and image scale as options; when answers and analysis are hidden, you can choose a global answer-space mode (auto by question type, none, small, medium, large) and manually adjust each question's blank space (0–600 px) via its slider or `-`/`+` buttons |
| Print exam papers | Print preview with an optional answer page and a choice of answer space below each question: automatic by question type (about 0.3–0.4 cm for true/false, choice and fill-in questions, about 6.3 cm for worked problems plus about 3.2 cm per extra sub-question, up to about 14.8 cm) or a fixed none, small (about 1.6 cm), medium (about 3.2 cm) or large (about 6.3 cm), plus per-question manual blank-space adjustment (0–600 px); the global mode is remembered in this browser. Exams with figures also allow adjusting figure scale (10–200%) and alignment (left / center / right, default center) per question or uniformly across the exam, saved for display, printing and backups |
| Download HTML | Save the exam paper as HTML and open it in a browser |
| Export Word (DOCX) | Export a `.docx` document from question print preview or exam print preview (including question text, figures/images, blank lines matching the current spacing settings, and answers/analyses) for free editing in Word or WPS |
| Save as PDF | Choose "Save as PDF" in the browser's print dialog |
Before printing, check page breaks, formulas and figures. Paper size, scaling and margins are controlled by the browser's print settings.

View File

@@ -0,0 +1,142 @@
import { describe, expect, it, vi } from "vitest";
import {
createDocxArchive,
docxFileName,
formatMathAndMarkdownForDocx,
rasterizeImageForDocx,
rasterizeSvgFigureForDocx,
triggerDocxDownload,
} from "@/lib/docx-export";
describe("formatMathAndMarkdownForDocx", () => {
it("转换分式、根式、上下标与常见数学几何符号", () => {
expect(formatMathAndMarkdownForDocx("计算 $\\frac{1}{2} + \\frac{x+1}{y-1}$"))
.toBe("计算 1/2 + (x+1)/(y-1)");
expect(formatMathAndMarkdownForDocx("$\\sqrt{5} + \\sqrt{x+1} + \\sqrt[3]{8}$"))
.toBe("√5 + √(x+1) + ³√8");
expect(formatMathAndMarkdownForDocx("$x^2 + y^{n+1} + a_1 + z^{abc}$"))
.toBe("x² + yⁿ⁺¹ + a₁ + z^(abc)");
expect(formatMathAndMarkdownForDocx("如图,$\\triangle ABC \\cong \\triangle DEF$,$\\angle A = 90^\\circ$"))
.toBe("如图,△ ABC ≌ △ DEF,∠ A = 90°");
expect(formatMathAndMarkdownForDocx("$a \\times b \\div c \\le d \\ge e \\neq 0 \\pm 1$"))
.toBe("a × b ÷ c ≤ d ≥ e ≠ 0 ± 1");
});
it("还原填空横线并剥离配图注释及 Markdown 标记", () => {
expect(
formatMathAndMarkdownForDocx(
"<!-- figure: 直角三角形 -->\n### 标题\n**重点**:当 $x = \\underline{\\quad}$ 时,结果为 \\_\\_\\_,或 $\\rule{2cm}{0.4pt}$。",
),
).toBe("标题\n重点:当 x = ______ 时,结果为 ___,或 ______。");
});
});
describe("docxFileName", () => {
it("过滤非法文件名字符并附加 .docx 后缀", () => {
expect(docxFileName("七年级数学:期中试卷/A卷")).toBe("七年级数学:期中试卷_A卷.docx");
expect(docxFileName(" ")).toBe("document.docx");
});
});
describe("createDocxArchive", () => {
it("生成合法的 OpenXML ZIP 归档,包含题干、图片、留白空行与独立答案页", () => {
const fakePng = new Uint8Array([137, 80, 78, 71, 13, 10, 26, 10]);
const archive = createDocxArchive({
title: "周末测试卷",
metaItems: ["姓名:________", "得分:________"],
questions: [
{
heading: "1.",
meta: "来源 ID: AB12CD",
questionText: "已知 $x^2 = 4$,求 $x$ 的值。",
image: {
data: fakePng,
extension: "png",
widthPx: 240,
heightPx: 120,
align: "center",
},
answerSpacePx: 120,
},
{
heading: "2.",
questionText: "1 + 1 = ____",
inlineAnswerLabel: "参考答案",
inlineAnswerText: "$2$",
inlineAnalysisLabel: "解析",
inlineAnalysisText: "基础加法",
answerSpacePx: 0,
},
],
answerKeyTitle: "参考答案与解析",
answerKey: [
{
heading: "1.",
meta: "来源 ID: AB12CD",
answerLabel: "答案",
answerText: "$x = \\pm 2$",
analysisLabel: "解析",
analysisText: "平方根定义",
},
],
});
// 检查 ZIP 魔数 PK\x03\x04 与结尾 EOCD 魔数 PK\x05\x06
expect(archive[0]).toBe(0x50);
expect(archive[1]).toBe(0x4b);
expect(archive[2]).toBe(0x03);
expect(archive[3]).toBe(0x04);
const text = new TextDecoder().decode(archive);
expect(text).toContain("[Content_Types].xml");
expect(text).toContain("word/document.xml");
expect(text).toContain("word/styles.xml");
expect(text).toContain("word/_rels/document.xml.rels");
expect(text).toContain("word/media/image1.png");
expect(text).toContain("周末测试卷");
expect(text).toContain("姓名:________");
expect(text).toContain("已知 x² = 4,求 x 的值。");
expect(text).toContain("x = ± 2");
expect(text).toContain("<w:pageBreakBefore/>");
expect(text).toContain('r:embed="rIdImg1"');
});
});
describe("rasterizeSvgFigureForDocx & triggerDocxDownload", () => {
it("空 SVG 返回 null,图片加载失败时优雅降级为 null", async () => {
expect(await rasterizeSvgFigureForDocx(null)).toBeNull();
expect(await rasterizeSvgFigureForDocx("")).toBeNull();
const OriginalImage = globalThis.Image;
class FailingImage {
onload: (() => void) | null = null;
onerror: (() => void) | null = null;
set src(_value: string) {
setTimeout(() => this.onerror?.(), 0);
}
}
globalThis.Image = FailingImage as unknown as typeof Image;
try {
const result = await rasterizeImageForDocx("https://example.com/broken.png");
expect(result).toBeNull();
} finally {
globalThis.Image = OriginalImage;
}
});
it("triggerDocxDownload 创建 Blob URL 并触发链接下载", () => {
const createObjectURL = vi.spyOn(URL, "createObjectURL").mockReturnValue("blob:mock-docx");
const revokeObjectURL = vi.spyOn(URL, "revokeObjectURL").mockImplementation(() => {});
const clickSpy = vi.spyOn(HTMLAnchorElement.prototype, "click").mockImplementation(() => {});
triggerDocxDownload(new Uint8Array([1, 2, 3]), "错题本导出");
expect(createObjectURL).toHaveBeenCalledTimes(1);
expect(clickSpy).toHaveBeenCalledTimes(1);
expect(revokeObjectURL).toHaveBeenCalledWith("blob:mock-docx");
createObjectURL.mockRestore();
revokeObjectURL.mockRestore();
clickSpy.mockRestore();
});
});

View File

@@ -1,5 +1,6 @@
import { describe, expect, it } from 'vitest';
import {
getPrintableItemTagNames,
getPrintPreviewCountLabel,
getPrintPreviewEmptyState,
getSelectedPrintItems,
@@ -36,4 +37,13 @@ describe('print preview helpers', () => {
expect(getPrintPreviewEmptyState(88, 0)).toBe('noSelection');
expect(getPrintPreviewEmptyState(88, 2)).toBeNull();
});
it('提取打印题目的知识点名称并兼容旧版 JSON 字符串', () => {
expect(getPrintableItemTagNames({ tags: [{ id: '1', name: '勾股定理' }], knowledgePoints: '["旧标签"]' }))
.toEqual(['勾股定理']);
expect(getPrintableItemTagNames({ tags: [], knowledgePoints: '["二次函数","配方法"]' }))
.toEqual(['二次函数', '配方法']);
expect(getPrintableItemTagNames({ tags: [], knowledgePoints: 'invalid-json' }))
.toEqual([]);
});
});

View File

@@ -14,6 +14,7 @@ import { AnswerSpaceControl } from "@/components/print-preview/answer-space-cont
import { useLanguage } from "@/contexts/LanguageContext";
import { usePageTitle } from "@/lib/page-title";
import { apiClient } from "@/lib/api-client";
import { createDocxArchive, rasterizeSvgFigureForDocx, triggerDocxDownload } from "@/lib/docx-export";
import { EXAM_PRINT_CSS, buildExamHtmlDocument, examFileName } from "@/lib/exam-print";
import {
ANSWER_SPACE_STORAGE_KEY,
@@ -33,6 +34,7 @@ export default function ExamPrintPage() {
const [includeAnswers, setIncludeAnswers] = useState(true);
const [answerSpace, setAnswerSpace] = useState<AnswerSpaceMode>(DEFAULT_ANSWER_SPACE_MODE);
const [customSpaces, setCustomSpaces] = useState<Record<string, number>>({});
const [exportingDocx, setExportingDocx] = useState(false);
const [uniformPreview, setUniformPreview] = useState<{ scale: number | null; align: FigureAlign | null }>({ scale: null, align: null });
const sheetRef = useRef<HTMLDivElement>(null);
@@ -108,6 +110,56 @@ export default function ExamPrintPage() {
URL.revokeObjectURL(url);
};
const downloadDocx = async () => {
if (exportingDocx) return;
setExportingDocx(true);
try {
const questionBlocks = await Promise.all(
questions.map(async (question, index) => {
const image = await rasterizeSvgFigureForDocx(
question.figureSvg,
uniformPreview.scale ?? question.figureScale,
uniformPreview.align ?? question.figureAlign,
);
return {
heading: `${index + 1}.`,
meta: `${t.exam.sourceLabel}: ${question.sourceShortId}`,
questionText: question.questionText ?? "",
image,
answerSpacePx: resolveQuestionAnswerSpacePx(
answerSpace,
question.questionText!,
customSpaces[question.id],
),
};
}),
);
const bytes = createDocxArchive({
title: paper.title,
metaItems: [
`${t.exam.nameLine}${t.common.colon}________`,
`${t.exam.dateLine}${t.common.colon}________`,
`${t.exam.scoreLine}${t.common.colon}________`,
],
questions: questionBlocks,
answerKeyTitle: t.exam.answerKey,
answerKey: includeAnswers
? questions.map((question, index) => ({
heading: `${index + 1}.`,
meta: `${t.exam.sourceLabel}: ${question.sourceShortId}`,
answerLabel: t.exam.answerLabel,
answerText: question.answerText ?? undefined,
analysisLabel: t.exam.analysisLabel,
analysisText: question.analysis ?? undefined,
}))
: undefined,
});
triggerDocxDownload(bytes, paper.title);
} finally {
setExportingDocx(false);
}
};
return (
<main className="min-h-screen bg-white">
<style>{EXAM_PRINT_CSS}</style>
@@ -139,11 +191,15 @@ export default function ExamPrintPage() {
</Button>
)}
</div>
<div className="flex gap-2 sm:ml-auto">
<div className="flex flex-wrap gap-2 sm:ml-auto">
<Button variant="outline" size="sm" onClick={downloadHtml}>
<Download className="mr-2 h-4 w-4" />
{t.exam.downloadHtml}
</Button>
<Button variant="outline" size="sm" onClick={downloadDocx} disabled={exportingDocx}>
<Download className="mr-2 h-4 w-4" />
{exportingDocx ? t.exam.exportingDocx : t.exam.downloadDocx}
</Button>
<Button size="sm" onClick={() => window.print()}>
<Printer className="mr-2 h-4 w-4" />
{t.exam.printNow}

View File

@@ -2,6 +2,7 @@
import { useEffect, useState, Suspense, useCallback } from "react";
import { useSearchParams } from "next/navigation";
import { Download } from "lucide-react";
import { Button } from "@/components/ui/button";
import { BackButton } from "@/components/ui/back-button";
import { PrintItemPicker } from "@/components/print-preview/print-item-picker";
@@ -10,15 +11,24 @@ import { PrintableQuestion } from "@/components/print-preview/printable-question
import { apiClient } from "@/lib/api-client";
import type { PaginatedResponse, PrintableErrorItem } from "@/types/api";
import { useLanguage } from "@/contexts/LanguageContext";
import {
createDocxArchive,
rasterizeImageForDocx,
rasterizeSvgFigureForDocx,
triggerDocxDownload,
} from "@/lib/docx-export";
import { resolveQuestionAnswerSpacePx } from "@/lib/exam-answer-space";
import { usePageTitle } from "@/lib/page-title";
import { PRINT_PREVIEW_PAGE_SIZE } from "@/lib/constants/pagination";
import { frontendLogger } from "@/lib/frontend-logger";
import {
getPrintableItemTagNames,
getPrintPreviewCountLabel,
getPrintPreviewEmptyState,
getSelectedPrintItems,
shouldReserveAnswerSpace,
} from "@/lib/print-preview";
import { usePaperGroups } from "@/lib/use-paper-groups";
function PrintPreviewContent() {
const searchParams = useSearchParams();
@@ -37,6 +47,8 @@ function PrintPreviewContent() {
const updateOptions = (patch: Partial<PrintDisplayOptions>) => setOptions((prev) => ({ ...prev, ...patch }));
const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());
const [customSpaces, setCustomSpaces] = useState<Record<string, number>>({});
const [exportingDocx, setExportingDocx] = useState(false);
const { groups: paperGroups } = usePaperGroups();
const setQuestionCustomSpace = (id: string, px: number | null) => {
setCustomSpaces((prev) => {
@@ -78,6 +90,64 @@ function PrintPreviewContent() {
const countLabel = getPrintPreviewCountLabel(items.length, selectedItems.length);
const emptyState = getPrintPreviewEmptyState(items.length, selectedItems.length);
const handleExportDocx = async () => {
if (exportingDocx || selectedItems.length === 0) return;
setExportingDocx(true);
try {
const questionBlocks = await Promise.all(
selectedItems.map(async (item, index) => {
const tags = getPrintableItemTagNames(item);
const paperGroupName = item.paperLevel
? paperGroups.find((g) => g.id === item.paperLevel)?.name || item.paperLevel
: null;
const metaParts = [
item.shortId ? t.printPreview.source.replace("{id}", item.shortId) : null,
item.subject?.name ?? null,
item.gradeSemester ?? null,
paperGroupName ? `${t.printPreview.paperLevel}: ${paperGroupName}` : null,
options.showTags && tags.length > 0 ? `${t.printPreview.knowledgePoints}: ${tags.join("、")}` : null,
].filter((part): part is string => Boolean(part));
const useTextMode = Boolean(options.showQuestionText && item.questionText);
const image = useTextMode
? await rasterizeSvgFigureForDocx(item.figureSvg, item.figureScale, item.figureAlign)
: (item.originalImageUrl
? await rasterizeImageForDocx(item.originalImageUrl, {
scalePercent: options.imageScale,
maxBaseWidthPx: 560,
align: "left",
})
: null);
return {
heading: t.printPreview.questionNumber.replace("{num}", String(index + 1)),
meta: metaParts.join(" · "),
questionText: useTextMode ? (item.questionText ?? "") : undefined,
image,
inlineAnswerLabel: options.showAnswers && item.answerText ? t.printPreview.referenceAnswer : undefined,
inlineAnswerText: options.showAnswers && item.answerText ? item.answerText : undefined,
inlineAnalysisLabel: options.showAnalysis && item.analysis ? t.printPreview.analysis : undefined,
inlineAnalysisText: options.showAnalysis && item.analysis ? item.analysis : undefined,
answerSpacePx: reserveAnswerSpace
? resolveQuestionAnswerSpacePx(
options.answerSpace ?? "auto",
item.questionText || "",
customSpaces[item.id],
)
: 0,
};
}),
);
const bytes = createDocxArchive({
title: t.printPreview.title,
questions: questionBlocks,
});
triggerDocxDownload(bytes, t.printPreview.title);
} finally {
setExportingDocx(false);
}
};
const toggleSelectedItem = (id: string) => {
setSelectedIds((prev) => {
const next = new Set(prev);
@@ -117,6 +187,16 @@ function PrintPreviewContent() {
<h1 className="text-lg sm:text-xl font-bold flex-1">
{t.printPreview?.title || 'Print Preview'} ({countLabel} {t.notebooks?.items || 'items'})
</h1>
<Button
variant="outline"
size="sm"
className="whitespace-nowrap"
onClick={handleExportDocx}
disabled={selectedItems.length === 0 || exportingDocx}
>
<Download className="mr-1.5 h-4 w-4" />
{exportingDocx ? t.printPreview.exportingDocx : t.printPreview.downloadDocx}
</Button>
<Button onClick={handlePrint} size="sm" className="whitespace-nowrap" disabled={selectedItems.length === 0}>
{t.printPreview?.printButton || 'Print / Save PDF'}
</Button>

View File

@@ -5,6 +5,7 @@ import { AnswerSpaceControl } from "@/components/print-preview/answer-space-cont
import { QuestionFigure } from "@/components/question-figure";
import { useLanguage } from "@/contexts/LanguageContext";
import { resolveQuestionAnswerSpacePx } from "@/lib/exam-answer-space";
import { getPrintableItemTagNames } from "@/lib/print-preview";
import { usePaperGroups } from "@/lib/use-paper-groups";
import type { PrintableErrorItem } from "@/types/api";
import type { PrintDisplayOptions } from "./print-options";
@@ -21,17 +22,6 @@ interface PrintableQuestionProps {
onCustomAnswerSpaceChange?: (px: number | null) => void;
}
/** 题目的知识点:优先使用 tags 关联,旧数据回退到 knowledgePoints */
function tagNames(item: PrintableErrorItem): string[] {
if (item.tags && item.tags.length > 0) return item.tags.map((tag) => tag.name);
try {
const parsed: unknown = JSON.parse(item.knowledgePoints || "[]");
return Array.isArray(parsed) ? parsed.filter((tag): tag is string => typeof tag === "string") : [];
} catch {
return [];
}
}
/** 打印页中的一道题:题号、来源信息、原图或文字,以及可选的答案和解析 */
export function PrintableQuestion({
item,
@@ -42,7 +32,7 @@ export function PrintableQuestion({
onCustomAnswerSpaceChange,
}: PrintableQuestionProps) {
const { t } = useLanguage();
const tags = tagNames(item);
const tags = getPrintableItemTagNames(item);
const { groups: paperGroups } = usePaperGroups();
const paperGroupName = item.paperLevel
? paperGroups.find((g) => g.id === item.paperLevel)?.name || item.paperLevel

631
src/lib/docx-export.ts Normal file
View File

@@ -0,0 +1,631 @@
import { normalizeFigureAlign, normalizeFigureScale, svgToDataUri } from "@/lib/figure-scale";
import type { FigureAlign } from "@/lib/figure-scale";
/** DOCX 内嵌图片数据 */
export interface DocxEmbeddedImage {
/** PNG 或 JPEG 二进制字节 */
data: Uint8Array;
/** 扩展名 */
extension: "png" | "jpeg";
/** 在文档中显示的宽度(px,96 DPI) */
widthPx: number;
/** 在文档中显示的高度(px,96 DPI) */
heightPx: number;
/** 水平对齐方式 */
align?: FigureAlign;
}
/** DOCX 单个题目区块 */
export interface DocxQuestionBlock {
/** 题号标题,如 "1." 或 "题目 1" */
heading: string;
/** 右侧或次要元信息,如 "来源 ID: ABC123 · 七年级上" */
meta?: string;
/** 题干 Markdown / LaTeX 文本 */
questionText?: string;
/** 题目配图或原图 */
image?: DocxEmbeddedImage | null;
/** 题内直接显示的参考答案(错题打印预览勾选“显示答案”时使用) */
inlineAnswerLabel?: string;
inlineAnswerText?: string;
/** 题内直接显示的解析(错题打印预览勾选“显示解析”时使用) */
inlineAnalysisLabel?: string;
inlineAnalysisText?: string;
/** 题目下方预留的作答留白高度(px) */
answerSpacePx: number;
}
/** DOCX 独立答案页条目(试卷打印勾选“包含答案页”时使用) */
export interface DocxAnswerKeyBlock {
heading: string;
meta?: string;
answerLabel?: string;
answerText?: string;
analysisLabel?: string;
analysisText?: string;
}
/** DOCX 文档完整规格 */
export interface DocxDocumentSpec {
title: string;
/** 试卷抬头行,如 ["姓名:________", "日期:________", "得分:________"] */
metaItems?: string[];
questions: DocxQuestionBlock[];
answerKeyTitle?: string;
answerKey?: DocxAnswerKeyBlock[];
}
const SUPERSCRIPT_MAP: Record<string, string> = {
"0": "⁰", "1": "¹", "2": "²", "3": "³", "4": "⁴",
"5": "⁵", "6": "⁶", "7": "⁷", "8": "⁸", "9": "⁹",
"+": "⁺", "-": "⁻", "=": "⁼", "(": "⁽", ")": "⁾", "n": "ⁿ",
};
const SUBSCRIPT_MAP: Record<string, string> = {
"0": "₀", "1": "₁", "2": "₂", "3": "₃", "4": "₄",
"5": "₅", "6": "₆", "7": "₇", "8": "₈", "9": "₉",
"+": "₊", "-": "₋", "=": "₌", "(": "₍", ")": "₎",
};
const LATEX_SYMBOLS: ReadonlyArray<readonly [RegExp, string]> = [
[/\\times\b/g, "×"],
[/\\div\b/g, "÷"],
[/\\cdot\b/g, "·"],
[/\\pm\b/g, "±"],
[/\\mp\b/g, "∓"],
[/\\(?:le|leq)\b/g, "≤"],
[/\\(?:ge|geq)\b/g, "≥"],
[/\\(?:ne|neq)\b/g, "≠"],
[/\\approx\b/g, "≈"],
[/\\equiv\b/g, "≡"],
[/\\cong\b/g, "≌"],
[/\\sim\b/g, "∽"],
[/\\propto\b/g, "∝"],
[/\\infty\b/g, "∞"],
[/\\triangle\b/g, "△"],
[/\\angle\b/g, "∠"],
[/\\perp\b/g, "⊥"],
[/\\parallel\b/g, "∥"],
[/\\because\b/g, "∵"],
[/\\therefore\b/g, "∴"],
[/\\notin\b/g, "∉"],
[/\\in\b/g, "∈"],
[/\\subseteq\b/g, "⊆"],
[/\\subset\b/g, "⊂"],
[/\\cup\b/g, "∪"],
[/\\cap\b/g, "∩"],
[/\\(?:emptyset|varnothing)\b/g, "∅"],
[/\\forall\b/g, "∀"],
[/\\exists\b/g, "∃"],
[/\\Leftrightarrow\b/g, "⇔"],
[/\\Rightarrow\b/g, "⇒"],
[/\\(?:to|rightarrow)\b/g, "→"],
[/\\leftarrow\b/g, "←"],
[/\\alpha\b/g, "α"],
[/\\beta\b/g, "β"],
[/\\gamma\b/g, "γ"],
[/\\delta\b/g, "δ"],
[/\\Delta\b/g, "Δ"],
[/\\(?:epsilon|varepsilon)\b/g, "ε"],
[/\\theta\b/g, "θ"],
[/\\lambda\b/g, "λ"],
[/\\mu\b/g, "μ"],
[/\\pi\b/g, "π"],
[/\\rho\b/g, "ρ"],
[/\\sigma\b/g, "σ"],
[/\\tau\b/g, "τ"],
[/\\(?:phi|varphi)\b/g, "φ"],
[/\\omega\b/g, "ω"],
[/\\Omega\b/g, "Ω"],
[/\\sum\b/g, "∑"],
[/\\prod\b/g, "∏"],
[/\\int\b/g, "∫"],
];
function mapScriptChars(input: string, table: Record<string, string>, fallbackPrefix: string): string {
const trimmed = input.trim();
if (!trimmed) return "";
const mapped = Array.from(trimmed).map((ch) => table[ch]);
if (mapped.every(Boolean)) return mapped.join("");
return trimmed.length === 1 ? `${fallbackPrefix}${trimmed}` : `${fallbackPrefix}(${trimmed})`;
}
/** 将 Markdown 与 LaTeX 数学公式转换为适合在 Word 中直接阅读和编辑的纯文本 */
export function formatMathAndMarkdownForDocx(raw: string): string {
let text = raw
.replace(/<!--[\s\S]*?-->/g, "")
.replace(/\r\n/g, "\n")
.replace(/\\_/g, "_");
// 填空横线与空白命令
text = text
.replace(/\\underline\{\s*(?:\\quad|\\qquad|\\hspace\{[^}]*\}|\s)*\}/g, "______")
.replace(/\\underline\{([^{}]*)\}/g, "$1")
.replace(/\\rule\{[^}]*\}\{[^}]*\}/g, "______")
.replace(/\\hspace\{[^}]*\}/g, " ");
// 分式与根式(支持两层嵌套花括号)
for (let i = 0; i < 2; i++) {
text = text.replace(/\\(?:d|t)?frac\{([^{}]*)\}\{([^{}]*)\}/g, (_, num: string, den: string) => {
const n = num.trim();
const d = den.trim();
const left = /^[A-Za-z0-9α-ωΑ-Ω]+$/.test(n) ? n : `(${n})`;
const right = /^[A-Za-z0-9α-ωΑ-Ω]+$/.test(d) ? d : `(${d})`;
return `${left}/${right}`;
});
text = text.replace(/\\sqrt\[([^{}\]]*)\]\{([^{}]*)\}/g, (_, root: string, body: string) => {
const sup = mapScriptChars(root, SUPERSCRIPT_MAP, "^");
const b = body.trim();
return /^[A-Za-z0-9]+$/.test(b) ? `${sup}√${b}` : `${sup}√(${b})`;
});
text = text.replace(/\\sqrt\{([^{}]*)\}/g, (_, body: string) => {
const b = body.trim();
return /^[A-Za-z0-9]+$/.test(b) ? `√${b}` : `√(${b})`;
});
}
// 角度与上下标
text = text
.replace(/\^\{\\circ\}|\^\\circ/g, "°")
.replace(/\^\{([^{}]+)\}/g, (_, exp: string) => mapScriptChars(exp, SUPERSCRIPT_MAP, "^"))
.replace(/\^([0-9n+-])/g, (_, exp: string) => mapScriptChars(exp, SUPERSCRIPT_MAP, "^"))
.replace(/_\{([^{}]+)\}/g, (_, sub: string) => mapScriptChars(sub, SUBSCRIPT_MAP, "_"))
.replace(/_([0-9+-])/g, (_, sub: string) => mapScriptChars(sub, SUBSCRIPT_MAP, "_"));
// 常见 LaTeX 文本包装与定界符
text = text
.replace(/\\(?:text|mathrm|mathbf|mathit|mathbb|mathcal)\{([^{}]*)\}/g, "$1")
.replace(/\\(?:left|right)\s*([()[\]|.{])/g, "$1")
.replace(/\\(?:quad|qquad)\b/g, " ")
.replace(/\\[,;!]/g, " ");
for (const [pattern, replacement] of LATEX_SYMBOLS) {
text = text.replace(pattern, replacement);
}
// 去除公式包裹符与常见 Markdown 标记
text = text
.replace(/\$\$([\s\S]*?)\$\$/g, "$1")
.replace(/\$([^$\n]+)\$/g, "$1")
.replace(/\\([{}%&#])/g, "$1")
.replace(/\*\*([^*]+)\*\*/g, "$1")
.replace(/`([^`]+)`/g, "$1")
.replace(/^#{1,6}\s+/gm, "");
return text.trim();
}
function escapeXml(value: string): string {
return value
.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F]/g, "")
.replace(/[&<>"']/g, (ch) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;", "'": "&apos;" }[ch]!));
}
/** 生成下载用的 .docx 文件名 */
export function docxFileName(title: string): string {
const cleaned = title.trim().replace(/[\\/:*?"<>|\s]+/g, "_").replace(/^_+|_+$/g, "").slice(0, 80);
return `${cleaned || "document"}.docx`;
}
// --- 标准 ZIP (STORE) 打包实现,零外部依赖 ---
const CRC32_TABLE = (() => {
const table = new Uint32Array(256);
for (let i = 0; i < 256; i++) {
let c = i;
for (let k = 0; k < 8; k++) {
c = (c & 1) ? (0xedb88320 ^ (c >>> 1)) : (c >>> 1);
}
table[i] = c >>> 0;
}
return table;
})();
function crc32(bytes: Uint8Array): number {
let crc = 0xffffffff;
for (let i = 0; i < bytes.length; i++) {
crc = CRC32_TABLE[(crc ^ bytes[i]) & 0xff] ^ (crc >>> 8);
}
return (crc ^ 0xffffffff) >>> 0;
}
interface ZipEntry {
name: string;
data: Uint8Array;
}
function buildZipArchive(entries: ZipEntry[]): Uint8Array {
const encoder = new TextEncoder();
const localParts: Uint8Array[] = [];
const centralParts: Uint8Array[] = [];
let offset = 0;
for (const entry of entries) {
const nameBytes = encoder.encode(entry.name);
const data = entry.data;
const crc = crc32(data);
const localHeader = new Uint8Array(30 + nameBytes.length);
const lv = new DataView(localHeader.buffer);
lv.setUint32(0, 0x04034b50, true);
lv.setUint16(4, 20, true);
lv.setUint16(6, 0x0800, true); // UTF-8
lv.setUint16(8, 0, true); // STORE
lv.setUint16(10, 0, true);
lv.setUint16(12, 0x21, true);
lv.setUint32(14, crc, true);
lv.setUint32(18, data.length, true);
lv.setUint32(22, data.length, true);
lv.setUint16(26, nameBytes.length, true);
lv.setUint16(28, 0, true);
localHeader.set(nameBytes, 30);
const centralHeader = new Uint8Array(46 + nameBytes.length);
const cv = new DataView(centralHeader.buffer);
cv.setUint32(0, 0x02014b50, true);
cv.setUint16(4, 20, true);
cv.setUint16(6, 20, true);
cv.setUint16(8, 0x0800, true);
cv.setUint16(10, 0, true);
cv.setUint16(12, 0, true);
cv.setUint16(14, 0x21, true);
cv.setUint32(16, crc, true);
cv.setUint32(20, data.length, true);
cv.setUint32(24, data.length, true);
cv.setUint16(28, nameBytes.length, true);
cv.setUint16(30, 0, true);
cv.setUint16(32, 0, true);
cv.setUint16(34, 0, true);
cv.setUint16(36, 0, true);
cv.setUint32(38, 0, true);
cv.setUint32(42, offset, true);
centralHeader.set(nameBytes, 46);
localParts.push(localHeader, data);
centralParts.push(centralHeader);
offset += localHeader.length + data.length;
}
const centralSize = centralParts.reduce((sum, part) => sum + part.length, 0);
const eocd = new Uint8Array(22);
const ev = new DataView(eocd.buffer);
ev.setUint32(0, 0x06054b50, true);
ev.setUint16(4, 0, true);
ev.setUint16(6, 0, true);
ev.setUint16(8, entries.length, true);
ev.setUint16(10, entries.length, true);
ev.setUint32(12, centralSize, true);
ev.setUint32(16, offset, true);
ev.setUint16(20, 0, true);
const totalSize = offset + centralSize + eocd.length;
const output = new Uint8Array(totalSize);
let cursor = 0;
for (const part of localParts) {
output.set(part, cursor);
cursor += part.length;
}
for (const part of centralParts) {
output.set(part, cursor);
cursor += part.length;
}
output.set(eocd, cursor);
return output;
}
function buildParagraphXml(
runsXml: string,
options?: { align?: "left" | "center" | "right"; spaceBeforeDxa?: number; spaceAfterDxa?: number; pageBreakBefore?: boolean; bottomBorder?: boolean },
): string {
const pPrParts: string[] = [];
if (options?.pageBreakBefore) pPrParts.push("<w:pageBreakBefore/>");
if (options?.align && options.align !== "left") {
pPrParts.push(`<w:jc w:val="${options.align}"/>`);
}
if (options?.spaceBeforeDxa !== undefined || options?.spaceAfterDxa !== undefined) {
const before = options.spaceBeforeDxa ?? 0;
const after = options.spaceAfterDxa ?? 80;
pPrParts.push(`<w:spacing w:before="${before}" w:after="${after}" w:line="320" w:lineRule="auto"/>`);
}
if (options?.bottomBorder) {
pPrParts.push('<w:pBdr><w:bottom w:val="dashed" w:sz="4" w:space="4" w:color="CCCCCC"/></w:pBdr>');
}
const pPr = pPrParts.length > 0 ? `<w:pPr>${pPrParts.join("")}</w:pPr>` : "";
return `<w:p>${pPr}${runsXml}</w:p>`;
}
function buildRunXml(text: string, options?: { bold?: boolean; sizeHalfPt?: number; colorHex?: string }): string {
const rPrParts: string[] = [
'<w:rFonts w:ascii="Calibri" w:hAnsi="Calibri" w:eastAsia="Microsoft YaHei" w:cs="Calibri"/>',
];
if (options?.bold) rPrParts.push("<w:b/>");
if (options?.sizeHalfPt) rPrParts.push(`<w:sz w:val="${options.sizeHalfPt}"/><w:szCs w:val="${options.sizeHalfPt}"/>`);
if (options?.colorHex) rPrParts.push(`<w:color w:val="${options.colorHex}"/>`);
return `<w:r><w:rPr>${rPrParts.join("")}</w:rPr><w:t xml:space="preserve">${escapeXml(text)}</w:t></w:r>`;
}
function buildMultilineParagraphsXml(rawText: string, prefixLabel?: string): string[] {
const formatted = formatMathAndMarkdownForDocx(rawText);
const lines = formatted.split("\n");
return lines.map((line, index) => {
if (index === 0 && prefixLabel) {
return buildParagraphXml(
`${buildRunXml(prefixLabel, { bold: true, colorHex: "333333" })}${buildRunXml(line)}`,
{ spaceBeforeDxa: 40, spaceAfterDxa: 60 },
);
}
return buildParagraphXml(buildRunXml(line), { spaceBeforeDxa: 20, spaceAfterDxa: 60 });
});
}
function buildDrawingParagraphXml(relId: string, docPrId: number, image: DocxEmbeddedImage): string {
// 1 px (96 DPI) = 9525 EMU;限制最大宽度为 A4 版心约 600px
const maxWidthPx = 600;
const scale = image.widthPx > maxWidthPx ? maxWidthPx / image.widthPx : 1;
const cx = Math.max(9525, Math.round(image.widthPx * scale * 9525));
const cy = Math.max(9525, Math.round(image.heightPx * scale * 9525));
const align = normalizeFigureAlign(image.align);
const drawingXml = `<w:r><w:drawing><wp:inline distT="0" distB="0" distL="0" distR="0"><wp:extent cx="${cx}" cy="${cy}"/><wp:docPr id="${docPrId}" name="Figure ${docPrId}"/><wp:cNvGraphicFramePr><a:graphicFrameLocks xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" noChangeAspect="1"/></wp:cNvGraphicFramePr><a:graphic xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><a:graphicData uri="http://schemas.openxmlformats.org/drawingml/2006/picture"><pic:pic xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture"><pic:nvPicPr><pic:cNvPr id="${docPrId}" name="image${docPrId}.${image.extension}"/><pic:cNvPicPr/></pic:nvPicPr><pic:blipFill><a:blip r:embed="${relId}"/><a:stretch><a:fillRect/></a:stretch></pic:blipFill><pic:spPr><a:xfrm><a:off x="0" y="0"/><a:ext cx="${cx}" cy="${cy}"/></a:xfrm><a:prstGeom prst="rect"><a:avLst/></a:prstGeom></pic:spPr></pic:pic></a:graphicData></a:graphic></wp:inline></w:drawing></w:r>`;
return buildParagraphXml(drawingXml, { align, spaceBeforeDxa: 80, spaceAfterDxa: 80 });
}
/** 根据留白像素高度生成可直接在 Word 中编辑增删的空行段落 */
function buildAnswerSpaceParagraphsXml(answerSpacePx: number): string[] {
const px = Math.max(0, Math.round(answerSpacePx));
if (px <= 0) {
return [buildParagraphXml("", { spaceBeforeDxa: 0, spaceAfterDxa: 80, bottomBorder: true })];
}
// 每约 28px 对应一行空段落,方便用户在 Word 中直接按退格或回车调节间距
const blankLineCount = Math.max(1, Math.round(px / 28));
const paragraphs: string[] = [];
for (let i = 0; i < blankLineCount; i++) {
const isLast = i === blankLineCount - 1;
paragraphs.push(
buildParagraphXml("", {
spaceBeforeDxa: 0,
spaceAfterDxa: isLast ? 120 : 80,
bottomBorder: isLast,
}),
);
}
return paragraphs;
}
/** 将文档规格打包为标准 OpenXML (.docx) 二进制字节 */
export function createDocxArchive(spec: DocxDocumentSpec): Uint8Array {
const encoder = new TextEncoder();
const bodyParagraphs: string[] = [];
const mediaEntries: ZipEntry[] = [];
const imageRels: string[] = [];
let imageCounter = 0;
// 标题
bodyParagraphs.push(
buildParagraphXml(buildRunXml(spec.title, { bold: true, sizeHalfPt: 36 }), {
align: "center",
spaceBeforeDxa: 0,
spaceAfterDxa: 160,
}),
);
// 试卷姓名/日期/得分栏
if (spec.metaItems && spec.metaItems.length > 0) {
bodyParagraphs.push(
buildParagraphXml(buildRunXml(spec.metaItems.join(" "), { sizeHalfPt: 22 }), {
align: "center",
spaceBeforeDxa: 0,
spaceAfterDxa: 240,
}),
);
}
// 题目列表
for (const q of spec.questions) {
const headRuns = [
buildRunXml(q.heading, { bold: true, sizeHalfPt: 24 }),
...(q.meta ? [buildRunXml(` ${q.meta}`, { sizeHalfPt: 18, colorHex: "666666" })] : []),
].join("");
bodyParagraphs.push(buildParagraphXml(headRuns, { spaceBeforeDxa: 160, spaceAfterDxa: 80 }));
if (q.questionText) {
bodyParagraphs.push(...buildMultilineParagraphsXml(q.questionText));
}
if (q.image && q.image.data.length > 0) {
imageCounter += 1;
const relId = `rIdImg${imageCounter}`;
const fileName = `image${imageCounter}.${q.image.extension}`;
mediaEntries.push({ name: `word/media/${fileName}`, data: q.image.data });
imageRels.push(
`<Relationship Id="${relId}" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image" Target="media/${fileName}"/>`,
);
bodyParagraphs.push(buildDrawingParagraphXml(relId, imageCounter, q.image));
}
if (q.inlineAnswerText) {
bodyParagraphs.push(
...buildMultilineParagraphsXml(q.inlineAnswerText, q.inlineAnswerLabel ? `${q.inlineAnswerLabel}:` : undefined),
);
}
if (q.inlineAnalysisText) {
bodyParagraphs.push(
...buildMultilineParagraphsXml(q.inlineAnalysisText, q.inlineAnalysisLabel ? `${q.inlineAnalysisLabel}:` : undefined),
);
}
bodyParagraphs.push(...buildAnswerSpaceParagraphsXml(q.answerSpacePx));
}
// 独立答案页
if (spec.answerKey && spec.answerKey.length > 0) {
bodyParagraphs.push(
buildParagraphXml(
buildRunXml(spec.answerKeyTitle || "参考答案与解析", { bold: true, sizeHalfPt: 30 }),
{ align: "center", pageBreakBefore: true, spaceBeforeDxa: 120, spaceAfterDxa: 200 },
),
);
for (const item of spec.answerKey) {
const headRuns = [
buildRunXml(item.heading, { bold: true, sizeHalfPt: 22 }),
...(item.meta ? [buildRunXml(` ${item.meta}`, { sizeHalfPt: 18, colorHex: "666666" })] : []),
].join("");
bodyParagraphs.push(buildParagraphXml(headRuns, { spaceBeforeDxa: 120, spaceAfterDxa: 60 }));
if (item.answerText) {
bodyParagraphs.push(
...buildMultilineParagraphsXml(item.answerText, item.answerLabel ? `${item.answerLabel}:` : undefined),
);
}
if (item.analysisText) {
bodyParagraphs.push(
...buildMultilineParagraphsXml(item.analysisText, item.analysisLabel ? `${item.analysisLabel}:` : undefined),
);
}
}
}
const documentXml = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:wp="http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing" xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" xmlns:pic="http://schemas.openxmlformats.org/drawingml/2006/picture">
<w:body>
${bodyParagraphs.join("\n")}
<w:sectPr>
<w:pgSz w:w="11906" w:h="16838"/>
<w:pgMar w:top="850" w:right="850" w:bottom="850" w:left="850" w:header="450" w:footer="450" w:gutter="0"/>
</w:sectPr>
</w:body>
</w:document>`;
const stylesXml = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<w:styles xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">
<w:docDefaults>
<w:rPrDefault><w:rPr><w:rFonts w:ascii="Calibri" w:hAnsi="Calibri" w:eastAsia="Microsoft YaHei" w:cs="Calibri"/><w:sz w:val="22"/><w:szCs w:val="22"/><w:color w:val="111111"/></w:rPr></w:rPrDefault>
<w:pPrDefault><w:pPr><w:spacing w:after="80" w:line="320" w:lineRule="auto"/></w:pPr></w:pPrDefault>
</w:docDefaults>
</w:styles>`;
const contentTypesXml = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">
<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>
<Default Extension="xml" ContentType="application/xml"/>
<Default Extension="png" ContentType="image/png"/>
<Default Extension="jpeg" ContentType="image/jpeg"/>
<Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/>
<Override PartName="/word/styles.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.styles+xml"/>
</Types>`;
const rootRelsXml = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/>
</Relationships>`;
const docRelsXml = `<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">
<Relationship Id="rIdStyles" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/styles" Target="styles.xml"/>
${imageRels.join("\n")}
</Relationships>`;
return buildZipArchive([
{ name: "[Content_Types].xml", data: encoder.encode(contentTypesXml) },
{ name: "_rels/.rels", data: encoder.encode(rootRelsXml) },
{ name: "word/document.xml", data: encoder.encode(documentXml) },
{ name: "word/styles.xml", data: encoder.encode(stylesXml) },
{ name: "word/_rels/document.xml.rels", data: encoder.encode(docRelsXml) },
...mediaEntries,
]);
}
function dataUrlToBytes(dataUrl: string): Uint8Array | null {
const commaIdx = dataUrl.indexOf(",");
if (commaIdx < 0) return null;
const base64 = dataUrl.slice(commaIdx + 1);
const binary = atob(base64);
const bytes = new Uint8Array(binary.length);
for (let i = 0; i < binary.length; i++) {
bytes[i] = binary.charCodeAt(i);
}
return bytes;
}
/** 在浏览器中将图片 URL 或 SVG 栅格化为 PNG 字节与目标显示尺寸;失败或非浏览器环境返回 null */
export async function rasterizeImageForDocx(
src: string,
options?: { scalePercent?: number; maxBaseWidthPx?: number; align?: FigureAlign | string | null },
): Promise<DocxEmbeddedImage | null> {
if (typeof window === "undefined" || typeof document === "undefined" || typeof Image === "undefined") {
return null;
}
return new Promise((resolve) => {
const img = new Image();
img.crossOrigin = "anonymous";
img.onload = () => {
try {
const rawW = img.naturalWidth || img.width || 320;
const rawH = img.naturalHeight || img.height || 200;
const maxBase = options?.maxBaseWidthPx ?? 560;
const baseScale = rawW > maxBase ? maxBase / rawW : 1;
const userScale = (options?.scalePercent ?? 100) / 100;
const displayW = Math.max(40, Math.round(rawW * baseScale * userScale));
const displayH = Math.max(30, Math.round(rawH * baseScale * userScale));
const dpr = 2;
const canvas = document.createElement("canvas");
canvas.width = displayW * dpr;
canvas.height = displayH * dpr;
const ctx = canvas.getContext("2d");
if (!ctx) {
resolve(null);
return;
}
ctx.fillStyle = "#ffffff";
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(img, 0, 0, canvas.width, canvas.height);
const bytes = dataUrlToBytes(canvas.toDataURL("image/png"));
if (!bytes) {
resolve(null);
return;
}
resolve({
data: bytes,
extension: "png",
widthPx: displayW,
heightPx: displayH,
align: normalizeFigureAlign(options?.align),
});
} catch {
resolve(null);
}
};
img.onerror = () => resolve(null);
img.src = src;
});
}
/** 将题目 SVG 配图转换为 DOCX 内嵌图片 */
export async function rasterizeSvgFigureForDocx(
svg: string | null | undefined,
scale?: number | null,
align?: FigureAlign | string | null,
): Promise<DocxEmbeddedImage | null> {
if (!svg) return null;
return rasterizeImageForDocx(svgToDataUri(svg), {
scalePercent: normalizeFigureScale(scale ?? undefined),
maxBaseWidthPx: 360,
align,
});
}
/** 在浏览器中触发 .docx 文件下载 */
export function triggerDocxDownload(bytes: Uint8Array, title: string): void {
const buffer = new ArrayBuffer(bytes.byteLength);
new Uint8Array(buffer).set(bytes);
const blob = new Blob([buffer], {
type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
});
const url = URL.createObjectURL(blob);
const link = document.createElement("a");
link.href = url;
link.download = docxFileName(title);
link.click();
URL.revokeObjectURL(url);
}

View File

@@ -1,7 +1,20 @@
import type { PrintableErrorItem } from '@/types/api';
type PrintSelectableItem = {
id: string;
};
/** 提取错题打印项的知识点名称:优先使用 tags 关联,旧数据回退到 knowledgePoints */
export function getPrintableItemTagNames(item: Pick<PrintableErrorItem, 'tags' | 'knowledgePoints'>): string[] {
if (item.tags && item.tags.length > 0) return item.tags.map((tag) => tag.name);
try {
const parsed: unknown = JSON.parse(item.knowledgePoints || '[]');
return Array.isArray(parsed) ? parsed.filter((tag): tag is string => typeof tag === 'string') : [];
} catch {
return [];
}
}
export function getSelectedPrintItems<T extends PrintSelectableItem>(
items: T[],
selectedIds: Set<string>,

View File

@@ -962,6 +962,8 @@ export const translations = {
showAnalysis: "Show Analysis",
showTags: "Show Tags",
printButton: "Print / Save PDF",
downloadDocx: "Export DOCX",
exportingDocx: "Exporting…",
questionNumber: "Question {num}",
source: "Source {id}",
paperLevel: "Paper Level",
@@ -1190,6 +1192,8 @@ export const translations = {
resetAllQuestionAnswerSpaces: "Reset custom spaces",
printNow: "Print",
downloadHtml: "Download HTML",
downloadDocx: "Download DOCX",
exportingDocx: "Exporting…",
nameLine: "Name",
dateLine: "Date",
scoreLine: "Score",
@@ -2361,6 +2365,8 @@ export const translations = {
showAnalysis: "显示解析",
showTags: "显示知识点",
printButton: "打印 / 保存 PDF",
downloadDocx: "导出 Word (DOCX)",
exportingDocx: "导出中…",
questionNumber: "题目 {num}",
source: "来源 {id}",
paperLevel: "试卷等级",
@@ -2589,6 +2595,8 @@ export const translations = {
resetAllQuestionAnswerSpaces: "重置单题留白",
printNow: "打印",
downloadHtml: "下载 HTML",
downloadDocx: "下载 Word (DOCX)",
exportingDocx: "导出中…",
nameLine: "姓名",
dateLine: "日期",
scoreLine: "得分",