Extract Media from Word Documents
如何在 .NET 中从 Word 文档中提取文本、图像和元数据
从Word文档中提取文本、图像和代数据是文档分析和处理至关重要的。 通过Aspose.Words for .NET**,开发人员可以编程地获取文档内容和属性,用于各种使用情况,如索引、存档或内容转换。
原則
- 安装 The 网 SDK .
- 添加 Aspose.Words NuGet 包:
dotnet add package Aspose.Words
- 编写文本(
document.docx
)与文本、图像和金属数据。
步骤指南从Word文件中提取内容
1、下载词文档
using System;
using Aspose.Words;
class Program
{
static void Main()
{
// Step 1: Load the Word document
string filePath = "document.docx";
Document doc = new Document(filePath);
// Steps 2, 3, and 4 will be added below
}
}
解释: 此代码将所指定的 Word 文档加载到内存中,以便进一步处理。
二、从文件中提取文本
using System;
using Aspose.Words;
class Program
{
static void Main()
{
string filePath = "document.docx";
Document doc = new Document(filePath);
// Step 2: Extract Text
string text = doc.GetText();
Console.WriteLine("Extracted Text: " + text);
// Steps 3 and 4 will be added below
}
}
解释: 此代码从加载的 Word 文档中提取所有文本内容并将其打印到控制台上。
3、从文档中提取代数据
using System;
using Aspose.Words;
class Program
{
static void Main()
{
string filePath = "document.docx";
Document doc = new Document(filePath);
string text = doc.GetText();
Console.WriteLine("Extracted Text: " + text);
// Step 3: Extract Metadata
Console.WriteLine("Title: " + doc.BuiltInDocumentProperties.Title);
Console.WriteLine("Author: " + doc.BuiltInDocumentProperties.Author);
Console.WriteLine("Created Date: " + doc.BuiltInDocumentProperties.CreatedTime);
// Step 4 will be added below
}
}
解释: 此代码从 Word 文档中提取和打印标题、作者和创建日期的代码数据。
4、从文件中提取图像
using System;
using Aspose.Words;
class Program
{
static void Main()
{
string filePath = "document.docx";
Document doc = new Document(filePath);
string text = doc.GetText();
Console.WriteLine("Extracted Text: " + text);
Console.WriteLine("Title: " + doc.BuiltInDocumentProperties.Title);
Console.WriteLine("Author: " + doc.BuiltInDocumentProperties.Author);
Console.WriteLine("Created Date: " + doc.BuiltInDocumentProperties.CreatedTime);
// Step 4: Extract Images
int imageCount = 0;
foreach (var shape in doc.GetChildNodes(NodeType.Shape, true))
{
if (shape is Shape { HasImage: true } imageShape)
{
string imageFilePath = $"Image_{++imageCount}.png";
imageShape.ImageData.Save(imageFilePath);
Console.WriteLine($"Saved Image: {imageFilePath}");
}
}
Console.WriteLine("Content extraction completed.");
}
}
解释: 此代码从 Word 文档中提取所有图像,并将其保存为项目目录中的 PNG 文件。
5、测试解决方案
- 保证
document.docx
在项目目录中。 - 运行程序并验证:- 在控制台输出中提取的文本。
- 印刷的细节。
- 提取的图像存储在项目文件夹中。
如何在主要平台上部署和运行
窗口
- 安装 .NET 运行时间并部署应用程序。
- 通过命令线运行应用程序进行测试。
林肯
- 安装 .NET 运行时间。
- 使用终端命令执行应用程序或在服务器上托管它。
马克思
- 使用 Kestrel 运行应用程序或在云服务中部署应用程序。
常见问题和解决方案
未提取的图像:- 确保文件包含内置的图像,而不是外部链接的图像。
缺失的数据:- 确保文档具有代数据属性,如标题或作者设置。
大文件处理:- 使用记忆效益的方法,例如处理文档的特定部分。
使用此指南,您可以通过使用 Aspose.Words for .NET 从 Word 文档中编程提取有价值的内容。