ReportUtils.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411
  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. if (dataSource != null && modelTable.Type is not null)
  128. {
  129. var columnNames = CoreUtils.GetColumnNames(modelTable.Type, x => true);
  130. if (template.OptimiseData)
  131. {
  132. // DataColumn="(table).(field)" or [(table).(field)]
  133. var pattern = @"DataColumn=""(?<value>[^""]+)""|\[(?<value>[^\]]+)\]";
  134. var matches = Regex.Matches(templaterdl, pattern);
  135. var usedcolumns = matches
  136. .Cast<Match>()
  137. .Select(m => m.Groups["value"].Value)
  138. .ToList();
  139. columnNames = columnNames
  140. .Where(x=>x.Equals("ID") || usedcolumns.Contains($"{modelTable.Type.Name}.{x.Replace(".","_")}"))
  141. .ToList();
  142. }
  143. else
  144. {
  145. foreach (var column in dataSource.Columns)
  146. {
  147. if(column is FastReport.Data.Column col && !col.Enabled)
  148. {
  149. columnNames.Remove(col.Name.Replace('_', '.'));
  150. }
  151. /*if (column is FastReport.Data.Column col && col.DataType != null && col.DataType.IsAssignableTo(typeof(IEnumerable<byte[]>)))
  152. {
  153. col.BindableControl = ColumnBindableControl.Custom;
  154. col.CustomBindableControl = "MultiImageObject";
  155. }*/
  156. }
  157. }
  158. modelTable.Columns = Columns.None(modelTable.Type).Add(columnNames);
  159. }
  160. }
  161. ScriptDocument? script = null;
  162. bool ScriptOK = false;
  163. if (!string.IsNullOrWhiteSpace(template?.Script))
  164. {
  165. script = new ScriptDocument(template.Script);
  166. if (script.Compile())
  167. {
  168. script.SetValue("Model", data);
  169. ScriptOK = script.Execute("Report", "Init");
  170. }
  171. }
  172. if (repopulate)
  173. data.LoadModel(tables);
  174. if (ScriptOK && script is not null)
  175. {
  176. script.SetValue("RequireTables", tables);
  177. script.Execute("Report", "Populate");
  178. }
  179. var ds = data.AsDataSet();
  180. report.RegisterData(ds);
  181. foreach (var tableName in data.TableNames)
  182. {
  183. var columnNames = data.GetColumns(tableName)?.ColumnNames().ToHashSet();
  184. var dataSource = report.GetDataSource(tableName);
  185. if(dataSource != null)
  186. {
  187. foreach (var column in dataSource.Columns)
  188. {
  189. if (column is FastReport.Data.Column col)
  190. {
  191. if (col.DataType != null && col.DataType.IsAssignableTo(typeof(IEnumerable<byte[]>)))
  192. {
  193. col.BindableControl = ColumnBindableControl.Custom;
  194. col.CustomBindableControl = "MultiImageObject";
  195. }
  196. col.Enabled = columnNames is null || columnNames.Contains(col.Name.Replace('_', '.'));
  197. }
  198. }
  199. }
  200. }
  201. if (string.IsNullOrWhiteSpace(templaterdl))
  202. {
  203. foreach (var table in data.DefaultTables)
  204. {
  205. var dataSource = report.GetDataSource(table.TableName);
  206. dataSource.Enabled = true;
  207. }
  208. foreach (Relation relation in report.Dictionary.Relations)
  209. if (data.DefaultTables.Any(x => x.TableName.Equals(relation.ParentDataSource.Alias)) &&
  210. data.DefaultTables.Any(x => x.TableName.Equals(relation.ChildDataSource.Alias)))
  211. relation.Enabled = true;
  212. }
  213. return report;
  214. }
  215. public static void DesignReport(ReportTemplate template, DataModel data, bool populate = false, Action<ReportTemplate>? saveTemplate = null)
  216. {
  217. var isrdl = template != null && template.IsRDL;
  218. var templaterdl = template != null ? string.IsNullOrWhiteSpace(template.RDL) ? "" : template.RDL : "";
  219. if (isrdl)
  220. MessageBox.Show("RDL Reports are not supported!");
  221. else
  222. {
  223. PreviewWindow window = new(template, data)
  224. {
  225. AllowDesign = true,
  226. Title = string.Format("Report Designer - {0}", template.Name),
  227. Height = 800,
  228. Width = 1200,
  229. WindowState = WindowState.Maximized,
  230. IsPreview = false,
  231. ShouldPopulate = populate,
  232. SaveTemplate = saveTemplate
  233. };
  234. window.Show();
  235. }
  236. }
  237. public static byte[] CompressPDF(byte[] original)
  238. {
  239. //Load the existing PDF document
  240. PdfLoadedDocument loadedDocument = new PdfLoadedDocument(original);
  241. //Create a new compression option.
  242. PdfCompressionOptions options = new PdfCompressionOptions();
  243. //Enable the compress image.
  244. options.CompressImages = true;
  245. //Set the image quality.
  246. options.ImageQuality = 50;
  247. //Assign the compression option to the document.
  248. loadedDocument.CompressionOptions = options;
  249. //Creating the stream object.
  250. using (MemoryStream stream = new MemoryStream())
  251. {
  252. //Save the document into stream.
  253. loadedDocument.Save(stream);
  254. return stream.GetBuffer();
  255. }
  256. }
  257. public static byte[] ReportToPDF(ReportTemplate template, DataModel data, bool repopulate = true)
  258. {
  259. byte[] result = null;
  260. if (template.IsRDL)
  261. MessageBox.Show("RDL Reports are not supported!");
  262. else
  263. using (var report = SetupReport(template, data, repopulate))
  264. {
  265. report.Prepare();
  266. var ms = new MemoryStream();
  267. report.Export(new PDFExport() { JpegCompression = true, JpegQuality = 65, Compressed = true }, ms);
  268. result = ms.GetBuffer();
  269. }
  270. return result;
  271. }
  272. public static Filter<ReportTemplate> GetReportFilter(string sectionName, DataModel model)
  273. {
  274. return new Filter<ReportTemplate>(x => x.DataModel).IsEqualTo(model.Name)
  275. .And(x => x.Section).IsEqualTo(sectionName)
  276. .And(x => x.Visible).IsEqualTo(true);
  277. }
  278. public static IEnumerable<ReportTemplate> LoadReports(string sectionName, DataModel model, Columns<ReportTemplate>? columns = null)
  279. {
  280. return new Client<ReportTemplate>().Query(
  281. GetReportFilter(sectionName, model),
  282. columns,
  283. new SortOrder<ReportTemplate>(x => x.Name))
  284. .ToObjects<ReportTemplate>();
  285. }
  286. private static void PopulateMenu(ItemsControl menu, string sectionName, DataModel model, bool allowdesign, bool populate = false)
  287. {
  288. var reports = LoadReports(sectionName, model);
  289. foreach (var report in reports)
  290. {
  291. var print = new MenuItem
  292. {
  293. Header = report.Name,
  294. Tag = report
  295. };
  296. print.Click += (sender, args) =>
  297. {
  298. PreviewReport(report, model, false, allowdesign);
  299. };
  300. menu.Items.Add(print);
  301. }
  302. if (allowdesign)
  303. {
  304. if (menu.Items.Count > 0 && menu.Items[^1] is not Separator)
  305. {
  306. menu.Items.Add(new Separator());
  307. }
  308. var manage = new MenuItem
  309. {
  310. Header = "Manage Reports"
  311. };
  312. manage.Click += (sender, args) =>
  313. {
  314. var manager = new ReportManager()
  315. {
  316. DataModel = model,
  317. Section = sectionName,
  318. Populate = populate
  319. };
  320. manager.ShowDialog();
  321. };
  322. menu.Items.Add(manage);
  323. }
  324. }
  325. /// <summary>
  326. /// Populate the <paramref name="menu"/> with a list of reports attached to this data model, loaded through <see cref="LoadReports(string, DataModel, Columns{ReportTemplate}?)"/>.
  327. /// </summary>
  328. /// <remarks>
  329. /// This is used for the various places we have context menus for printing reports.
  330. /// </remarks>
  331. /// <param name="allowdesign">Allow designing reports; if <see langword="true"/>, then also adds a "Manage Reports" button.</param>
  332. /// <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>
  333. public static void PopulateMenu(MenuItem menu, string sectionName, DataModel model, bool allowdesign, bool populate = false) =>
  334. PopulateMenu(menu as ItemsControl, sectionName, model, allowdesign, populate);
  335. /// <summary>
  336. /// Populate the <paramref name="menu"/> with a list of reports attached to this data model, loaded through <see cref="LoadReports(string, DataModel, Columns{ReportTemplate}?)"/>.
  337. /// </summary>
  338. /// <remarks>
  339. /// This is used for the various places we have context menus for printing reports.
  340. /// </remarks>
  341. /// <param name="allowdesign">Allow designing reports; if <see langword="true"/>, then also adds a "Manage Reports" button.</param>
  342. /// <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>
  343. public static void PopulateMenu(ContextMenu menu, string sectionName, DataModel model, bool allowdesign, bool populate = false) =>
  344. PopulateMenu(menu as ItemsControl, sectionName, model, allowdesign, populate);
  345. public static void PrintMenu(FrameworkElement? element, string sectionName, DataModel model, bool allowdesign, bool populate = false)
  346. {
  347. var menu = new ContextMenu();
  348. PopulateMenu(menu, sectionName, model, allowdesign, populate);
  349. if (menu.Items.Count > 0)
  350. {
  351. menu.PlacementTarget = element;
  352. menu.IsOpen = true;
  353. }
  354. }
  355. public static void PrintMenu<TType>(FrameworkElement? element, string sectionName, DataModel<TType> model, bool allowdesign, bool populate = false)
  356. where TType : Entity, IRemotable, IPersistent, new()
  357. {
  358. PrintMenu(element, sectionName, model, allowdesign, populate);
  359. }
  360. }
  361. }