![從 PowerPoint C# 中提取文本](images/Extract-Text-from-PowerPoint.jpg#center)
您可能經常需要從 PowerPoint 幻燈片中提取文本以執行文本分析。另一方面,您可能希望提取文本並將其保存在文件或數據庫中以供進一步處理。根據這一點,本文介紹瞭如何使用 C# 從 PowerPoint 演示文稿中提取文本。特別是,您將學習如何從特定幻燈片或整個演示文稿中提取文本。
從 PowerPoint PPTX 中提取文本的 C# API
為了操作 PowerPoint 演示文稿,Aspose 提供了 Aspose.Slides for .NET。上述 API 旨在在 .NET 應用程序中實現 PowerPoint 自動化功能。它還提供了一些從 PPTX 演示文稿中提取文本的簡單方法。您可以 下載 API 或使用 NuGet 安裝它。
PM> Install-Package Aspose.Slides.NET
在 C# 中從 PowerPoint 幻燈片中提取文本
以下是從 PowerPoint 演示文稿的幻燈片中提取文本的步驟。
- 使用 Presentation 類加載演示文稿。
- 使用 SlideUtil.GetAllTextBoxes() 方法將幻燈片中的所有文本框放入 ITextFrame 數組。
- 遍歷每個 ITextFrame 並使用 ITextFrame.Paragraphs 屬性訪問其文本。
- 從段落的每個 部分 中檢索並打印文本。
以下代碼示例演示如何使用 C# 從 PowerPoint 幻燈片中提取文本。
//實例化表示 PPTX 文件的 PresentationEx 類
Presentation pptxPresentation = new Presentation("demo.pptx");
//從第一張幻燈片中獲取 TextFrameEx 對像數組
ITextFrame[] textFramesSlideOne = SlideUtil.GetAllTextBoxes(pptxPresentation.Slides[0]);
//遍歷 TextFrames 數組
for (int i = 0; i < textFramesSlideOne.Length; i++)
{
//循環遍歷當前 TextFrame 中的段落
foreach (Paragraph para in textFramesSlideOne[i].Paragraphs)
{
//遍歷當前段落中的部分
foreach (Portion port in para.Portions)
{
//在當前部分顯示文本
Console.WriteLine(port.Text);
//顯示文本的字體高度
Console.WriteLine(port.PortionFormat.FontHeight);
//顯示文本的字體名稱
Console.WriteLine(port.PortionFormat.LatinFont.FontName);
}
}
}
在 C# 中從 PowerPoint 演示文稿中提取文本
您還可以使用 Aspose.Slides for .NET 從整個 PowerPoint 演示文稿中提取文本。以下是執行此操作的步驟。
- 使用 Presentation 類加載演示文稿。
- 使用 SlideUtil.GetAllTextFrames() 方法獲取演示文稿中的所有文本框。
- 遍歷每個 ITextFrame 並訪問其 Paragraphs。
- 訪問段落的各個部分並打印其文本。
以下代碼示例顯示如何從 PowerPoint 演示文稿中提取文本。
//實例化表示 PPTX 文件的 Presentation 類
Presentation pptxPresentation = new Presentation("demo.pptx");
//從 PPTX 中的所有幻燈片獲取 ITextFrame 對像數組
ITextFrame[] textFramesPPTX = Aspose.Slides.Util.SlideUtil.GetAllTextFrames(pptxPresentation, true);
//遍歷 TextFrames 數組
for (int i = 0; i < textFramesPPTX.Length; i++)
{
//循環遍歷當前 ITextFrame 中的段落
foreach (IParagraph para in textFramesPPTX[i].Paragraphs)
{
//遍歷當前 IParagraph 中的部分
foreach (IPortion port in para.Portions)
{
//在當前部分顯示文本
Console.WriteLine(port.Text);
//顯示文本的字體高度
Console.WriteLine(port.PortionFormat.FontHeight);
//顯示文本的字體名稱
if (port.PortionFormat.LatinFont != null)
Console.WriteLine(port.PortionFormat.LatinFont.FontName);
}
}
}
獲取免費的 API 許可證
如果您想在沒有評估限制的情況下試用 API,您可以獲得免費的臨時許可證。
結論
在本文中,您學習瞭如何從 PowerPoint 演示文稿中提取文本。特別是,您已經了解瞭如何使用 C# 從特定幻燈片或整個演示文稿中提取文本。您可以使用 文檔 探索更多關於 Aspose.Slides for .NET 的信息。如果您有任何疑問或困惑,請通過我們的 論壇 通知我們。