DigitalFormUtils.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534
  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. Dock = System.Windows.Forms.DockStyle.Fill
  299. };
  300. cell.AddChild(image);
  301. manualHeight = 40;
  302. }
  303. else if(field is DFLayoutMultiSignaturePad)
  304. {
  305. var image = new MultiSignatureObject
  306. {
  307. DataColumn = dataColumn,
  308. Dock = System.Windows.Forms.DockStyle.Fill
  309. };
  310. cell.AddChild(image);
  311. manualHeight = 40;
  312. }
  313. else
  314. {
  315. cell.Text = $"[{dataColumn}]";
  316. cell.Font = new System.Drawing.Font(cell.Font.FontFamily, 8F, FontStyle.Italic);
  317. cell.TextColor = Color.Navy;
  318. }
  319. if(manualHeight > 0 && dfLayout.RowHeights[element.Row - 1] == "Auto")
  320. {
  321. dfLayout.RowHeights[element.Row - 1] = manualHeight.ToString();
  322. }
  323. }
  324. else if (element is DFLayoutLabel label)
  325. {
  326. var background = label.Style.BackgroundColour;
  327. if (background == Color.Empty)
  328. {
  329. label.Style.BackgroundColour = Color.WhiteSmoke;
  330. }
  331. cell.Text = label.Description;
  332. ApplyStyle(cell, label.Style);
  333. }
  334. else if (element is DFLayoutHeader header)
  335. {
  336. cell.Text = header.Header;
  337. ApplyStyle(cell, header.Style);
  338. }
  339. }
  340. }
  341. ProcessColumnWidths(band.Width, dfLayout.ColumnWidths, table.Columns);
  342. ProcessRowHeights(band.Height, dfLayout.RowHeights, table.Rows);
  343. return report;
  344. }
  345. private static void ApplyStyle(TableCell cell, DFLayoutTextStyle style)
  346. {
  347. var background = style.BackgroundColour;
  348. if(background != Color.Empty) cell.FillColor = background;
  349. var foreground = style.ForegroundColour;
  350. if (foreground != Color.Empty) cell.TextColor = foreground;
  351. FontStyle fontstyle = System.Drawing.FontStyle.Regular;
  352. if (style.IsBold)
  353. fontstyle |= System.Drawing.FontStyle.Bold;
  354. if (style.IsItalic)
  355. fontstyle |= System.Drawing.FontStyle.Italic;
  356. if (style.Underline != UnderlineType.None)
  357. fontstyle |= FontStyle.Underline;
  358. float fontsize = (float)style.FontSize * 8F / 12F;
  359. fontsize = fontsize == 0F ? 8F : fontsize;
  360. cell.Font = new System.Drawing.Font(cell.Font.FontFamily, fontsize, fontstyle);
  361. cell.HorzAlign = style.HorizontalTextAlignment switch
  362. {
  363. DFLayoutAlignment.Start => HorzAlign.Left,
  364. DFLayoutAlignment.Middle => HorzAlign.Center,
  365. DFLayoutAlignment.End => HorzAlign.Right,
  366. DFLayoutAlignment.Stretch => HorzAlign.Justify,
  367. _ => HorzAlign.Left
  368. };
  369. cell.VertAlign = style.VerticalTextAlignment switch
  370. {
  371. DFLayoutAlignment.Start => VertAlign.Top,
  372. DFLayoutAlignment.Middle => VertAlign.Center,
  373. DFLayoutAlignment.End => VertAlign.Bottom,
  374. DFLayoutAlignment.Stretch => VertAlign.Center,
  375. _ => VertAlign.Center
  376. };
  377. cell.WordWrap = style.TextWrapping;
  378. }
  379. private static void ProcessRowHeights(float bandheight, List<string> values, TableRowCollection rows)
  380. {
  381. float fixedtotal = 0F;
  382. for (int iFixed = 0; iFixed < values.Count; iFixed++)
  383. {
  384. if (!values[iFixed].Contains("*"))
  385. {
  386. if (!float.TryParse(values[iFixed], out float value))
  387. value = 4F;
  388. rows[iFixed].Height = Units.Millimeters * value;
  389. fixedtotal += Units.Millimeters * value;
  390. }
  391. }
  392. Dictionary<int, float> starvalues = new Dictionary<int, float>();
  393. float startotal = 0F;
  394. for (int iStar = 0; iStar < values.Count; iStar++)
  395. {
  396. float fstartotal = 0F;
  397. if (values[iStar].Contains("*"))
  398. {
  399. if (!float.TryParse(values[iStar].Replace("*", ""), out float value))
  400. value += 1;
  401. starvalues[iStar] = value;
  402. startotal += value;
  403. }
  404. }
  405. foreach (var key in starvalues.Keys)
  406. rows[key].Height = (starvalues[key] / startotal) * (bandheight - fixedtotal);
  407. }
  408. private static void ProcessColumnWidths(float bandwidth, List<string> values, TableColumnCollection columns)
  409. {
  410. float fixedtotal = 0F;
  411. for (int iFixed = 0; iFixed < values.Count; iFixed++)
  412. {
  413. if (!values[iFixed].Contains("*"))
  414. {
  415. if (!float.TryParse(values[iFixed], out float value))
  416. value = 20F;
  417. columns[iFixed].Width = Units.Millimeters * value;
  418. fixedtotal += Units.Millimeters * value;
  419. }
  420. }
  421. Dictionary<int, float> starvalues = new Dictionary<int, float>();
  422. float startotal = 0F;
  423. for (int iStar = 0; iStar < values.Count; iStar++)
  424. {
  425. float fstartotal = 0F;
  426. if (values[iStar].Contains("*"))
  427. {
  428. if (!float.TryParse(values[iStar].Replace("*", ""), out float value))
  429. value += 1;
  430. starvalues[iStar] = value;
  431. startotal += value;
  432. }
  433. }
  434. foreach (var key in starvalues.Keys)
  435. columns[key].Width = (starvalues[key] / startotal) * (bandwidth - fixedtotal);
  436. }
  437. #endregion
  438. #region Data Model
  439. private static List<Type>? _entityForms;
  440. public static DataModel? GetDataModel(String appliesto, IEnumerable<DigitalFormVariable> variables)
  441. {
  442. _entityForms ??= CoreUtils.Entities
  443. .Where(x => x.IsSubclassOfRawGeneric(typeof(EntityForm<,,>)))
  444. .ToList();
  445. var entityForm = _entityForms
  446. .FirstOrDefault(x => x.GetSuperclassDefinition(typeof(EntityForm<,,>))
  447. ?.GenericTypeArguments[0].Name == appliesto);
  448. if(entityForm is not null)
  449. {
  450. var model = (Activator.CreateInstance(typeof(DigitalFormReportDataModel<>).MakeGenericType(entityForm), Filter.Create(entityForm).None(), null) as DataModel)!;
  451. (model as IDigitalFormReportDataModel)!.Variables = variables.ToArray();
  452. return model;
  453. }
  454. return null;
  455. }
  456. #endregion
  457. }
  458. }