超链接是 Word 文档中不可或缺的交互元素,广泛应用于指向网页、电子邮件地址、文档内部位置或外部文件。Spire.Doc for JavaScript 基于 WebAssembly 在浏览器端直接完成超链接的插入、查找、修改与移除操作,通过虚拟文件系统(VFS)管理输入输出文件,无需后端服务支持。
本文介绍三个核心功能点:
有关安装和项目配置,请参考 React 项目中集成 Spire.Doc for JavaScript。以下示例默认已安装 Spire.Doc 并完成 WebAssembly 模块初始化。
插入超链接
插入超链接的核心流程分为三个阶段:首先通过 FetchFileToVFS 将字体文件载入 WASM 虚拟文件系统;然后实例化 Document,在段落中通过 AppendHyperlink 方法插入网页链接、邮件链接或图片链接;最后保存文档并从 VFS 读取生成的文件,封装为 Blob 后触发浏览器下载。
function App() {
const insertHyperlinks = async () => {
// 获取 Spire.Doc WASM 模块
const docModule = window.wasmModule?.spiredoc;
// 检查模块是否就绪
if (!docModule) {
alert('Spire.Doc is not ready yet');
return;
}
const imageFileName = 'Spire.Doc.png';
await window.spire.FetchFileToVFS(imageFileName, '', `${process.env.PUBLIC_URL}/data/`);
// 创建文档对象
const doc = new docModule.Document();
const section = doc.AddSection();
// 插入网页链接
let paragraph = section.AddParagraph();
paragraph.AppendText("Home page");
paragraph.ApplyStyle({ builtinStyle: docModule.BuiltinStyle.Heading2 });
paragraph = section.AddParagraph();
paragraph.AppendHyperlink("www.e-iceblue.com", "www.e-iceblue.com", docModule.HyperlinkType.WebLink);
// 插入邮件链接
paragraph = section.AddParagraph();
paragraph.AppendText("Contact US");
paragraph.ApplyStyle({ builtinStyle: docModule.BuiltinStyle.Heading2 });
paragraph = section.AddParagraph();
paragraph.AppendHyperlink("mailto:support@ e-iceblue.com", "support@ e-iceblue.com", docModule.HyperlinkType.EMailLink);
// 插入图片链接
paragraph = section.AddParagraph();
paragraph.AppendText("Insert Link On Image");
paragraph.ApplyStyle({ builtinStyle: docModule.BuiltinStyle.Heading2 });
paragraph = section.AddParagraph();
const picture = paragraph.AppendPicture({ imgFile: imageFileName });
paragraph.AppendHyperlink("www.e-iceblue.com", picture, docModule.HyperlinkType.WebLink);
// 定义输出文件名
const outputFileName = "Hyperlink_output.docx";
// 保存文档
doc.SaveToFile({ fileName: outputFileName, fileFormat: docModule.FileFormat.Docx2013 });
// 从 VFS 读取生成的文件,触发下载
const modifiedFileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
const blob = new Blob([modifiedFileArray], { 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= {insertHyperlinks}>
Generate
</button>
</div>
);
}
export default App;
通过 AppendHyperlink 方法插入网页链接和邮件链接后,生成的 Word 文档中包含可点击的超链接文本与图片链接。

查找并修改超链接
对于已包含超链接的 Word 文档,可以通过遍历文档对象模型找到所有超链接字段,并获取或修改其显示文本。
function App() {
const findAndModifyHyperlinks = async () => {
// 获取 Spire.Doc WASM 模块
const docModule = window.wasmModule?.spiredoc;
// 检查模块是否就绪
if (!docModule) {
alert('Spire.Doc is not ready yet');
return;
}
const inputFileName = 'Hyperlinks.docx';
await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/static/data/`);
// 加载文档
const doc = new docModule.Document();
doc.LoadFromFile(inputFileName);
// 遍历文档中所有超链接
let hyperlinks = [];
for (let i = 0; i < doc.Sections.Count; i++) {
let section = doc.Sections.get_Item(i);
for (let j = 0; j < section.Body.ChildObjects.Count; j++) {
let sec = section.Body.ChildObjects.get_Item(j);
if (sec.DocumentObjectType == docModule.DocumentObjectType.Paragraph) {
for (let k = 0; k < sec.ChildObjects.Count; k++) {
let para = sec.ChildObjects.get_Item(k);
if (para.DocumentObjectType == docModule.DocumentObjectType.Field) {
let field = para;
if (field.Type == docModule.FieldType.FieldHyperlink) {
hyperlinks.push(field);
}
}
}
}
}
}
// 修改第一个超链接的显示文本
hyperlinks[0].FieldText = "Spire.Doc component";
// 定义输出文件名
const outputFileName = "ModifyHyperlinkText_output.docx";
// 保存文档
doc.SaveToFile({ fileName: outputFileName, fileFormat: docModule.FileFormat.Docx2013 });
// 从 VFS 读取生成的文件,触发下载
const modifiedFileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
const blob = new Blob([modifiedFileArray], { 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);
// 释放资源
doc.Dispose();
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>Find & Modify Hyperlinks</h1>
<button onClick={findAndModifyHyperlinks}>
Generate
</button>
</div>
);
}
export default App;
通过遍历文档对象模型找到所有超链接后,可以读取或修改每个超链接的显示文本与目标地址,满足批量更新需求。

移除超链接
当文档中的超链接不再需要时,可以将其移除,同时保留超链接对应的文本内容。核心思路是先找到所有超链接字段,然后通过扁平化(Flatten)操作将字段结构拆解,仅保留普通文本并去除超链接格式。
// 查找文档中所有超链接
function FindAllHyperlinks(document) {
let docModule = window.wasmModule.spiredoc;
let hyperlinks = [];
for (let i = 0; i < document.Sections.Count; i++) {
let section = document.Sections.get_Item(i);
for (let j = 0; j < section.Body.ChildObjects.Count; j++) {
let sec = section.Body.ChildObjects.get_Item(j);
if (sec.DocumentObjectType == docModule.DocumentObjectType.Paragraph) {
for (let k = 0; k < sec.ChildObjects.Count; k++) {
let para = sec.ChildObjects.get_Item(k);
if (para.DocumentObjectType == docModule.DocumentObjectType.Field) {
let field = para;
if (field.Type == docModule.FieldType.FieldHyperlink) {
hyperlinks.push(field);
}
}
}
}
}
}
return hyperlinks;
}
// 移除超链接格式,仅保留文本
function FormatFieldResultText(ownerBody, sepOwnerParaIndex, endOwnerParaIndex, sepIndex, endIndex) {
let docModule = window.wasmModule.spiredoc;
for (let i = sepOwnerParaIndex; i <= endOwnerParaIndex; i++) {
let para = ownerBody.ChildObjects.get_Item(i);
if (i == sepOwnerParaIndex && i == endOwnerParaIndex) {
for (let j = sepIndex + 1; j < endIndex; j++) {
let tr = para.ChildObjects.get_Item(j);
tr.CharacterFormat.TextColor = docModule.Color.get_Black();
tr.CharacterFormat.UnderlineStyle = docModule.UnderlineStyle.None;
}
} else if (i == sepOwnerParaIndex) {
for (let j = sepIndex + 1; j < para.ChildObjects.Count; j++) {
let tr = para.ChildObjects.get_Item(j);
tr.CharacterFormat.TextColor = docModule.Color.get_Black();
tr.CharacterFormat.UnderlineStyle = docModule.UnderlineStyle.None;
}
} else if (i == endOwnerParaIndex) {
for (let j = 0; j < endIndex; j++) {
let tr = para.ChildObjects.get_Item(j);
tr.CharacterFormat.TextColor = docModule.Color.get_Black();
tr.CharacterFormat.UnderlineStyle = docModule.UnderlineStyle.None;
}
} else {
for (let j = 0; j < para.ChildObjects.Count; j++) {
let tr = para.ChildObjects.get_Item(j);
tr.CharacterFormat.TextColor = docModule.Color.get_Black();
tr.CharacterFormat.UnderlineStyle = docModule.UnderlineStyle.None;
}
}
}
}
function FlattenHyperlinks(field) {
// 获取超链接字段各组成部分的位置索引
let ownerParaIndex = field.OwnerParagraph.OwnerTextBody.ChildObjects.IndexOf(field.OwnerParagraph);
let fieldIndex = field.OwnerParagraph.ChildObjects.IndexOf(field);
let sepOwnerPara = field.Separator.OwnerParagraph;
let sepOwnerParaIndex = field.Separator.OwnerParagraph.OwnerTextBody.ChildObjects.IndexOf(field.Separator.OwnerParagraph);
let sepIndex = field.Separator.OwnerParagraph.ChildObjects.IndexOf(field.Separator);
let endIndex = field.End.OwnerParagraph.ChildObjects.IndexOf(field.End);
let endOwnerParaIndex = field.End.OwnerParagraph.OwnerTextBody.ChildObjects.IndexOf(field.End.OwnerParagraph);
// 移除超链接格式(蓝色下划线)
FormatFieldResultText(field.Separator.OwnerParagraph.OwnerTextBody, sepOwnerParaIndex, endOwnerParaIndex, sepIndex, endIndex);
// 移除超链接字段结构
field.End.OwnerParagraph.ChildObjects.RemoveAt(endIndex);
for (let i = sepOwnerParaIndex; i >= ownerParaIndex; i--) {
if (i == sepOwnerParaIndex && i == ownerParaIndex) {
for (let j = sepIndex; j >= fieldIndex; j--) {
field.OwnerParagraph.ChildObjects.RemoveAt(j);
}
} else if (i == ownerParaIndex) {
for (let j = field.OwnerParagraph.ChildObjects.Count - 1; j >= fieldIndex; j--) {
field.OwnerParagraph.ChildObjects.RemoveAt(j);
}
} else if (i == sepOwnerParaIndex) {
for (let j = sepIndex; j >= 0; j--) {
sepOwnerPara.ChildObjects.RemoveAt(j);
}
} else {
field.OwnerParagraph.OwnerTextBody.ChildObjects.RemoveAt(i);
}
}
}
function App() {
const removeHyperlinks = async () => {
// 获取 Spire.Doc WASM 模块
const docModule = window.wasmModule?.spiredoc;
// 检查模块是否就绪
if (!docModule) {
alert('Spire.Doc is not ready yet');
return;
}
const inputFileName = 'Hyperlinks.docx';
await window.spire.FetchFileToVFS(inputFileName, '', `${process.env.PUBLIC_URL}/data/`);
// 加载文档
const doc = new docModule.Document();
doc.LoadFromFile(inputFileName);
// 查找所有超链接
let hyperlinks = FindAllHyperlinks(doc);
// 扁平化所有超链接(移除超链接格式,保留文本)
for (let i = hyperlinks.length - 1; i >= 0; i--) {
FlattenHyperlinks(hyperlinks[i]);
}
// 定义输出文件名
const outputFileName = "RemoveHyperlinks_output.docx";
// 保存文档
doc.SaveToFile({ fileName: outputFileName, fileFormat: docModule.FileFormat.Docx2013 });
// 从 VFS 读取生成的文件,触发下载
const modifiedFileArray = window.dotnetRuntime.Module.FS.readFile(outputFileName);
const blob = new Blob([modifiedFileArray], { 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);
// 释放资源
doc.Dispose();
};
return (
<div style={{ textAlign: 'center', height: '300px' }}>
<h1>移除超链接。</h1>
<button onClick={removeHyperlinks}>
Generate
</button>
</div>
);
}
export default App;
移除超链接后,文档中的超链接文本保留为普通文本,原有的蓝色下划线样式被清除,内容保持不变。

常见问题
插入的超链接在文档中无法点击
原因:插入的链接目标地址格式不正确,例如缺少协议前缀(如 http:// 或 mailto:)导致 Word 无法识别为有效的可点击链接。
解决:确保网页链接使用完整的 URL,邮件链接添加 mailto: 前缀:
// 正确的网页链接
paragraph.AppendHyperlink("https://www.e-iceblue.com", "e-iceblue", docModule.HyperlinkType.WebLink);
// 正确的邮件链接
paragraph.AppendHyperlink("mailto:support@ e-iceblue.com", "support@ e-iceblue.com", docModule.HyperlinkType.EMailLink);
移除超链接后文字样式异常
原因:仅移除了超链接字段结构,但未将文字颜色和下划线样式重置为普通文本样式。
解决:扁平化超链接时,同步将文字颜色设为黑色、下划线样式设为无:
tr.CharacterFormat.TextColor = docModule.Color.get_Black();
tr.CharacterFormat.UnderlineStyle = docModule.UnderlineStyle.None;
获取免费许可证
如果您希望删除结果文档中的评估消息,或者摆脱功能限制,请该Email地址已收到反垃圾邮件插件保护。要显示它您需要在浏览器中启用JavaScript。获取有效期 30 天的临时许可证。







