半岛权威十大直营(官方)网站

Word控件Spire.Doc 【文本】教程(14) ;如何用图片替换Word中的文字

翻译|使用教程|编辑:胡涛|2022-08-15 10:06:25.520|阅读 127 次

概述:本文将介绍在Word中用图像替换文本的方法。

# 界面/图表报表/文档/IDE等千款热门软控件火热销售中 >>

相关链接:

在 Spire.Doc 的教程部分,我们介绍了“用 C# 中的表格替换 Word 中的文本”和“用 C# 中的文本替换 Word 中的图像”的简单方法。有时,我们需要将 Word 中的文本替换为图像。Spire.Doc 还提供了一种快速有效的解决方案,可以通过稍微不同的代码来实现此功能。本文将介绍在Word中用图像替换文本的方法。

Spire.Doc for.NET 最新下载

注意:开始之前,请下载最新版本的Spire.Doc,并将Spire.Doc.dll添加到bin文件夹中,作为visual studio的参考。

样本文件

如何用图片替换Word中的文字

第 1 步:加载示例 Word 文档和用于替换文本的图像。

Document document = new Document();
document.LoadFromFile("s.docx");
Image image = Image.FromFile("2.bmp");

第 2 步:在文档中找到字符串“E-iceblue”。

TextSelection[] selections = document.FindAllString("E-iceblue", true, true);
int index = 0;
TextRange range = null;

第 3 步:删除文本并将其替换为图像

foreach (TextSelection selection in selections)
{
DocPicture pic = new DocPicture(document);
pic.LoadImage(image);

range = selection.GetAsOneRange();
index = range.OwnerParagraph.ChildObjects.IndexOf(range);
range.OwnerParagraph.ChildObjects.Insert(index, pic);
range.OwnerParagraph.ChildObjects.Remove(range);

}

第 4 步:保存并启动文档以查看效果。

document.SaveToFile("Sample.doc", FileFormat.Doc);
System.Diagnostics.Process.Start("Sample.doc");

效果

如何用图片替换Word中的文字

完整代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System.Drawing;

namespace Replace_Text_with_Image
{
class Program
{
static void Main(string[] args)
{
Document document = new Document();
document.LoadFromFile("s.docx");
Image image = Image.FromFile("2.bmp");

TextSelection[] selections = document.FindAllString("E-iceblue", true, true);
int index = 0;
TextRange range = null;

foreach (TextSelection selection in selections)
{
DocPicture pic = new DocPicture(document);
pic.LoadImage(image);

range = selection.GetAsOneRange();
index = range.OwnerParagraph.ChildObjects.IndexOf(range);
range.OwnerParagraph.ChildObjects.Insert(index, pic);
range.OwnerParagraph.ChildObjects.Remove(range);

}

document.SaveToFile("Sample.doc", FileFormat.Doc);
System.Diagnostics.Process.Start("Sample.doc");

}
}
}

欢迎下载|体验更多E-iceblue产品

获取更多信息请咨询  ;技术交流Q群(767755948)


标签:

本站文章除注明转载外,均为本站原创或翻译。欢迎任何形式的转载,但请务必注明出处、不得修改原文相关链接,如果存在内容上的异议请邮件反馈至chenjj@wqylolg.cn


为你推荐

  • 推荐视频
  • 推荐活动
  • 推荐产品
  • 推荐文章
  • 慧都慧问
相关产品
Spire.Office for .NET

专业的.NET Office套件,涵盖office文档创建、编辑、转换、管理和OCR内容识别等操作

Spire.Doc for .NET

Spire.Doc for .NET 是一款专门对 Word 文档进行操作的 .NET 类库。

Spire.XLS for .NET

Spire.XLS for .NET是专业.NET Excel组件,快速完成对Excel各类编程操作

Aspose.Cells for .NET

专业的电子表格控件,无需MS Excel也可满足一切Excel表格功能。

Aspose.Words for .NET

无需Microsoft Word也可在任何平台上满足Word文档的一切操作需求。

title
title
title
扫码咨询


添加微信 立即咨询

电话咨询

客服热线
023-68661681

TOP