andruhovski icon

iText

andruhovski | PRO | 07/13/21 07:06:47 AM UTC | 0 ⭐ | 1375 👁️ | Never ⏰ | []
C# |

2.22 KB

|

None

|

0 👍

/

0 👎

using iText.StyledXmlParser.Resolver.Resource;
using Microsoft.Extensions.Logging;
using System;
using System.IO;
using System.Resources;
 
namespace Cytena.EVA.Report
{
    public class CustomResourceRetriever : IResourceRetriever
    {
        private readonly string _baseUri;
        private readonly ILogger<PdfGenerator> _logger;
        public CustomResourceRetriever(ILogger<PdfGenerator> logger, string baseUri)
        {
            _logger = logger;
            _baseUri = baseUri;
        }
 
        public byte[] GetByteArrayByUrl(Uri url)
        {
            using Stream stream = GetInputStreamByUrl(url);
            if (stream == null)
            {
                return Array.Empty<byte>();
            }
 
            byte[] result = InputStreamToArray(stream);
 
            return result;
        }
 
        // TODO CodReview with Andrey
        public Stream GetInputStreamByUrl(Uri url)
        {
            string localPath = url.LocalPath;
            if (File.Exists(localPath))
            {
                var fi = new FileInfo(url.LocalPath);
                _logger.LogInformation($"Retrieved: {url.LocalPath} {fi.Length}");
            }
            else
            {
                _logger.LogWarning($"Not found: {localPath}");
                var filename = Path.GetFileName(url.LocalPath);
 
                if (filename.EndsWith("css"))
                    localPath = Path.Combine(_baseUri, filename);
                else
                    localPath = Path.Combine(_baseUri, "Images", filename);
 
                _logger.LogWarning($"New filename: {localPath}");
            }
            return new FileStream(localPath, FileMode.Open, FileAccess.Read);
        }
 
        private static byte[] InputStreamToArray(Stream stream)
        {
            byte[] b = new byte[8192];
            MemoryStream output = new();
            while (true)
            {
                var read = stream.Read(b, 0, b.Length);
                if (read < 1)
                {
                    break;
                }
 
                output.Write(b, 0, read);
            }
 
            output.Dispose();
            return output.ToArray();
        }
    }
}
 

Comments