EntityDocumentStore.cs 2.6 KB

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