如何使用C#從word文檔中提取圖片
圖片和文字是word文檔中兩種最常見的對象,在微軟word中,如果我們想要提取出一個文檔內(nèi)的圖片,只需要右擊圖片選擇另存為然后命名保存就可以了,今天這篇文章主要是實(shí)現(xiàn)如何使用C#從word文檔中提取圖片。
這里我準(zhǔn)備了一個含有文字和圖片的word文檔:
詳細(xì)步驟與代碼:
步驟1 : 添加引用。
新建一個Visual C#控制臺項(xiàng)目,添加引用并使用如下命名空間:
using System; using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields;
步驟2 : 新建一個word文檔對象并加載需要提取圖片的word文檔。
Document document = new Document("法國景點(diǎn).docx ");
步驟3 : 遍歷文檔中的所有section,找到圖片,將它們提取出來并保存。
int index = 0; //獲取文檔的section foreach (Section section in document.Sections) { //獲取section中的段落 foreach (Paragraph paragraph in section.Paragraphs) { //獲取段落中的文檔對象 foreach (DocumentObject docObject in paragraph.ChildObjects) { //對對象的type進(jìn)行判斷,如果是圖片,就提取出來 if (docObject.DocumentObjectType == DocumentObjectType.Picture) { DocPicture picture = docObject as DocPicture; //給圖片命名 String imageName = String.Format(@"images\Image-{0}.png", index); //保存圖片 picture.Image.Save(imageName, System.Drawing.Imaging.ImageFormat.Png); index++; } } } }
提取出來的圖片:
全部代碼:
using System; using Spire.Doc; using Spire.Doc.Documents; using Spire.Doc.Fields; using System.Drawing; namespace Extract_image_from_word { class Program { static void Main(string[] args) { Document document = new Document("法國景點(diǎn).docx"); int index = 0; foreach (Section section in document.Sections) { foreach (Paragraph paragraph in section.Paragraphs) { foreach (DocumentObject docObject in paragraph.ChildObjects) { if (docObject.DocumentObjectType == DocumentObjectType.Picture) { DocPicture picture = docObject as DocPicture; String imageName = String.Format(@"images\Image-{0}.png", index); picture.Image.Save(imageName, System.Drawing.Imaging.ImageFormat.Png); index++; } } } } } } }
總結(jié):
這里我使用的是E-iceblue公司的免費(fèi) word 組件,它除了可以從文檔中提取圖片,還可以提取文本,這里我只寫了提取圖片的,提取文本的也差不多,如有需要可以留言。
相關(guān)文章
C#中const,readonly和static關(guān)鍵字的用法介紹
這篇文章介紹了C#中const,readonly和static關(guān)鍵字的用法,文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-08-08C# WinForm 判斷程序是否已經(jīng)在運(yùn)行,且只允許運(yùn)行一個實(shí)例,附源碼
本文主要介紹WinFrom程序中只允許運(yùn)行一個實(shí)例的方法,并有完整的代碼示例,希望能給需要的朋友一些幫助。2016-04-04C#基于ScottPlot實(shí)現(xiàn)可視化的示例代碼
這篇文章主要為大家詳細(xì)介紹了C#如何基于ScottPlot實(shí)現(xiàn)可視化效果,文中的示例代碼講解詳細(xì),具有一定的借鑒價值,感興趣的小伙伴可以跟隨小編一起學(xué)習(xí)一下2024-01-01Unity編輯器預(yù)制體工具類PrefabUtility常用函數(shù)和用法
這篇文章主要為大家介紹了Unity編輯器預(yù)制體工具類PrefabUtility常用函數(shù)及用法詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-08-08