Files
xSaherElmAiApi/Providers/Extractors/XDocxFileContentExtractor.cs
T
2026-10-02 22:12:46 +03:30

79 lines
2.4 KiB
C#

using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using xAiApi.Interfaces.Extractors;
using DocumentFormat.OpenXml.Drawing;
using DocumentFormat.OpenXml.Packaging;
namespace xAiApi.Providers.Extractors
{
/// <summary>
/// Extracts text content from DOCX files using DocumentFormat.OpenXml ...
/// </summary>
public class XDocxFileContentExtractor : IXDocxFileContentExtractor
{
/// <summary>
/// Supported MIME Types ...
/// </summary>
private static readonly string[] SupportedMimeTypes =
[
"application/vnd.openxmlformats-officedocument.wordprocessingml.document"
];
/// <summary>
/// Check if this extractor supports the specified MIME type ...
/// </summary>
public bool CanExtract(string mimeType)
{
//
return SupportedMimeTypes.Contains(
mimeType?.ToLowerInvariant() ?? string.Empty
);
}
/// <summary>
/// Extract text content from file stream ...
/// </summary>
public async Task<string> ExtractAsync(
Stream fileStream,
string mimeType,
CancellationToken cancellationToken = default
)
{
//
using var memoryStream = new MemoryStream();
await fileStream.CopyToAsync(memoryStream, cancellationToken);
memoryStream.Position = 0;
//
var stringBuilder = new StringBuilder();
//
using (var wordDocument = WordprocessingDocument.Open(memoryStream, false))
{
//
var body = wordDocument.MainDocumentPart?.Document?.Body;
if (body != null)
{
//
var paragraphs = body.Elements<Paragraph>();
foreach (var paragraph in paragraphs)
{
//
var text = paragraph.InnerText?.Trim();
if (!string.IsNullOrEmpty(text))
{
stringBuilder.AppendLine(text);
}
}
}
}
//
return stringBuilder.ToString();
}
}
}