DigitalFormUtils.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Drawing;
  4. using System.Linq;
  5. using System.Text.RegularExpressions;
  6. using FastReport;
  7. using FastReport.Data;
  8. using FastReport.Table;
  9. using FastReport.Utils;
  10. using InABox.Core;
  11. using InABox.Scripting;
  12. using InABox.Wpf.Reports;
  13. using InABox.Wpf.Reports.CustomObjects;
  14. using UnderlineType = InABox.Core.UnderlineType;
  15. namespace InABox.DynamicGrid
  16. {
  17. public static class DigitalFormUtils
  18. {
  19. #region Layout Importer
  20. private class Cell
  21. {
  22. public string Content { get; set; }
  23. public int Row { get; set; }
  24. public int Column { get; set; }
  25. public int RowSpan { get; set; } = 1;
  26. public int ColumnSpan { get; set; } = 1;
  27. public ICell InnerCell { get; set; }
  28. public Cell(int row, int column, string content, ICell cell)
  29. {
  30. Row = row;
  31. Column = column;
  32. Content = content;
  33. InnerCell = cell;
  34. }
  35. }
  36. private static void DeleteColumn(List<Cell> cells, int column)
  37. {
  38. foreach(var cell in cells)
  39. {
  40. if(cell.Column <= column && cell.Column + cell.ColumnSpan - 1 >= column)
  41. {
  42. --cell.ColumnSpan;
  43. }
  44. else if(cell.Column > column)
  45. {
  46. --cell.Column;
  47. }
  48. }
  49. cells.RemoveAll(x => x.ColumnSpan < 0);
  50. }
  51. private static List<Cell> GetCells(ISheet sheet)
  52. {
  53. var grid = new Dictionary<int, Dictionary<int, Cell>>();
  54. for (int rowIdx = sheet.FirstRow; rowIdx <= sheet.LastRow; ++rowIdx)
  55. {
  56. var row = sheet.GetRow(rowIdx);
  57. if (row is not null && row.FirstColumn >= 0)
  58. {
  59. var rowCells = new Dictionary<int, Cell>();
  60. for (int colIdx = row.FirstColumn; colIdx <= row.LastColumn; ++colIdx)
  61. {
  62. var cell = row.GetCell(colIdx);
  63. if (cell is not null)
  64. {
  65. rowCells.Add(colIdx, new Cell(rowIdx, colIdx, cell.GetValue(), cell));
  66. }
  67. }
  68. grid.Add(rowIdx, rowCells);
  69. }
  70. }
  71. foreach (var region in sheet.GetMergedCells())
  72. {
  73. for (int r = region.FirstRow; r <= region.LastRow; ++r)
  74. {
  75. if (!grid.TryGetValue(r, out var row)) continue;
  76. for (int c = region.FirstColumn; c <= region.LastColumn; ++c)
  77. {
  78. if ((r - region.FirstRow) + (c - region.FirstColumn) != 0)
  79. {
  80. row.Remove(c);
  81. }
  82. }
  83. if (row.Count == 0)
  84. {
  85. grid.Remove(r);
  86. }
  87. }
  88. if (grid.TryGetValue(region.FirstRow, out var cRow) && cRow.TryGetValue(region.FirstColumn, out var cCell))
  89. {
  90. cCell.RowSpan = region.LastRow - region.FirstRow + 1;
  91. cCell.ColumnSpan = region.LastColumn - region.FirstColumn + 1;
  92. }
  93. }
  94. var cells = new List<Cell>();
  95. foreach (var row in grid.Values)
  96. {
  97. foreach (var cell in row.Values)
  98. {
  99. cells.Add(cell);
  100. }
  101. }
  102. return cells;
  103. }
  104. private static Regex VariableRegex = new(@"^\[(?<VAR>[^:\]]+)(?::(?<TYPE>[^:\]]*))?(?::(?<PROPERTIES>[^\]]*))?\]$");
  105. private static Regex HeaderRegex = new(@"^{(?<HEADER>[^:}]+)(?::(?<COLLAPSED>[^}]*))?}$");
  106. public static DFLayout LoadLayout(ISpreadsheet spreadsheet)
  107. {
  108. var sheet = spreadsheet.GetSheet(0);
  109. var cells = GetCells(sheet);
  110. int firstRow = int.MaxValue;
  111. int lastRow = 0;
  112. int firstCol = int.MaxValue;
  113. int lastCol = 0;
  114. foreach (var cell in cells)
  115. {
  116. firstCol = Math.Min(cell.Column, firstCol);
  117. lastCol = Math.Max(cell.Column + cell.ColumnSpan - 1, lastCol);
  118. firstRow = Math.Min(cell.Row, firstRow);
  119. lastRow = Math.Max(cell.Row + cell.RowSpan - 1, lastRow);
  120. }
  121. var layout = new DFLayout();
  122. var columnWidths = new Dictionary<int, float>();
  123. var colOffset = 0;
  124. for (int col = firstCol; col <= lastCol; ++col)
  125. {
  126. var width = sheet.GetColumnWidth(col);
  127. if(width == float.MinValue)
  128. {
  129. layout.ColumnWidths.Add("10*");
  130. }
  131. else if(width <= 0f)
  132. {
  133. DeleteColumn(cells, col);
  134. }
  135. else
  136. {
  137. layout.ColumnWidths.Add($"{width}*");
  138. }
  139. }
  140. for (int row = firstRow; row <= lastRow; ++row)
  141. layout.RowHeights.Add("Auto");
  142. foreach(var cell in cells)
  143. {
  144. var style = cell.InnerCell.GetStyle();
  145. if (string.IsNullOrWhiteSpace(cell.Content) && style.Foreground == Color.Empty) continue;
  146. DFLayoutControl? control;
  147. String content = cell.Content?.Trim() ?? "";
  148. var headermatch = HeaderRegex.Match(content);
  149. var variablematch = VariableRegex.Match(content);
  150. if (headermatch.Success)
  151. {
  152. var text = headermatch.Groups["HEADER"];
  153. var collapsed = headermatch.Groups["COLLAPSED"];
  154. var header = new DFLayoutHeader()
  155. {
  156. Header = text.Value,
  157. Collapsed = collapsed.Success ? String.Equals(collapsed.Value.ToUpper(),"COLLAPSED") : false,
  158. Style = CreateStyle(style)
  159. };
  160. control = header;
  161. }
  162. else if (variablematch.Success)
  163. {
  164. var variableName = variablematch.Groups["VAR"];
  165. var variableType = variablematch.Groups["TYPE"];
  166. var variableProps = variablematch.Groups["PROPERTIES"];
  167. Type? fieldType = null;
  168. if (variableType.Success)
  169. fieldType = DFUtils.GetFieldType(variableType.Value);
  170. fieldType ??= typeof(DFLayoutStringField);
  171. var field = (Activator.CreateInstance(fieldType) as DFLayoutField)!;
  172. field.Name = variableName.Value;
  173. if (variableProps.Success)
  174. {
  175. if (field is DFLayoutOptionField option)
  176. option.Properties.Options = variableProps.Value;
  177. if (field is DFLayoutStringField text)
  178. text.Properties.TextWrapping = style.WrapText;
  179. // need to populate other variable types here
  180. }
  181. control = field;
  182. }
  183. else
  184. {
  185. control = new DFLayoutLabel
  186. {
  187. Caption = cell.Content,
  188. Style = CreateStyle(style)
  189. };
  190. }
  191. if(control is not null)
  192. {
  193. control.Row = cell.Row - firstRow + 1;
  194. control.Column = cell.Column - firstCol + 1 - colOffset;
  195. control.RowSpan = cell.RowSpan;
  196. control.ColumnSpan = cell.ColumnSpan;
  197. layout.Elements.Add(control);
  198. }
  199. }
  200. return layout;
  201. }
  202. private static DFLayoutTextStyle CreateStyle(ICellStyle style)
  203. {
  204. if (style == null)
  205. return new DFLayoutTextStyle();
  206. var result = new DFLayoutTextStyle
  207. {
  208. FontSize = style.Font.FontSize,
  209. IsItalic = style.Font.Italic,
  210. IsBold = style.Font.Bold,
  211. Underline = style.Font.Underline switch
  212. {
  213. Scripting.UnderlineType.None => UnderlineType.None,
  214. Scripting.UnderlineType.Single or Scripting.UnderlineType.SingleAccounting => UnderlineType.Single,
  215. Scripting.UnderlineType.Double or Scripting.UnderlineType.DoubleAccounting => UnderlineType.Double,
  216. _ => UnderlineType.None
  217. },
  218. BackgroundColour = style.Background,
  219. ForegroundColour = style.Font.Colour,
  220. HorizontalTextAlignment = style.HorizontalAlignment switch
  221. {
  222. CellAlignment.Middle => DFLayoutAlignment.Middle,
  223. CellAlignment.End => DFLayoutAlignment.End,
  224. CellAlignment.Justify => DFLayoutAlignment.Stretch,
  225. _ => DFLayoutAlignment.Start
  226. },
  227. VerticalTextAlignment = style.VerticalAlignment switch
  228. {
  229. CellAlignment.Start => DFLayoutAlignment.Start,
  230. CellAlignment.End => DFLayoutAlignment.End,
  231. CellAlignment.Justify => DFLayoutAlignment.Stretch,
  232. _ => DFLayoutAlignment.Middle
  233. },
  234. TextWrapping = style.WrapText
  235. };
  236. return result;
  237. }
  238. #endregion
  239. #region Report Generator
  240. public static Report? GenerateReport(DigitalFormLayout layout, DataModel model)
  241. {
  242. var report = ReportUtils.SetupReport(null, model, true);
  243. var dfLayout = new DFLayout();
  244. dfLayout.LoadLayout(layout.Layout);
  245. var page = new ReportPage();
  246. page.Name = "Page1";
  247. page.PaperWidth = 210;
  248. page.PaperHeight = 297;
  249. page.Landscape = false;
  250. page.LeftMargin = 10;
  251. page.TopMargin = 10;
  252. page.RightMargin = 10;
  253. page.BottomMargin = 10;
  254. report.Pages.Add(page);
  255. var formData = report.GetDataSource("Form_Data");
  256. var band = new DataBand();
  257. band.Name = "Data1";
  258. band.Height = Units.Millimeters * (page.PaperHeight - (page.TopMargin + page.BottomMargin));
  259. band.Width = Units.Millimeters * (page.PaperWidth - (page.LeftMargin + page.RightMargin));
  260. band.PrintIfDatasourceEmpty = true;
  261. band.DataSource = formData;
  262. page.AddChild(band);
  263. var table = new TableObject()
  264. {
  265. ColumnCount = dfLayout.ColumnWidths.Count,
  266. RowCount = dfLayout.RowHeights.Count
  267. };
  268. band.AddChild(table);
  269. foreach(var element in dfLayout.Elements)
  270. {
  271. if (element.Row < 1 || element.Row + element.RowSpan - 1 > table.RowCount
  272. || element.Column < 1 || element.Column + element.ColumnSpan - 1 > table.ColumnCount) continue;
  273. var row = table.Rows[element.Row - 1];
  274. if(row.ChildObjects[element.Column - 1] is TableCell cell)
  275. {
  276. cell.Border.Lines = BorderLines.All;
  277. cell.ColSpan = element.ColumnSpan;
  278. cell.RowSpan = element.RowSpan;
  279. if (element is DFLayoutField field)
  280. {
  281. var manualHeight = 0.0f;
  282. var dataColumn = $"Form_Data.{field.Name}";
  283. if(field is DFLayoutEmbeddedImage || field is DFLayoutSignaturePad)
  284. {
  285. var picture = new PictureObject
  286. {
  287. DataColumn = dataColumn,
  288. Dock = System.Windows.Forms.DockStyle.Fill
  289. };
  290. cell.AddChild(picture);
  291. manualHeight = 40;
  292. }
  293. else if(field is DFLayoutMultiImage)
  294. {
  295. var image = new MultiImageObject
  296. {
  297. DataColumn = dataColumn,
  298. };
  299. cell.AddChild(image);
  300. manualHeight = 40;
  301. }
  302. else if(field is DFLayoutMultiSignaturePad)
  303. {
  304. var image = new MultiSignatureObject
  305. {
  306. DataColumn = dataColumn,
  307. };
  308. cell.AddChild(image);
  309. manualHeight = 40;
  310. }
  311. else
  312. {
  313. cell.Text = $"[{dataColumn}]";
  314. cell.Font = new System.Drawing.Font(cell.Font.FontFamily, 8F, FontStyle.Italic);
  315. cell.TextColor = Color.Navy;
  316. }
  317. if(manualHeight > 0 && dfLayout.RowHeights[element.Row - 1] == "Auto")
  318. {
  319. dfLayout.RowHeights[element.Row - 1] = manualHeight.ToString();
  320. }
  321. }
  322. else if (element is DFLayoutLabel label)
  323. {
  324. var background = label.Style.BackgroundColour;
  325. if (background == Color.Empty)
  326. {
  327. label.Style.BackgroundColour = Color.WhiteSmoke;
  328. }
  329. cell.Text = label.Description;
  330. ApplyStyle(cell, label.Style);
  331. }
  332. else if (element is DFLayoutHeader header)
  333. {
  334. cell.Text = header.Header;
  335. ApplyStyle(cell, header.Style);
  336. }
  337. }
  338. }
  339. ProcessColumnWidths(band.Width, dfLayout.ColumnWidths, table.Columns);
  340. ProcessRowHeights(band.Height, dfLayout.RowHeights, table.Rows);
  341. return report;
  342. }
  343. private static void ApplyStyle(TableCell cell, DFLayoutTextStyle style)
  344. {
  345. var background = style.BackgroundColour;
  346. if(background != Color.Empty) cell.FillColor = background;
  347. var foreground = style.ForegroundColour;
  348. if (foreground != Color.Empty) cell.TextColor = foreground;
  349. FontStyle fontstyle = System.Drawing.FontStyle.Regular;
  350. if (style.IsBold)
  351. fontstyle |= System.Drawing.FontStyle.Bold;
  352. if (style.IsItalic)
  353. fontstyle |= System.Drawing.FontStyle.Italic;
  354. if (style.Underline != UnderlineType.None)
  355. fontstyle |= FontStyle.Underline;
  356. float fontsize = (float)style.FontSize * 8F / 12F;
  357. fontsize = fontsize == 0F ? 8F : fontsize;
  358. cell.Font = new System.Drawing.Font(cell.Font.FontFamily, fontsize, fontstyle);
  359. cell.HorzAlign = style.HorizontalTextAlignment switch
  360. {
  361. DFLayoutAlignment.Start => HorzAlign.Left,
  362. DFLayoutAlignment.Middle => HorzAlign.Center,
  363. DFLayoutAlignment.End => HorzAlign.Right,
  364. DFLayoutAlignment.Stretch => HorzAlign.Justify,
  365. _ => HorzAlign.Left
  366. };
  367. cell.VertAlign = style.VerticalTextAlignment switch
  368. {
  369. DFLayoutAlignment.Start => VertAlign.Top,
  370. DFLayoutAlignment.Middle => VertAlign.Center,
  371. DFLayoutAlignment.End => VertAlign.Bottom,
  372. DFLayoutAlignment.Stretch => VertAlign.Center,
  373. _ => VertAlign.Center
  374. };
  375. cell.WordWrap = style.TextWrapping;
  376. }
  377. private static void ProcessRowHeights(float bandheight, List<string> values, TableRowCollection rows)
  378. {
  379. float fixedtotal = 0F;
  380. for (int iFixed = 0; iFixed < values.Count; iFixed++)
  381. {
  382. if (!values[iFixed].Contains("*"))
  383. {
  384. if (!float.TryParse(values[iFixed], out float value))
  385. value = 4F;
  386. rows[iFixed].Height = Units.Millimeters * value;
  387. fixedtotal += Units.Millimeters * value;
  388. }
  389. }
  390. Dictionary<int, float> starvalues = new Dictionary<int, float>();
  391. float startotal = 0F;
  392. for (int iStar = 0; iStar < values.Count; iStar++)
  393. {
  394. float fstartotal = 0F;
  395. if (values[iStar].Contains("*"))
  396. {
  397. if (!float.TryParse(values[iStar].Replace("*", ""), out float value))
  398. value += 1;
  399. starvalues[iStar] = value;
  400. startotal += value;
  401. }
  402. }
  403. foreach (var key in starvalues.Keys)
  404. rows[key].Height = (starvalues[key] / startotal) * (bandheight - fixedtotal);
  405. }
  406. private static void ProcessColumnWidths(float bandwidth, List<string> values, TableColumnCollection columns)
  407. {
  408. float fixedtotal = 0F;
  409. for (int iFixed = 0; iFixed < values.Count; iFixed++)
  410. {
  411. if (!values[iFixed].Contains("*"))
  412. {
  413. if (!float.TryParse(values[iFixed], out float value))
  414. value = 20F;
  415. columns[iFixed].Width = Units.Millimeters * value;
  416. fixedtotal += Units.Millimeters * value;
  417. }
  418. }
  419. Dictionary<int, float> starvalues = new Dictionary<int, float>();
  420. float startotal = 0F;
  421. for (int iStar = 0; iStar < values.Count; iStar++)
  422. {
  423. float fstartotal = 0F;
  424. if (values[iStar].Contains("*"))
  425. {
  426. if (!float.TryParse(values[iStar].Replace("*", ""), out float value))
  427. value += 1;
  428. starvalues[iStar] = value;
  429. startotal += value;
  430. }
  431. }
  432. foreach (var key in starvalues.Keys)
  433. columns[key].Width = (starvalues[key] / startotal) * (bandwidth - fixedtotal);
  434. }
  435. #endregion
  436. #region Data Model
  437. private static List<Type>? _entityForms;
  438. public static DataModel? GetDataModel(String appliesto, IEnumerable<DigitalFormVariable> variables)
  439. {
  440. _entityForms ??= CoreUtils.Entities
  441. .Where(x => x.IsSubclassOfRawGeneric(typeof(EntityForm<,>)))
  442. .ToList();
  443. var entityForm = _entityForms
  444. .Where(x => x.GetSuperclassDefinition(typeof(EntityForm<,>))?.GenericTypeArguments[0].Name == appliesto)
  445. .FirstOrDefault();
  446. if(entityForm is not null)
  447. {
  448. var model = (Activator.CreateInstance(typeof(DigitalFormReportDataModel<>).MakeGenericType(entityForm), Filter.Create(entityForm).None(), null) as DataModel)!;
  449. (model as IDigitalFormReportDataModel)!.Variables = variables.ToArray();
  450. return model;
  451. }
  452. return null;
  453. }
  454. #endregion
  455. }
  456. }