[ SKILL_DOCUMENTATION ]
# DOCX 库教程
使用 JavaScript/TypeScript 生成 .docx 文件。
**重要:开始前请阅读全文。** 文档中涵盖了关键的格式规则和常见陷阱 - 跳过某些章节可能会导致文件损坏或渲染问题。
## 设置
假设 docx 已全局安装
如果未安装:`npm install -g docx`
javascript
const { Document, Packer, Paragraph, TextRun, Table, TableRow, TableCell, ImageRun, Media,
Header, Footer, AlignmentType, PageOrientation, LevelFormat, ExternalHyperlink,
InternalHyperlink, TableOfContents, HeadingLevel, BorderStyle, WidthType, TabStopType,
TabStopPosition, UnderlineType, ShadingType, VerticalAlign, SymbolRun, PageNumber,
FootnoteReferenceRun, Footnote, PageBreak } = require('docx');
// 创建并保存
const doc = new Document({ sections: [{ children: [/* 内容 */] }] });
Packer.toBuffer(doc).then(buffer => fs.writeFileSync("doc.docx", buffer)); // Node.js
Packer.toBlob(doc).then(blob => { /* 下载逻辑 */ }); // 浏览器
## 文本与格式
javascript
// 重要:切勿使用 n 进行换行 - 始终使用独立的 Paragraph 元素
// ❌ 错误:new TextRun("第一行n第二行")
// ✅ 正确:new Paragraph({ children: [new TextRun("第一行")] }), new Paragraph({ children: [new TextRun("第二行")] })
// 带有所有格式选项的基本文本
new Paragraph({
alignment: AlignmentType.CENTER,
spacing: { before: 200, after: 200 },
indent: { left: 720, right: 720 },
children: [
new TextRun({ text: "粗体", bold: true }),
new TextRun({ text: "斜体", italics: true }),
new TextRun({ text: "下划线", underline: { type: UnderlineType.DOUBLE, color: "FF0000" } }),
new TextRun({ text: "彩色", color: "FF0000", size: 28, font: "Arial" }), // 默认 Arial
new TextRun({ text: "高亮", highlight: "yellow" }),
new TextRun({ text: "删除线", strike: true }),
new TextRun({ text: "x2", superScript: true }),
new TextRun({ text: "H2O", subScript: true }),
new TextRun({ text: "小型大写字母", smallCaps: true }),
new SymbolRun({ char: "2022", font: "Symbol" }), // 项目符号 •
new SymbolRun({ char: "00A9", font: "Arial" }) // 版权符号 © - 符号使用 Arial
]
})
## 样式与专业格式
javascript
const doc = new Document({
styles: {
default: { document: { run: { font: "Arial", size: 24 } } }, // 默认 12pt
paragraphStyles: [
// 文档标题