diff --git a/README.en.md b/README.en.md
index 1451b80b..f165deca 100644
--- a/README.en.md
+++ b/README.en.md
@@ -99,7 +99,7 @@ Generated exams keep each source question's ID and show every attempt, so you ca

-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.

@@ -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
diff --git a/README.md b/README.md
index 0b41f8d9..fcd2d450 100644
--- a/README.md
+++ b/README.md
@@ -99,7 +99,7 @@

-打印预览可选择包含答案页,并设置每题下方的留白:按题型自动(填空、选择、判断题少留,解答题按小问数多留),或固定为不留白、小、中、大;支持下载 HTML、打印或通过浏览器保存为 PDF。
+打印预览可选择包含答案页,并设置每题下方的留白:按题型自动(填空、选择、判断题少留,解答题按小问数多留),或固定为不留白、小、中、大,也可在单题下方手动调节留白高度;支持导出 Word(DOCX)、下载 HTML、打印或通过浏览器保存为 PDF。

@@ -158,7 +158,7 @@
- **📈 掌握概率**:根据举一反三和试卷的作答历史,由 AI 评估每道题的已掌握概率。错题分为三种状态:没有举一反三记录的为「待复习」,有记录且掌握概率低于已掌握阈值的为「复习中」,达到阈值的为「已掌握」。阈值默认 50%,每个用户可在设置中单独调整。
- **📅 今日复习**:按 1、2、4、7、15、30 天的艾宾浩斯间隔安排每道错题的复习,做对进入下一轮间隔,做错从头开始。导航栏的「复习」页列出今天到期的错题(最早到期的在前),首页显示今日待复习数量。
- **🧾 错题试卷**:按错题本、知识点和掌握情况随机抽题,用举一反三生成一套可打印的试卷;做完后可按题录入结果,结果计入原题的作答历史。
-- **🖨️ 错题打印**:筛选后打印错题,可选打印题目文字或原图、答案、解析、知识点,调节图片比例,可直接打印或保存为 PDF。
+- **🖨️ 错题打印与导出**:筛选后打印错题,可选打印题目文字或原图、答案、解析、知识点,调节图片比例以及全局/单题留白高度,可直接打印、保存为 PDF 或导出为 Word(DOCX)文档。
### 管理与统计
diff --git a/doc/wiki/Practice-and-Exams.md b/doc/wiki/Practice-and-Exams.md
index 33c269c1..8844769d 100644
--- a/doc/wiki/Practice-and-Exams.md
+++ b/doc/wiki/Practice-and-Exams.md
@@ -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” |
打印前检查分页、公式和配图是否完整;纸张、缩放和页边距由浏览器打印设置控制。
diff --git a/doc/wiki/en/Practice-and-Exams-en.md b/doc/wiki/en/Practice-and-Exams-en.md
index 99e8dda4..120a95a5 100644
--- a/doc/wiki/en/Practice-and-Exams-en.md
+++ b/doc/wiki/en/Practice-and-Exams-en.md
@@ -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.
diff --git a/src/__tests__/unit/docx-export.test.ts b/src/__tests__/unit/docx-export.test.ts
new file mode 100644
index 00000000..ac4931ab
--- /dev/null
+++ b/src/__tests__/unit/docx-export.test.ts
@@ -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(
+ "\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("");
+ 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();
+ });
+});
diff --git a/src/__tests__/unit/print-preview.test.ts b/src/__tests__/unit/print-preview.test.ts
index 9e87c96c..cade9eb9 100644
--- a/src/__tests__/unit/print-preview.test.ts
+++ b/src/__tests__/unit/print-preview.test.ts
@@ -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([]);
+ });
});
diff --git a/src/app/exams/[id]/print/page.tsx b/src/app/exams/[id]/print/page.tsx
index 335a2ff8..3afe9ac7 100644
--- a/src/app/exams/[id]/print/page.tsx
+++ b/src/app/exams/[id]/print/page.tsx
@@ -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(DEFAULT_ANSWER_SPACE_MODE);
const [customSpaces, setCustomSpaces] = useState>({});
+ const [exportingDocx, setExportingDocx] = useState(false);
const [uniformPreview, setUniformPreview] = useState<{ scale: number | null; align: FigureAlign | null }>({ scale: null, align: null });
const sheetRef = useRef(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 (
@@ -139,11 +191,15 @@ export default function ExamPrintPage() {
)}
-
+
+