文档半岛外围网上直营>>E-iceblue中文文档>>用图片替换Word中的文字
用图片替换Word中的文字
在 Spire.Doc 的教程部分,我们介绍了“用 C# 中的表格替换 Word 中的文本”和“用 C# 中的文本替换 Word 中的图像”的简单方法。有时,我们需要将 Word 中的文本替换为图像。Spire.Doc 还提供了一种快速有效的解决方案,可以通过稍微不同的代码来实现此功能。本文将介绍在Word中用图像替换文本的方法。
注意:开始之前,请下载最新版本的Spire.Doc,并将Spire.Doc.dll添加到bin文件夹中,作为visual studio的参考。
样本文件:
第 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");
效果:
完整代码:
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");
}
}
}

QQ交谈
在线咨询

渝公网安备
50010702500608号

客服热线