C# 提取PPT文本和圖片的實現方案


在圖文混排的文檔中,我們可以根據需要將文檔中的文字信息或者圖片提取出來,通過C#代碼可以提取Word和PDF文件中的文本和圖片,那么同樣的,我們也可以提取PPT幻燈片當中的文本和圖片。本篇文檔將講述如何使用C#來實現提取PPT文本和圖片的操作。首先也是需要安裝組件Spire.Presentation,然后添加引用dll文件到項目中。下面是主要的代碼步驟。

原文檔:

 

1. 提取文本

步驟一:創建一個Presentation實例並加載文檔

Presentation presentation = new Presentation(@"C:\Users\Administrator\Desktop\sample.pptx", FileFormat.Pptx2010);

步驟二:創建一個StringBuilder對象

StringBuilder sb = new StringBuilder();

 步驟三:遍歷幻燈片及幻燈片中的圖形,提取文本內容

 foreach (ISlide slide in presentation.Slides)
            {
                foreach (IShape shape in slide.Shapes)
                {
                    if (shape is IAutoShape)
                    {
                        foreach (TextParagraph tp in (shape as IAutoShape).TextFrame.Paragraphs)
                        {
                            sb.Append(tp.Text + Environment.NewLine);
                        }
                    }
                }
            }

步驟四:寫入Txt文檔

 File.WriteAllText("target.txt", sb.ToString());
 Process.Start("target.txt");

 

2. 提取圖片

 這里提取圖片有兩種情況,一種是提取整個文檔中的所有圖片,另外一種是只提取文檔中某一特定幻燈片中的圖片。

     2.1提取所有圖片

步驟一:初始化一個Presentation類實例,並加載文檔

 Presentation ppt = new Presentation();
 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));
 }

提取的圖片已保存到項目文件夾下

       2.2.提取特定幻燈片中的圖片

步驟一:創建一個Presentation類實例,並加載文檔

Presentation PPT = new Presentation();
PPT.LoadFromFile(@"C:\Users\Administrator\Desktop\sample.pptx");

步驟二:獲取第三張幻燈片,提取並保存圖片

int i = 0;
foreach (IShape s in PPT.Slides[2].Shapes)
{
    if (s is SlidePicture)
    {
        SlidePicture ps = s as SlidePicture;
        ps.PictureFill.Picture.EmbedImage.Image.Save(string.Format("{0}.png", i));
        i++;
    }
    if (s is PictureShape)
    {
        PictureShape ps = s as PictureShape;
        ps.EmbedImage.Image.Save(string.Format("{0}.png", i));
        i++;
    }
}

提取的第三張幻燈片中的圖片已保存至指定位置

 

上文演示了如何提取文本和圖片,步驟比較簡單實用,希望對你有所幫助,感謝閱讀!

如需轉載請注明出處。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM