ReportUtils.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  1. //using Ghostscript.NET;
  2. //using Ghostscript.NET.Processor;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Data;
  6. using System.Drawing;
  7. using System.Drawing.Printing;
  8. using System.IO;
  9. using System.Linq;
  10. using System.Reflection;
  11. using System.Text.RegularExpressions;
  12. using System.Windows;
  13. using System.Windows.Controls;
  14. using FastReport;
  15. using FastReport.Data;
  16. using FastReport.Export.Pdf;
  17. using FastReport.Utils;
  18. using InABox.Clients;
  19. using InABox.Core;
  20. using InABox.Core.Reports;
  21. using InABox.Scripting;
  22. using InABox.Wpf.Reports.CustomObjects;
  23. using Syncfusion.Pdf;
  24. using Syncfusion.Pdf.Parsing;
  25. using XmlDocument = System.Xml.XmlDocument;
  26. namespace InABox.Wpf.Reports
  27. {
  28. public enum ReportExportType
  29. {
  30. PDF,
  31. HTML,
  32. RTF,
  33. Excel,
  34. Text,
  35. Image
  36. }
  37. public delegate void ReportExportDefinitionClicked();
  38. public class ReportExportDefinition
  39. {
  40. public ReportExportDefinition(string caption, Bitmap image, ReportExportType type, Action<DataModel, byte[]> action)
  41. {
  42. Caption = caption;
  43. Image = image;
  44. Type = type;
  45. Action = action;
  46. }
  47. public ReportExportDefinition(string caption, ContentControl control, ReportExportType type, Action<DataModel, byte[]> action)
  48. {
  49. Caption = caption;
  50. Type = type;
  51. Action = action;
  52. Control = control;
  53. }
  54. public event ReportExportDefinitionClicked OnReportDefinitionClicked;
  55. public string Caption { get; }
  56. public Bitmap Image { get; }
  57. public ContentControl Control { get; }
  58. public ReportExportType Type { get; }
  59. public Action<DataModel, byte[]> Action { get; }
  60. }
  61. [LibraryInitializer]
  62. public static class ReportUtils
  63. {
  64. public static List<ReportExportDefinition> ExportDefinitions { get; } = new();
  65. public static void RegisterClasses()
  66. {
  67. foreach (string printer in PrinterSettings.InstalledPrinters)
  68. ReportPrinters.Register(printer);
  69. Application.Current.Dispatcher.BeginInvoke(() =>
  70. {
  71. RegisteredObjects.Add(typeof(MultiImageObject), "ReportPage", Wpf.Resources.multi_image, "Multi-Image");
  72. RegisteredObjects.Add(typeof(MultiSignatureObject), "ReportPage",Wpf.Resources.signature, "Multi-Signature");
  73. RegisteredObjects.Add(typeof(HTMLView), "ReportPage",Wpf.Resources.view, "HTML");
  74. });
  75. }
  76. public static void PreviewReport(ReportTemplate template, DataModel data, bool printandclose = false, bool allowdesigner = false)
  77. {
  78. if (template.IsRDL)
  79. {
  80. MessageBox.Show("RDL Reports are no longer supported!");
  81. }
  82. else
  83. {
  84. PreviewWindow window = new(template, data)
  85. {
  86. AllowDesign = allowdesigner,
  87. Title = string.Format("Report Preview - {0}", template.Name),
  88. Height = 800,
  89. Width = 1200,
  90. WindowState = WindowState.Maximized,
  91. };
  92. window.Show();
  93. }
  94. }
  95. public static Report SetupReport(ReportTemplate? template, DataModel data, bool repopulate)
  96. {
  97. var templaterdl = template != null ? string.IsNullOrWhiteSpace(template.RDL) ? "" : template.RDL : "";
  98. var tables = new List<string>();
  99. if (!string.IsNullOrWhiteSpace(templaterdl))
  100. {
  101. var xml = new XmlDocument();
  102. xml.LoadString(templaterdl);
  103. var datasources = xml.GetElementsByTagName("TableDataSource");
  104. for (var i = 0; i < datasources.Count; i++)
  105. {
  106. var datasource = datasources[i];
  107. tables.Add(datasource.Attributes.GetNamedItem("Name").Value);
  108. }
  109. }
  110. else
  111. {
  112. foreach(var table in data.DefaultTables)
  113. {
  114. tables.Add(table.TableName);
  115. }
  116. }
  117. var report = new Report();
  118. report.Log += (sender, args) =>
  119. Logger.Send(args.IsError ? LogType.Error : LogType.Information, "", args.Message);
  120. Config.ReportSettings.ShowProgress = false;
  121. report.LoadFromString(templaterdl);
  122. report.FileName = template?.Name ?? "";
  123. foreach(var tableName in data.TableNames)
  124. {
  125. var modelTable = data.GetDataModelTable(tableName);
  126. var dataSource = report.GetDataSource(tableName);
  127. var childkeys = data.Relations.Where(x => x.ChildTable.Equals(tableName))?.Select(x=>x.ChildColumn).ToArray() ?? [];
  128. var parentkeys = data.Relations.Where(x => x.ParentTable.Equals(tableName))?.Select(x=>x.ParentColumn).ToArray() ?? [];
  129. if (dataSource != null && modelTable.Type is not null)
  130. {
  131. var allcolumns = CoreUtils.GetColumnNames(modelTable.Type, x => true);
  132. var columnNames = allcolumns.ToList();
  133. if (template.OptimiseData)
  134. {
  135. // DataColumn="(table).(field)" or [(table).(field)]
  136. var pattern = @"DataColumn=""(?<value>[^""]+)""|\[(?<value>[^\]]+)\]";
  137. var matches = Regex.Matches(templaterdl, pattern);
  138. var usedcolumns = matches
  139. .Cast<Match>()
  140. .Select(m => m.Groups["value"].Value.Split('.').TakeLast(2))
  141. .Where(x=>x.Count() == 2 && x.First().Equals(tableName))
  142. .Select(x=>string.Join('.',x))
  143. .ToList();
  144. columnNames = columnNames
  145. .Where(x=>usedcolumns.Contains($"{tableName}.{x.Replace(".","_")}"))
  146. .ToList();
  147. if (columnNames.Count > 0)
  148. {
  149. if (!columnNames.Contains("ID"))
  150. columnNames.Add("ID");
  151. foreach (var childkey in childkeys)
  152. {
  153. var childcol = allcolumns.FirstOrDefault(x => x.Replace('.', '_').Equals(childkey));
  154. if (childcol != null && !columnNames.Contains(childcol))
  155. columnNames.Add(childcol);
  156. }
  157. foreach (var parentkey in parentkeys)
  158. {
  159. var parentcol = allcolumns.FirstOrDefault(x => x.Replace('.', '_').Equals(parentkey));
  160. if (parentcol != null && !columnNames.Contains(parentcol))
  161. columnNames.Add(parentcol);
  162. }
  163. }
  164. }
  165. else
  166. {
  167. foreach (var column in dataSource.Columns)
  168. {
  169. if(column is FastReport.Data.Column col && !col.Enabled)
  170. {
  171. columnNames.Remove(col.Name.Replace('_', '.'));
  172. }
  173. /*if (column is FastReport.Data.Column col && col.DataType != null && col.DataType.IsAssignableTo(typeof(IEnumerable<byte[]>)))
  174. {
  175. col.BindableControl = ColumnBindableControl.Custom;
  176. col.CustomBindableControl = "MultiImageObject";
  177. }*/
  178. }
  179. }
  180. modelTable.Columns = Columns.None(modelTable.Type).Add(columnNames);
  181. modelTable.ShouldLoad = modelTable.Columns.Count > 0;
  182. }
  183. }
  184. ScriptDocument? script = null;
  185. bool ScriptOK = false;
  186. if (!string.IsNullOrWhiteSpace(template?.Script))
  187. {
  188. script = new ScriptDocument(template.Script);
  189. if (script.Compile())
  190. {
  191. script.SetValue("Model", data);
  192. ScriptOK = script.Execute("Report", "Init");
  193. }
  194. }
  195. if (repopulate)
  196. data.LoadModel(tables);
  197. if (ScriptOK && script is not null)
  198. {
  199. script.SetValue("RequireTables", tables);
  200. script.Execute("Report", "Populate");
  201. }
  202. var ds = data.AsDataSet();
  203. report.RegisterData(ds);
  204. foreach (var tableName in data.TableNames)
  205. {
  206. var columnNames = data.GetColumns(tableName)?.ColumnNames().ToHashSet();
  207. var dataSource = report.GetDataSource(tableName);
  208. if(dataSource != null)
  209. {
  210. foreach (var column in dataSource.Columns)
  211. {
  212. if (column is FastReport.Data.Column col)
  213. {
  214. if (col.DataType != null && col.DataType.IsAssignableTo(typeof(IEnumerable<byte[]>)))
  215. {
  216. col.BindableControl = ColumnBindableControl.Custom;
  217. col.CustomBindableControl = "MultiImageObject";
  218. }
  219. col.Enabled = columnNames is null || columnNames.Contains(col.Name.Replace('_', '.'));
  220. }
  221. }
  222. }
  223. }
  224. if (string.IsNullOrWhiteSpace(templaterdl))
  225. {
  226. foreach (var table in data.DefaultTables)
  227. {
  228. var dataSource = report.GetDataSource(table.TableName);
  229. dataSource.Enabled = true;
  230. }
  231. foreach (Relation relation in report.Dictionary.Relations)
  232. if (data.DefaultTables.Any(x => x.TableName.Equals(relation.ParentDataSource.Alias)) &&
  233. data.DefaultTables.Any(x => x.TableName.Equals(relation.ChildDataSource.Alias)))
  234. relation.Enabled = true;
  235. }
  236. return report;
  237. }
  238. public static void DesignReport(ReportTemplate template, DataModel data, bool populate = false, Action<ReportTemplate>? saveTemplate = null)
  239. {
  240. var isrdl = template != null && template.IsRDL;
  241. var templaterdl = template != null ? string.IsNullOrWhiteSpace(template.RDL) ? "" : template.RDL : "";
  242. if (isrdl)
  243. MessageBox.Show("RDL Reports are not supported!");
  244. else
  245. {
  246. PreviewWindow window = new(template, data)
  247. {
  248. AllowDesign = true,
  249. Title = string.Format("Report Designer - {0}", template.Name),
  250. Height = 800,
  251. Width = 1200,
  252. WindowState = WindowState.Maximized,
  253. IsPreview = false,
  254. ShouldPopulate = populate,
  255. SaveTemplate = saveTemplate
  256. };
  257. window.Show();
  258. }
  259. }
  260. public static byte[] CompressPDF(byte[] original)
  261. {
  262. //Load the existing PDF document
  263. PdfLoadedDocument loadedDocument = new PdfLoadedDocument(original);
  264. //Create a new compression option.
  265. PdfCompressionOptions options = new PdfCompressionOptions();
  266. //Enable the compress image.
  267. options.CompressImages = true;
  268. //Set the image quality.
  269. options.ImageQuality = 50;
  270. //Assign the compression option to the document.
  271. loadedDocument.CompressionOptions = options;
  272. //Creating the stream object.
  273. using (MemoryStream stream = new MemoryStream())
  274. {
  275. //Save the document into stream.
  276. loadedDocument.Save(stream);
  277. return stream.GetBuffer();
  278. }
  279. }
  280. public static byte[] ReportToPDF(ReportTemplate template, DataModel data, bool repopulate = true)
  281. {
  282. byte[] result = null;
  283. if (template.IsRDL)
  284. MessageBox.Show("RDL Reports are not supported!");
  285. else
  286. using (var report = SetupReport(template, data, repopulate))
  287. {
  288. report.Prepare();
  289. var ms = new MemoryStream();
  290. report.Export(new PDFExport() { JpegCompression = true, JpegQuality = 65, Compressed = true }, ms);
  291. result = ms.GetBuffer();
  292. }
  293. return result;
  294. }
  295. public static Filter<ReportTemplate> GetReportFilter(string sectionName, DataModel model)
  296. {
  297. return Filter<ReportTemplate>.Where(x => x.DataModel).IsEqualTo(model.Name)
  298. .And(x => x.Section).IsEqualTo(sectionName)
  299. .And(x => x.Visible).IsEqualTo(true);
  300. }
  301. public static IEnumerable<ReportTemplate> LoadReports(string sectionName, DataModel model, Columns<ReportTemplate>? columns = null)
  302. {
  303. return new Client<ReportTemplate>().Query(
  304. GetReportFilter(sectionName, model),
  305. columns,
  306. new SortOrder<ReportTemplate>(x => x.Name))
  307. .ToObjects<ReportTemplate>();
  308. }
  309. private static void PopulateMenu(ItemsControl menu, string sectionName, DataModel model, bool allowdesign, bool populate = false)
  310. {
  311. var reports = LoadReports(sectionName, model);
  312. foreach (var report in reports)
  313. {
  314. var print = new MenuItem
  315. {
  316. Header = report.Name,
  317. Tag = report
  318. };
  319. print.Click += (sender, args) =>
  320. {
  321. PreviewReport(report, model, false, allowdesign);
  322. };
  323. menu.Items.Add(print);
  324. }
  325. if (allowdesign)
  326. {
  327. if (menu.Items.Count > 0 && menu.Items[^1] is not Separator)
  328. {
  329. menu.Items.Add(new Separator());
  330. }
  331. var manage = new MenuItem
  332. {
  333. Header = "Manage Reports"
  334. };
  335. manage.Click += (sender, args) =>
  336. {
  337. var manager = new ReportManager()
  338. {
  339. DataModel = model,
  340. Section = sectionName,
  341. Populate = populate
  342. };
  343. manager.ShowDialog();
  344. };
  345. menu.Items.Add(manage);
  346. }
  347. }
  348. /// <summary>
  349. /// Populate the <paramref name="menu"/> with a list of reports attached to this data model, loaded through <see cref="LoadReports(string, DataModel, Columns{ReportTemplate}?)"/>.
  350. /// </summary>
  351. /// <remarks>
  352. /// This is used for the various places we have context menus for printing reports.
  353. /// </remarks>
  354. /// <param name="allowdesign">Allow designing reports; if <see langword="true"/>, then also adds a "Manage Reports" button.</param>
  355. /// <param name="populate">Determines whether the datamodel should be reloaded when printing a report.<br/>Set to <see langword="false"/> if all the data has already been loaded.</param>
  356. public static void PopulateMenu(MenuItem menu, string sectionName, DataModel model, bool allowdesign, bool populate = false) =>
  357. PopulateMenu(menu as ItemsControl, sectionName, model, allowdesign, populate);
  358. /// <summary>
  359. /// Populate the <paramref name="menu"/> with a list of reports attached to this data model, loaded through <see cref="LoadReports(string, DataModel, Columns{ReportTemplate}?)"/>.
  360. /// </summary>
  361. /// <remarks>
  362. /// This is used for the various places we have context menus for printing reports.
  363. /// </remarks>
  364. /// <param name="allowdesign">Allow designing reports; if <see langword="true"/>, then also adds a "Manage Reports" button.</param>
  365. /// <param name="populate">Determines whether the datamodel should be reloaded when printing a report.<br/>Set to <see langword="false"/> if all the data has already been loaded.</param>
  366. public static void PopulateMenu(ContextMenu menu, string sectionName, DataModel model, bool allowdesign, bool populate = false) =>
  367. PopulateMenu(menu as ItemsControl, sectionName, model, allowdesign, populate);
  368. public static void PrintMenu(FrameworkElement? element, string sectionName, DataModel model, bool allowdesign, bool populate = false)
  369. {
  370. var menu = new ContextMenu();
  371. PopulateMenu(menu, sectionName, model, allowdesign, populate);
  372. if (menu.Items.Count > 0)
  373. {
  374. menu.PlacementTarget = element;
  375. menu.IsOpen = true;
  376. }
  377. }
  378. public static void PrintMenu<TType>(FrameworkElement? element, string sectionName, DataModel<TType> model, bool allowdesign, bool populate = false)
  379. where TType : Entity, IRemotable, IPersistent, new()
  380. {
  381. PrintMenu(element, sectionName, model, allowdesign, populate);
  382. }
  383. }
  384. }