DOCX

批注与修订

文档批注、修订跟踪和结构化文档标签(内容控件)

批注

使用 CommentRangeStartCommentRangeEndCommentReference 为文档内容添加批注:

import {
    Document,
    Paragraph,
    TextRun,
    Comments,
    Comment,
    CommentRangeStart,
    CommentRangeEnd,
    CommentReference,
} from "@office-open/docx";

const doc = new Document({
    comments: {
        comments: new Comments({
            children: [
                new Comment({
                    id: 0,
                    author: "Author Name",
                    date: new Date(),
                    children: [
                        new Paragraph({ children: [new TextRun("Please review this section.")] }),
                    ],
                }),
            ],
        }),
    },
    sections: [
        {
            children: [
                new Paragraph({
                    children: [
                        new CommentRangeStart(0),
                        new TextRun("This text has a comment attached."),
                        new CommentRangeEnd(0),
                        new CommentReference(0),
                    ],
                }),
            ],
        },
    ],
});

修订跟踪

跟踪文档中的插入、删除和移动:

import { Paragraph, TextRun, InsertedTextRun, DeletedTextRun } from "@office-open/docx";

// 插入
new Paragraph({
    children: [
        new InsertedTextRun({
            author: "Author",
            date: new Date(),
            children: [new TextRun("This text was inserted.")],
        }),
    ],
});

// 删除
new Paragraph({
    children: [
        new DeletedTextRun({
            author: "Author",
            date: new Date(),
            children: [new TextRun("This text was deleted.")],
        }),
    ],
});

结构化文档标签(内容控件)

使用 SDT 创建可编辑区域和表单控件:

import { StructuredDocumentTagRun, StructuredDocumentTagBlock } from "@office-open/docx";

// 行内内容控件
new Paragraph({
    children: [
        new StructuredDocumentTagRun({
            alias: "FirstName",
            tag: "first-name",
            children: [new TextRun("John")],
        }),
    ],
});

// 块级内容控件
new StructuredDocumentTagBlock({
    alias: "Section",
    tag: "custom-section",
    children: [new Paragraph("Editable content inside the control.")],
});

SDT 支持多种控件类型,适用于表单、模板和文档自动化。

文档保护

使用设置限制文档编辑:

import { Document } from "@office-open/docx";

const doc = new Document({
    features: {
        updateFields: true,
    },
    settings: {
        protection: {
            type: "readOnly",
            password: "secret",
        },
    },
    sections: [
        // ...
    ],
});

保护类型:"readOnly""comments""trackedChanges""forms"

修订跟踪选项

使用 InsertedTextRunDeletedTextRun 时的选项:

选项类型说明
authorstring修订作者名称
dateDate修订时间戳
idnumber修订 ID(省略时自动生成)
Copyright © 2026