using System;
using System.IO;
using System.Linq;
using System.Text;
using UglyToad.PdfPig;
using System.Threading;
using System.Threading.Tasks;
using xAiApi.Interfaces.Extractors;
namespace xAiApi.Providers
{
///
/// Extracts content from PDF files using PdfPig ...
///
public class XPdfFileContentExtractor : IXPdfFileContentExtractor
{
///
/// Supported MIME Types ...
///
private static readonly string[] SupportedMimeTypes =
[
"application/pdf"
];
///
/// Check if this extractor supports the specified MIME type ...
///
public bool CanExtract(string mimeType)
{
//
return SupportedMimeTypes.Contains(
mimeType?.ToLowerInvariant() ?? string.Empty
);
}
///
/// Extract text content from file stream ...
///
public async Task ExtractAsync(
Stream fileStream,
string mimeType,
CancellationToken cancellationToken = default
)
{
//
var result = await Task.Run(() =>
{
//
var sb = new StringBuilder();
using var document = PdfDocument.Open(fileStream);
foreach (var page in document.GetPages())
{
//
var text = page.Text;
//
sb.AppendLine(text);
sb.AppendLine();
}
//
return sb.ToString();
}, cancellationToken);
//
return result;
}
}
}