using System; using System.IO; using System.Linq; using System.Text; using UglyToad.PdfPig; using System.Threading; using System.Threading.Tasks; using Microsoft.AspNetCore.Http; using xCommons.Extensions; namespace xAiModels.Extensions { public static class IFormFileExtensions { /// /// Read a IFormFile Content as byte array ... /// /// /// /// public static async Task ReadAsBytes( this IFormFile source, CancellationToken cancellationToken = default ) { // // Create and use a Memory Stream ... using var stream = new MemoryStream(); // // Copy File Content to Stream ... await source.CopyToAsync( target: stream, cancellationToken: cancellationToken ); // // Read Stream Content as byte array ... var result = stream.ToArray(); // return result; } /// /// Read a File Content by it's Path as byte array ... /// /// /// /// /// /// public static async Task ReadAsBytes( this string filePath, int bufferSize = 81920, CancellationToken cancellationToken = default ) { // if (string.IsNullOrWhiteSpace(filePath)) { throw new Exception("Invalid Args ..."); } // // Create and use a Memory Stream ... using var memStream = new MemoryStream(); // using var stream = new FileStream( path: filePath, mode: FileMode.Open, access: FileAccess.Read, share: FileShare.ReadWrite ); // // Copy File Content to Stream ... await stream.CopyToAsync( destination: memStream, bufferSize: bufferSize, cancellationToken: cancellationToken ); // // Read Stream Content as byte array ... var result = memStream.ToArray(); // return result; } /// /// Read Text Content of Document ... /// /// /// /// public static async Task ReadContent( this IFormFile source, CancellationToken cancellationToken = default ) { // // Check if File PDF or not ... var isPDF = source.ContentType .ToNormalString() .Contains("pdf" .ToNormalString()); // var result = string.Empty; // var isValidFileType = isPDF; if (!isValidFileType) { return result; } // if (isPDF) { // // Reading File Content as Byte array ... var fileBytes = await source.ReadAsBytes(cancellationToken); // // Create a PDF Document ... using var stream = new MemoryStream(fileBytes); using var document = PdfDocument.Open(stream); // // Extract PDF Text ... var textBuilder = new StringBuilder(); foreach (var page in document.GetPages()) { textBuilder.Append(page.Text); } // result = textBuilder.ToString(); } // return result; } } }