翻譯|使用教程|編輯:胡濤|2022-08-15 10:06:25.520|閱讀 189 次
概述:本文將介紹在Word中用圖像替換文本的方法。
# 界面/圖表報表/文檔/IDE等千款熱門軟控件火熱銷售中 >>
相關鏈接:
在 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"); } } }
歡迎下載|體驗更多E-iceblue產品
本站文章除注明轉載外,均為本站原創或翻譯。歡迎任何形式的轉載,但請務必注明出處、不得修改原文相關鏈接,如果存在內容上的異議請郵件反饋至chenjj@fc6vip.cn