EntityDocumentStore.cs 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. using Comal.Stores;
  2. using InABox.Core;
  3. using System;
  4. using System.Linq;
  5. using System.IO;
  6. using Syncfusion.Pdf.Parsing;
  7. using System.Drawing;
  8. using System.Drawing.Imaging;
  9. namespace PRSStores
  10. {
  11. //In order to have BeforeSave active for a specific EntityDocument, it has to be concretized from this abstract class
  12. public abstract class EntityDocumentStore<TEntityDocument, TEntity, TEntityLink> : BaseStore<TEntityDocument>
  13. where TEntityDocument : EntityDocument<TEntityLink>, new()
  14. where TEntityLink : EntityLink<TEntity>, new()
  15. where TEntity : Entity, new()
  16. {
  17. protected override void BeforeSave(TEntityDocument entity)
  18. {
  19. SaveThumbnail(entity); //current size for saved thumbnails is 256*256
  20. base.BeforeSave(entity);
  21. }
  22. private void SaveThumbnail(TEntityDocument entity)
  23. {
  24. if (entity.DocumentLink.ID == Guid.Empty)
  25. return;
  26. if (entity.Thumbnail?.Any() == true)
  27. return;
  28. CoreTable table = Provider.Query<Document>(new Filter<Document>(x => x.ID).IsEqualTo(entity.DocumentLink.ID),
  29. new Columns<Document>(x => x.Data, x => x.FileName));
  30. if (table.Rows.Count == 0)
  31. return;
  32. Document doc = table.Rows.FirstOrDefault().ToObject<Document>();
  33. if (!doc.FileName.ToLower().EndsWith("pdf"))
  34. return;
  35. try
  36. {
  37. PdfLoadedDocument loadeddoc = new PdfLoadedDocument(doc.Data);
  38. Bitmap image = loadeddoc.ExportAsImage(0, new SizeF(256, 256), true);
  39. MemoryStream stream = new MemoryStream();
  40. image.Save(stream, ImageFormat.Jpeg);
  41. entity.Thumbnail = stream.ToArray();
  42. }
  43. catch (Exception ex)
  44. {
  45. Logger.Send(LogType.Information, UserID, ex.Message);
  46. }
  47. }
  48. }
  49. }