標籤:.net c# ppt
在圖文混排的文檔中,我們可以根據需要將文檔中的文字資訊或者圖片提取出來,通過C#代碼可以提取Word和PDF檔案中的文本和圖片,那麼同樣的,我們也可以提取PPT投影片當中的文本和圖片。本篇文檔將講述如何使用C#來實現提取PPT文本和圖片的操作。首先也是需要安裝組件Spire.Presentation,然後添加引用dll檔案到項目中。下面是主要的代碼步驟。
原文檔:
650) this.width=650;" src="https://s2.51cto.com/oss/201711/02/5c457371f706afa2a1849c02de436ace.png" style="float:none;" title="21.png" alt="5c457371f706afa2a1849c02de436ace.png" />
1. 提取文本
步驟一:建立一個Presentation執行個體並載入文檔
Presentation presentation = newPresentation(@"C:\Users\Administrator\Desktop\sample.pptx", FileFormat.Pptx2010);
步驟二:建立一個StringBuilder對象
StringBuilder sb = newStringBuilder();
步驟三:遍曆投影片及投影片中的圖形,提取常值內容
foreach (ISlide slide in presentation.Slides) { foreach (IShape shape in slide.Shapes) { if (shape isIAutoShape) { foreach (TextParagraph tp in (shape asIAutoShape).TextFrame.Paragraphs) { sb.Append(tp.Text +Environment.NewLine); } } } }
步驟四:寫入Txt文檔
File.WriteAllText("target.txt", sb.ToString());Process.Start("target.txt");
650) this.width=650;" src="https://s2.51cto.com/oss/201711/02/5be16c77c6ea256a5e4e98d1855a7023.png" style="float:none;" title="22.png" alt="5be16c77c6ea256a5e4e98d1855a7023.png" />
2. 提取圖片
這裡提取圖片有兩種情況,一種是提取整個文檔中的所有圖片,另外一種是只提取文檔中某一特定投影片中的圖片。
2.1提取所有圖片
步驟一:初始化一個Presentation類執行個體,並載入文檔
Presentation ppt = newPresentation();ppt.LoadFromFile(@"C:\Users\Administrator\Desktop\sample.pptx");
步驟二:遍曆文檔中圖片,提取圖片並儲存
for (int i = 0; i <ppt.Images.Count; i++) { Image image = ppt.Images[i].Image; image.Save(string.Format(@"..\..\Images{0}.png", i)); }
提取的圖片已儲存到專案檔夾下
650) this.width=650;" src="https://s2.51cto.com/oss/201711/02/ea2a491c2e1e45c15501bee5b25b47fb.png" style="float:none;" title="23.png" alt="ea2a491c2e1e45c15501bee5b25b47fb.png" />
2.2.提取特定投影片中的圖片
步驟一:建立一個Presentation類執行個體,並載入文檔
Presentation PPT = newPresentation();PPT.LoadFromFile(@"C:\Users\Administrator\Desktop\sample.pptx");
步驟二:擷取第三張投影片,提取並儲存圖片
int i = 0;foreach (IShape s inPPT.Slides[2].Shapes){ if (s isSlidePicture) { SlidePicture ps = s asSlidePicture; ps.PictureFill.Picture.EmbedImage.Image.Save(string.Format("{0}.png", i)); i++; } if (s isPictureShape) { PictureShape ps = s asPictureShape; ps.EmbedImage.Image.Save(string.Format("{0}.png", i)); i++; }}
提取的第三張投影片中的圖片已儲存至指定位置
650) this.width=650;" src="https://s4.51cto.com/oss/201711/02/9ac544f080e7be678df0f9651913b671.png" style="float:none;" title="24.png" alt="9ac544f080e7be678df0f9651913b671.png" />
上文示範了如何提取文本和圖片,步驟比較簡單實用,希望對你有所協助,感謝閱讀!
(如需轉載,請註明出處和作者)
本文出自 “E-iceblue” 部落格,請務必保留此出處http://eiceblue.blog.51cto.com/13438008/1978495
C# 提取PPT文本和圖片的實現方案