Advertisement
andruhovski

iText

Jul 13th, 2021
991
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 2.22 KB | None | 0 0
  1. using iText.StyledXmlParser.Resolver.Resource;
  2. using Microsoft.Extensions.Logging;
  3. using System;
  4. using System.IO;
  5. using System.Resources;
  6.  
  7. namespace Cytena.EVA.Report
  8. {
  9.     public class CustomResourceRetriever : IResourceRetriever
  10.     {
  11.         private readonly string _baseUri;
  12.         private readonly ILogger<PdfGenerator> _logger;
  13.         public CustomResourceRetriever(ILogger<PdfGenerator> logger, string baseUri)
  14.         {
  15.             _logger = logger;
  16.             _baseUri = baseUri;
  17.         }
  18.  
  19.         public byte[] GetByteArrayByUrl(Uri url)
  20.         {
  21.             using Stream stream = GetInputStreamByUrl(url);
  22.             if (stream == null)
  23.             {
  24.                 return Array.Empty<byte>();
  25.             }
  26.  
  27.             byte[] result = InputStreamToArray(stream);
  28.  
  29.             return result;
  30.         }
  31.  
  32.         // TODO CodReview with Andrey
  33.         public Stream GetInputStreamByUrl(Uri url)
  34.         {
  35.             string localPath = url.LocalPath;
  36.             if (File.Exists(localPath))
  37.             {
  38.                 var fi = new FileInfo(url.LocalPath);
  39.                 _logger.LogInformation($"Retrieved: {url.LocalPath} {fi.Length}");
  40.             }
  41.             else
  42.             {
  43.                 _logger.LogWarning($"Not found: {localPath}");
  44.                 var filename = Path.GetFileName(url.LocalPath);
  45.  
  46.                 if (filename.EndsWith("css"))
  47.                     localPath = Path.Combine(_baseUri, filename);
  48.                 else
  49.                     localPath = Path.Combine(_baseUri, "Images", filename);
  50.  
  51.                 _logger.LogWarning($"New filename: {localPath}");
  52.             }
  53.             return new FileStream(localPath, FileMode.Open, FileAccess.Read);
  54.         }
  55.  
  56.         private static byte[] InputStreamToArray(Stream stream)
  57.         {
  58.             byte[] b = new byte[8192];
  59.             MemoryStream output = new();
  60.             while (true)
  61.             {
  62.                 var read = stream.Read(b, 0, b.Length);
  63.                 if (read < 1)
  64.                 {
  65.                     break;
  66.                 }
  67.  
  68.                 output.Write(b, 0, read);
  69.             }
  70.  
  71.             output.Dispose();
  72.             return output.ToArray();
  73.         }
  74.     }
  75. }
  76.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement