签名区、页边提示与图注经常放在文本框里。文本框脱离正文流,可以自由定位,又不会改变正文排版;自动生成这类文档时,既要能创建文本框并写入内容,也要能从已有文档中读出框内文字,或在清理模板时把它们删除。
本文用 Spire.Doc for JavaScript 在浏览器中完成四项操作,示例文档为一份三页的设备采购合同 EquipmentPurchaseContract.docx:
有关安装和项目配置,请参考 React 项目中集成 Spire.Doc for JavaScript。下面的示例假定 Spire.Doc 已安装、WebAssembly 模块已初始化。
示例合同包含封面、合同双方、设备明细、付款条款与签署页,签署页留有空白,适合放置印章、提示文字与页边标签:

文本框的对象结构
文本框悬挂在段落之下,内部有独立的正文容器 Body。它不属于段落的正文流,因此遍历正文时不会自然命中;文档级的 Document.TextBoxes 集合按插入顺序收录全部文本框,是访问文本框的主要入口。
| 成员 | 作用 |
|---|---|
paragraph.AppendTextBox(width, height) |
在段落中插入文本框,宽高以磅为单位 |
textBox.Body |
文本框内部的正文容器 |
textBox.Format |
边框、填充、内边距、位置与文字方向 |
document.TextBoxes |
文档中全部文本框的集合 |
document.TextBoxes.RemoveAt(index) |
按下标删除文本框 |
document.TextBoxes.Clear() |
清空全部文本框 |
创建并写出一个文本框的一般流程如下:
- 获取 Spire.Doc 的 WASM 模块,确认已就绪。
- 载入字体与示例文档,取得目标段落。
- 调用
AppendTextBox创建文本框,并设置填充、边框与内边距。 - 通过
textBox.Body.AddParagraph()写入文字,并设置字符格式。 - 保存结果文件,从 VFS 读出并触发浏览器下载。
文本框的宽高与内边距都以磅为单位;A4 纸张、左右各 2.5 厘米页边距时,正文可用宽度约为 454 磅,超过该宽度的文本框会压到页边距上。
在 Word 文档中插入文本框
在 Word 文档中插入文本框,先调用 paragraph.AppendTextBox(width, height) 在目标段落创建一个文本框,再通过 Body.AddParagraph() 写入内容。文本框默认随段落排布,段落的位置决定它在页面上的位置。
文本框的外观全部通过 Format 设置,常用成员如下:
| 成员 | 说明 |
|---|---|
Format.FillColor |
填充色,取 Color.FromArgb(a, r, g, b) |
Format.LineStyle |
边框线型,取 TextBoxLineStyle 枚举 |
Format.LineColor / Format.LineWidth |
边框颜色与线宽 |
Format.NoLine |
设为 true 时隐藏边框 |
Format.InternalMargin |
文字距边框的内边距,分上下左右四项 |
具体操作步骤如下:
- 获取 Spire.Doc 的 WASM 模块,确认已就绪。
- 读入示例合同,创建
Document对象并加载EquipmentPurchaseContract.docx。 - 在第一节末尾新增段落,调用
AppendTextBox(260, 70)创建文本框。 - 设置填充色、边框色与内边距,再通过
Body.AddParagraph()写入签署日期并居中对齐。 - 保存结果文件,从 VFS 读出并触发浏览器下载。
在 Word 文档中插入文本框的代码如下:
function App() {
const insertTextBox = async () => {
// 获取 Spire.Doc 的 WASM 模块
const docModule = window.wasmModule?.spiredoc;
if (!docModule) {
alert('Spire.Doc is not ready yet');
return;
}
// 载入示例合同
await window.spire.FetchFileToVFS('EquipmentPurchaseContract.docx', '', `${process.env.PUBLIC_URL}/data/`);
const doc = new docModule.Document();
doc.LoadFromFile('EquipmentPurchaseContract.docx');
// 在第一节末尾新增段落,再创建文本框
const paragraph = doc.Sections.get_Item(0).AddParagraph();
// 宽 260 磅、高 70 磅的文本框
const textBox = paragraph.AppendTextBox(260, 70);
textBox.Format.FillColor = docModule.Color.FromArgb(255, 245, 247, 250);
textBox.Format.LineStyle = docModule.TextBoxLineStyle.Simple;
textBox.Format.LineColor = docModule.Color.FromArgb(255, 0, 82, 155);
textBox.Format.LineWidth = 0.75;
// 文字距边框的内边距
textBox.Format.InternalMargin.Top = 6;
textBox.Format.InternalMargin.Bottom = 6;
textBox.Format.InternalMargin.Left = 8;
textBox.Format.InternalMargin.Right = 8;
// 文本框内的段落,对齐与字号都设在内部段落上
const inner = textBox.Body.AddParagraph();
inner.Format.HorizontalAlignment = docModule.HorizontalAlignment.Center;
const range = inner.AppendText('签署日期:____ 年 __ 月 __ 日');
range.CharacterFormat.FontSize = 10.5;
range.CharacterFormat.TextColor = docModule.Color.FromArgb(255, 23, 50, 77);
const outputFileName = 'ContractWithTextBox.docx';
doc.SaveToFile({ fileName: outputFileName, fileFormat: docModule.FileFormat.Docx2013 });
doc.Dispose();
// 从 VFS 读取生成的文件,触发下载
const fileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
const blob = new Blob([fileArray], {
type: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
});
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = outputFileName;
a.click();
URL.revokeObjectURL(url);
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>插入文本框</h1>
<button onClick={insertTextBox}>插入文本框</button>
</div>
);
}
export default App;
插入后,签署页末尾新增了一个带边框的签署日期文本框:

在页面指定位置插入文本框
AppendTextBox 创建的文本框默认随段落排布。需要把它固定在页面的某个坐标时,应设置 Format.HorizontalOrigin 与 Format.VerticalOrigin 为 Page,再给出 HorizontalPosition 与 VerticalPosition;坐标以页面左上角为原点,单位为磅。
下面的代码在同一段落上创建三枚文本框:乙方一栏的印章、左下方的提示条,以及右侧页边的竖排标签。三枚文本框共用同一个锚点段落,位置互不影响:
const anchor = doc.Sections.get_Item(0).AddParagraph();
// 印章:98 × 98 磅,定位到签署页乙方一栏
const seal = anchor.AppendTextBox(98, 98);
seal.Format.HorizontalOrigin = docModule.HorizontalOrigin.Page;
seal.Format.VerticalOrigin = docModule.VerticalOrigin.Page;
seal.Format.HorizontalPosition = 424;
seal.Format.VerticalPosition = 226;
seal.Format.FillColor = docModule.Color.FromArgb(255, 255, 255, 255);
seal.Format.NoLine = true;
const sealInner = seal.Body.AddParagraph();
sealInner.Format.HorizontalAlignment = docModule.HorizontalAlignment.Center;
const sealImage = sealInner.AppendPicture('Seal.png');
sealImage.Width = 80;
sealImage.Height = 80;
// 提示条:306 × 56 磅,定位到页面左下方
const tip = anchor.AppendTextBox(306, 56);
tip.Format.HorizontalOrigin = docModule.HorizontalOrigin.Page;
tip.Format.VerticalOrigin = docModule.VerticalOrigin.Page;
tip.Format.HorizontalPosition = 70;
tip.Format.VerticalPosition = 470;
tip.Format.FillColor = docModule.Color.FromArgb(255, 234, 242, 250);
tip.Format.LineStyle = docModule.TextBoxLineStyle.Simple;
tip.Format.LineColor = docModule.Color.FromArgb(255, 46, 117, 182);
const tipInner = tip.Body.AddParagraph();
tipInner.Format.HorizontalAlignment = docModule.HorizontalAlignment.Center;
tipInner.AppendText('签署提示:乙方已盖章,请甲方核对合同编号与金额后签署。')
.CharacterFormat.FontSize = 9;
// 页边标签:32 × 148 磅,竖排在右侧页边
const tab = anchor.AppendTextBox(32, 148);
tab.Format.HorizontalOrigin = docModule.HorizontalOrigin.Page;
tab.Format.VerticalOrigin = docModule.VerticalOrigin.Page;
tab.Format.HorizontalPosition = 540;
tab.Format.VerticalPosition = 420;
tab.Format.FillColor = docModule.Color.FromArgb(255, 23, 50, 77);
tab.Format.LineStyle = docModule.TextBoxLineStyle.Simple;
tab.Format.LineColor = docModule.Color.FromArgb(255, 23, 50, 77);
tab.Format.LayoutFlowAlt = docModule.TextDirection.LeftToRightRotated;
const tabInner = tab.Body.AddParagraph();
tabInner.Format.HorizontalAlignment = docModule.HorizontalAlignment.Center;
const tabText = tabInner.AppendText('合同正本');
tabText.CharacterFormat.FontSize = 9;
tabText.CharacterFormat.TextColor = docModule.Color.FromArgb(255, 255, 255, 255);
三枚文本框插入后,签署页同时具备印章、提示与页边标签。后文的读取与删除示例都以这份结果文件 ContractWithTextBoxes.docx 为输入,示例仓库中已经提供了该文件,可以直接从任意一节开始运行。
读取文本框中的内容
读取文本框中的内容,需要先进入文本框的 Body,再遍历其中的段落与图片。Document.TextBoxes 按插入顺序排列,下标从 0 开始;文本框内的图片位于其段落的子对象中,要单独向下遍历一层。
| 成员 | 作用 |
|---|---|
document.TextBoxes.Count |
文本框总数 |
document.TextBoxes.get_Item(index) |
按下标取得文本框 |
textBox.Body.ChildObjects |
文本框内的子对象集合 |
DocumentObjectType.Paragraph |
判断子对象是否为段落 |
DocumentObjectType.Picture |
判断子对象是否为图片 |
具体操作步骤如下:
- 载入包含文本框的
ContractWithTextBoxes.docx。 - 遍历
Document.TextBoxes集合。 - 对每个文本框遍历
Body.ChildObjects,累加段落的Text。 - 再遍历段落的子对象,统计
Picture的数量。 - 把结果写入 VFS 的文本文件,并触发下载。
读取文本框内容的代码如下:
const doc = new docModule.Document();
doc.LoadFromFile('ContractWithTextBoxes.docx');
const results = [];
for (let i = 0; i < doc.TextBoxes.Count; i++) {
const textBox = doc.TextBoxes.get_Item(i);
let text = '';
let pictureCount = 0;
for (let k = 0; k < textBox.Body.ChildObjects.Count; k++) {
const obj = textBox.Body.ChildObjects.get_Item(k);
if (obj.DocumentObjectType !== docModule.DocumentObjectType.Paragraph) continue;
text += obj.Text;
// 图片在段落的子对象中,需要再遍历一层
for (let j = 0; j < obj.ChildObjects.Count; j++) {
const child = obj.ChildObjects.get_Item(j);
if (child.DocumentObjectType === docModule.DocumentObjectType.Picture) {
pictureCount++;
}
}
}
results.push({ index: i, text: text.trim(), pictureCount });
}
// 把读取结果写入 VFS,并下载为文本文件
window.dotnetRuntime.Module.FS.writeFile(
'TextBoxes.txt', JSON.stringify(results, null, 2));
const report = window.dotnetRuntime.Module.FS.readFile('TextBoxes.txt');
const reportBlob = new Blob([report], { type: 'text/plain;charset=utf-8' });
const reportUrl = URL.createObjectURL(reportBlob);
const link = document.createElement('a');
link.href = reportUrl;
link.download = 'TextBoxes.txt';
link.click();
URL.revokeObjectURL(reportUrl);
示例合同中共有三个文本框,读取结果如下:索引 0 的印章框没有文字、含一张图片;索引 1 的提示框有 27 个字;索引 2 的页边标签为“合同正本”四个字。

页眉页脚中的文本框
在实测中,页眉中插入的文本框同样会收录到 Document.TextBoxes,保存并重新载入后依然如此,因此上面的遍历可以一并读到。如果业务上需要区分文本框来自正文还是页眉,可以按节遍历 HeadersFooters,分别读取页眉、页脚与正文的集合,再按来源归类。
删除 Word 文档中的文本框
删除 Word 文档中的文本框,按 Document.TextBoxes 的下标或整体清空即可。每删除一个,其后文本框的下标都会前移一位,连续删除多个时应从后向前处理,或每次都删除索引 0。
| 方法 | 作用 |
|---|---|
document.TextBoxes.RemoveAt(index) |
删除指定下标的文本框 |
document.TextBoxes.Clear() |
删除全部文本框 |
具体操作步骤如下:
- 载入需要清理的
ContractWithTextBoxes.docx。 - 读取删除前的
TextBoxes.Count,确认文本框数量。 - 调用
RemoveAt(index)删除单个文本框,或调用Clear()清空全部。 - 保存结果文件,从 VFS 读出并触发下载。
删除 Word 文档中的文本框的代码如下:
const doc = new docModule.Document();
doc.LoadFromFile('ContractWithTextBoxes.docx');
console.log('删除前:', doc.TextBoxes.Count);
// 删除第一个文本框
doc.TextBoxes.RemoveAt(0);
// 删除全部文本框(与上一行二选一)
// doc.TextBoxes.Clear();
console.log('删除后:', doc.TextBoxes.Count);
const outputFileName = 'ContractNoTextBoxes.docx';
doc.SaveToFile({ fileName: outputFileName, fileFormat: docModule.FileFormat.Docx2013 });
doc.Dispose();
// 后续从 VFS 读取并下载,代码同前
删除后,签署页上的印章、提示条与页边标签一并消失,正文与页眉页脚不受影响:

按条件删除文本框
清理模板时,通常只删除某一类文本框,例如文字中包含“提示”的临时说明。此时先读取每个文本框的文字,命中条件再删除;倒序遍历可以避免下标前移造成的漏删:
// 从后向前遍历,删除文字中包含“提示”的文本框
for (let i = doc.TextBoxes.Count - 1; i >= 0; i--) {
const textBox = doc.TextBoxes.get_Item(i);
let text = '';
for (let k = 0; k < textBox.Body.ChildObjects.Count; k++) {
const obj = textBox.Body.ChildObjects.get_Item(k);
if (obj.DocumentObjectType === docModule.DocumentObjectType.Paragraph) {
text += obj.Text;
}
}
if (text.includes('提示')) {
doc.TextBoxes.RemoveAt(i);
}
}
示例运行后,三个文本框中只剩印章与页边标签两个,提示条被移除。
设置文本框的文字方向
设置文本框的文字方向,通过 Format.LayoutFlowAlt 完成,取值来自 TextDirection 枚举。该属性只作用于文本框内部的排版,不影响正文;中文内容会按竖排方式自上而下排列,适合页边标签、封面与书名。
| 取值 | 实测效果 |
|---|---|
TextDirection.RightToLeft |
文字竖排,自上而下排列 |
TextDirection.LeftToRightRotated |
文字竖排,适合页边与封面标签 |
TextDirection.TopToBottom |
在本版本中仍按横排显示 |
TopToBottom 的名称容易让人以为它是竖排,但在 JavaScript 版本的实测中,该取值保存后仍是横排。需要竖排效果时,可以优先使用 RightToLeft 或 LeftToRightRotated,并在保存后于 Word 中核对实际渲染。
具体操作步骤如下:
- 载入包含文本框的
ContractWithTextBoxes.docx。 - 通过
get_Item(index)取得需要调整的文本框,示例取索引 1 的提示条。 - 将
Format.LayoutFlowAlt设为TextDirection.RightToLeft。 - 按竖排重新设置宽高与页面坐标,使文字落在页边。
- 保存结果文件,从 VFS 读出并触发下载。
设置文本框文字方向的代码如下:
const doc = new docModule.Document();
doc.LoadFromFile('ContractWithTextBoxes.docx');
// 取索引 1 的提示文本框
const textBox = doc.TextBoxes.get_Item(1);
// 竖排:文字自上而下排列
textBox.Format.LayoutFlowAlt = docModule.TextDirection.RightToLeft;
// 竖排后宽度变成列宽、高度变成列长,需要按内容重新设置
textBox.Format.Width = 46;
textBox.Format.Height = 306;
// 移到左侧页边
textBox.Format.HorizontalOrigin = docModule.HorizontalOrigin.Page;
textBox.Format.HorizontalPosition = 16;
textBox.Format.VerticalOrigin = docModule.VerticalOrigin.Page;
textBox.Format.VerticalPosition = 270;
const outputFileName = 'ContractVerticalTextBox.docx';
doc.SaveToFile({ fileName: outputFileName, fileFormat: docModule.FileFormat.Docx2013 });
doc.Dispose();
// 后续从 VFS 读取并下载,代码同前
调整后,原本横向的提示条变成左侧页边的竖排标签,阅读顺序自上而下:

文字方向改变后为什么要重设宽高
横排时,文本框的宽度决定每行字数,高度决定行数;竖排后两者互换,宽度变成每列字数,高度变成一列可容纳的字数。示例中的提示条约 27 个字,改为 46 磅宽、306 磅高后,刚好排成一列并完整显示。若沿用原来的宽高,文字可能被截断或溢出文本框,需要按字数与字号重新估算。
常见问题
遍历正文时为什么读不到文本框
原因:文本框不是正文的段落或表格,而是悬挂在段落下的子对象。正文遍历只处理 Body.ChildObjects 中的段落与表格,自然不会命中文本框。
解决:直接遍历 Document.TextBoxes;如果从段落进入,需要检查段落子对象的 DocumentObjectType,再访问其 Body。
页眉页脚中的文本框会被读到吗
在实测中会。页眉中插入的文本框同样计入 Document.TextBoxes,保存并重新载入后仍然如此,因此按文档级集合遍历时不会遗漏。若需要区分来源,可以分别遍历各节 HeadersFooters 中的正文容器,按来源归类。
删除文本框后,正文里为什么还留着一个空段落
原因:RemoveAt 与 Clear 删除的是文本框对象本身,承载它的锚点段落仍然保留。锚点段落没有其他内容时,页面上可能表现为一个空行。
解决:删除前记录承载文本框的段落,删除后按版式要求决定是否一并移除该段落;清理模板时也可以把“无文字、无子对象”的段落统一处理。
设置了 TopToBottom,文字为什么还是横排
原因:TextDirection 各取值在 JavaScript 版本中的实际效果与名称并不完全一致。实测中 TopToBottom 保存后仍为横排,而 RightToLeft 与 LeftToRightRotated 可以得到竖排效果。
解决:改用 RightToLeft 或 LeftToRightRotated,保存后在 Word 中确认渲染结果;不同版本对枚举的实现可能不同,升级后应重新核对。
按页面坐标定位的文本框,位置为什么不准确
常见原因有三种:没有把 HorizontalOrigin 与 VerticalOrigin 设为 Page,坐标被当成段落偏移;坐标单位不是磅;或者设置了对齐属性 ShapeVerticalAlignment。在实测中,设置纵向对齐后,文本框的纵向位置会按页面重新居中,原先的 VerticalPosition 不再生效。建议先设置页面坐标,再处理框内文字的对齐。
获取免费许可证
如果您希望删除结果文档中的评估消息,或者摆脱功能限制,请该Email地址已收到反垃圾邮件插件保护。要显示它您需要在浏览器中启用JavaScript。获取有效期 30 天的临时许可证。







