翻譯|使用教程|編輯:胡濤|2022-10-08 10:08:31.100|閱讀 163 次
概述:本文主要介紹如何在 C#、VB.NET 中從 Word 中提取圖像。
# 界面/圖表報表/文檔/IDE等千款熱門軟控件火熱銷售中 >>
相關鏈接:
Spire.Doc for .NET是一款專門對 Word 文檔進行操作的 .NET 類庫。在于幫助開發人員無需安裝 Microsoft Word情況下,輕松快捷高效地創建、編輯、轉換和打印 Microsoft Word 文檔。擁有近10年專業開發經驗Spire系列辦公文檔開發工具,專注于創建、編輯、轉換和打印Word/PDF/Excel等格式文件處理,小巧便捷。在 C#、VB.NET 中從 Word 中提取圖像。
讓我們看看 Spire.Doc 是如何幫助開發人員解決與 Office 技術編程相關的問題。根據描述,發帖人希望將Word文件中的每張圖片對應替換為“Here was image {image index}”。但是,我們想提供一個帶有以下示例代碼的解決方案。
測試文件:
用文本替換圖像的代碼片段;
第 1 步:創建一個新的 Word 文檔并加載測試文件。
Document document = new Document(@"..\..\test.docx");
第 2 步:獲取Word文檔中的所有圖片并將它們替換為文本“Here was image {image index}”。
int j = 1; foreach (Section sec in document.Sections) { foreach (Paragraph para in sec.Paragraphs) { List pictures = new List(); foreach (DocumentObject docObj in para.ChildObjects) { if (docObj.DocumentObjectType == DocumentObjectType.Picture) { pictures.Add(docObj); } } foreach (DocumentObject pic in pictures) { int index = para.ChildObjects.IndexOf(pic); TextRange range = new TextRange(document); range.Text = string.Format("Here was image {0}", j); para.ChildObjects.Insert(index, range); para.ChildObjects.Remove(pic); j++; } } }
第 3 步:保存并啟動文件。
document.SaveToFile(@"..\..\result.docx", FileFormat.Docx); System.Diagnostics.Process.Start(@"..\..\result.docx");
結果:
完整的 C# 代碼:
[C#]
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; using Spire.Doc.Interface; using System.Drawing; namespace ReplaceImageWithText { class Program { static void Main(string[] args) { Document document = new Document(@"..\..\test.docx"); int j = 1; foreach (Section sec in document.Sections) { foreach (Paragraph para in sec.Paragraphs) { List pictures = new List(); foreach (DocumentObject docObj in para.ChildObjects) { if (docObj.DocumentObjectType == DocumentObjectType.Picture) { pictures.Add(docObj); } } foreach (DocumentObject pic in pictures) { int index = para.ChildObjects.IndexOf(pic); TextRange range = new TextRange(document); range.Text = string.Format("Here was image {0}", j); para.ChildObjects.Insert(index, range); para.ChildObjects.Remove(pic); j++; } } } document.SaveToFile(@"..\..\result.docx", FileFormat.Docx); System.Diagnostics.Process.Start(@"..\..\result.docx"); } } }
以上便是如何在 C#/VB.NET 中的指定位置插入圖像,如果您有其他問題也可以繼續瀏覽本系列文章,獲取相關教程,你還可以給我留言或者加入我們的官方技術交流群。
歡迎下載|體驗更多E-iceblue產品
本站文章除注明轉載外,均為本站原創或翻譯。歡迎任何形式的轉載,但請務必注明出處、不得修改原文相關鏈接,如果存在內容上的異議請郵件反饋至chenjj@fc6vip.cn