文檔半島外圍網上直營>>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交談
QQ交談 在線咨詢
在線咨詢 
                 
                
 渝公網安備
            50010702500608號
渝公網安備
            50010702500608號
             
            
 客服熱線
客服熱線