ReportUtils.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  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.Windows;
  12. using System.Windows.Controls;
  13. using FastReport;
  14. using FastReport.Data;
  15. using FastReport.Export.Pdf;
  16. using FastReport.Utils;
  17. using InABox.Clients;
  18. using InABox.Core;
  19. using InABox.Core.Reports;
  20. using InABox.Scripting;
  21. using InABox.Wpf.Reports.CustomObjects;
  22. using Syncfusion.Pdf;
  23. using Syncfusion.Pdf.Parsing;
  24. using XmlDocument = System.Xml.XmlDocument;
  25. namespace InABox.Wpf.Reports
  26. {
  27. public enum ReportExportType
  28. {
  29. PDF,
  30. HTML,
  31. RTF,
  32. Excel,
  33. Text,
  34. Image
  35. }
  36. public delegate void ReportExportDefinitionClicked();
  37. public class ReportExportDefinition
  38. {
  39. public ReportExportDefinition(string caption, Bitmap image, ReportExportType type, Action<DataModel, byte[]> action)
  40. {
  41. Caption = caption;
  42. Image = image;
  43. Type = type;
  44. Action = action;
  45. }
  46. public ReportExportDefinition(string caption, ContentControl control, ReportExportType type, Action<DataModel, byte[]> action)
  47. {
  48. Caption = caption;
  49. Type = type;
  50. Action = action;
  51. Control = control;
  52. }
  53. public event ReportExportDefinitionClicked OnReportDefinitionClicked;
  54. public string Caption { get; }
  55. public Bitmap Image { get; }
  56. public ContentControl Control { get; }
  57. public ReportExportType Type { get; }
  58. public Action<DataModel, byte[]> Action { get; }
  59. }
  60. [LibraryInitializer]
  61. public static class ReportUtils
  62. {
  63. public static List<ReportExportDefinition> ExportDefinitions { get; } = new();
  64. public static void RegisterClasses()
  65. {
  66. CoreUtils.RegisterClasses(typeof(ReportTemplate).Assembly, typeof(ReportUtils).Assembly);
  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. foreach (var column in dataSource.Columns)
  131. {
  132. if(column is FastReport.Data.Column col && !col.Enabled)
  133. {
  134. //columns.Add(col.Name.Replace('_','.'));
  135. columnNames.Remove(col.Name.Replace('_', '.'));
  136. }
  137. /*if (column is FastReport.Data.Column col && col.DataType != null && col.DataType.IsAssignableTo(typeof(IEnumerable<byte[]>)))
  138. {
  139. col.BindableControl = ColumnBindableControl.Custom;
  140. col.CustomBindableControl = "MultiImageObject";
  141. }*/
  142. }
  143. modelTable.Columns = Columns.None(modelTable.Type).Add(columnNames);
  144. }
  145. }
  146. ScriptDocument? script = null;
  147. bool ScriptOK = false;
  148. if (!string.IsNullOrWhiteSpace(template?.Script))
  149. {
  150. script = new ScriptDocument(template.Script);
  151. if (script.Compile())
  152. {
  153. script.SetValue("Model", data);
  154. ScriptOK = script.Execute("Report", "Init");
  155. }
  156. }
  157. if (repopulate)
  158. data.LoadModel(tables);
  159. if (ScriptOK && script is not null)
  160. {
  161. script.SetValue("RequireTables", tables);
  162. script.Execute("Report", "Populate");
  163. }
  164. var ds = data.AsDataSet();
  165. report.RegisterData(ds);
  166. foreach (var tableName in data.TableNames)
  167. {
  168. var columnNames = data.GetColumns(tableName)?.ColumnNames().ToHashSet();
  169. var dataSource = report.GetDataSource(tableName);
  170. if(dataSource != null)
  171. {
  172. foreach (var column in dataSource.Columns)
  173. {
  174. if (column is FastReport.Data.Column col)
  175. {
  176. if (col.DataType != null && col.DataType.IsAssignableTo(typeof(IEnumerable<byte[]>)))
  177. {
  178. col.BindableControl = ColumnBindableControl.Custom;
  179. col.CustomBindableControl = "MultiImageObject";
  180. }
  181. col.Enabled = columnNames is null || columnNames.Contains(col.Name.Replace('_', '.'));
  182. }
  183. }
  184. }
  185. }
  186. if (string.IsNullOrWhiteSpace(templaterdl))
  187. {
  188. foreach (var table in data.DefaultTables)
  189. {
  190. var dataSource = report.GetDataSource(table.TableName);
  191. dataSource.Enabled = true;
  192. }
  193. foreach (Relation relation in report.Dictionary.Relations)
  194. if (data.DefaultTables.Any(x => x.TableName.Equals(relation.ParentDataSource.Alias)) &&
  195. data.DefaultTables.Any(x => x.TableName.Equals(relation.ChildDataSource.Alias)))
  196. relation.Enabled = true;
  197. }
  198. return report;
  199. }
  200. public static void DesignReport(ReportTemplate template, DataModel data, bool populate = false, Action<ReportTemplate>? saveTemplate = null)
  201. {
  202. var isrdl = template != null && template.IsRDL;
  203. var templaterdl = template != null ? string.IsNullOrWhiteSpace(template.RDL) ? "" : template.RDL : "";
  204. if (isrdl)
  205. MessageBox.Show("RDL Reports are not supported!");
  206. else
  207. {
  208. PreviewWindow window = new(template, data)
  209. {
  210. AllowDesign = true,
  211. Title = string.Format("Report Designer - {0}", template.Name),
  212. Height = 800,
  213. Width = 1200,
  214. WindowState = WindowState.Maximized,
  215. IsPreview = false,
  216. ShouldPopulate = populate,
  217. SaveTemplate = saveTemplate
  218. };
  219. window.Show();
  220. }
  221. }
  222. public static byte[] CompressPDF(byte[] original)
  223. {
  224. //Load the existing PDF document
  225. PdfLoadedDocument loadedDocument = new PdfLoadedDocument(original);
  226. //Create a new compression option.
  227. PdfCompressionOptions options = new PdfCompressionOptions();
  228. //Enable the compress image.
  229. options.CompressImages = true;
  230. //Set the image quality.
  231. options.ImageQuality = 50;
  232. //Assign the compression option to the document.
  233. loadedDocument.CompressionOptions = options;
  234. //Creating the stream object.
  235. using (MemoryStream stream = new MemoryStream())
  236. {
  237. //Save the document into stream.
  238. loadedDocument.Save(stream);
  239. return stream.GetBuffer();
  240. }
  241. }
  242. public static byte[] ReportToPDF(ReportTemplate template, DataModel data, bool repopulate = true)
  243. {
  244. byte[] result = null;
  245. if (template.IsRDL)
  246. MessageBox.Show("RDL Reports are not supported!");
  247. else
  248. using (var report = SetupReport(template, data, repopulate))
  249. {
  250. report.Prepare();
  251. var ms = new MemoryStream();
  252. report.Export(new PDFExport() { JpegCompression = true, JpegQuality = 65, Compressed = true }, ms);
  253. result = ms.GetBuffer();
  254. }
  255. return result;
  256. }
  257. public static Filter<ReportTemplate> GetReportFilter(string sectionName, DataModel model)
  258. {
  259. return new Filter<ReportTemplate>(x => x.DataModel).IsEqualTo(model.Name)
  260. .And(x => x.Section).IsEqualTo(sectionName)
  261. .And(x => x.Visible).IsEqualTo(true);
  262. }
  263. public static IEnumerable<ReportTemplate> LoadReports(string sectionName, DataModel model, Columns<ReportTemplate>? columns = null)
  264. {
  265. return new Client<ReportTemplate>().Query(
  266. GetReportFilter(sectionName, model),
  267. columns,
  268. new SortOrder<ReportTemplate>(x => x.Name))
  269. .ToObjects<ReportTemplate>();
  270. }
  271. private static void PopulateMenu(ItemsControl menu, string sectionName, DataModel model, bool allowdesign, bool populate = false)
  272. {
  273. var reports = LoadReports(sectionName, model);
  274. foreach (var report in reports)
  275. {
  276. var print = new MenuItem
  277. {
  278. Header = report.Name,
  279. Tag = report
  280. };
  281. print.Click += (sender, args) =>
  282. {
  283. PreviewReport(report, model, false, allowdesign);
  284. };
  285. menu.Items.Add(print);
  286. }
  287. if (allowdesign)
  288. {
  289. if (menu.Items.Count > 0 && menu.Items[^1] is not Separator)
  290. {
  291. menu.Items.Add(new Separator());
  292. }
  293. var manage = new MenuItem
  294. {
  295. Header = "Manage Reports"
  296. };
  297. manage.Click += (sender, args) =>
  298. {
  299. var manager = new ReportManager()
  300. {
  301. DataModel = model,
  302. Section = sectionName,
  303. Populate = populate
  304. };
  305. manager.ShowDialog();
  306. };
  307. menu.Items.Add(manage);
  308. }
  309. }
  310. /// <summary>
  311. /// Populate the <paramref name="menu"/> with a list of reports attached to this data model, loaded through <see cref="LoadReports(string, DataModel, Columns{ReportTemplate}?)"/>.
  312. /// </summary>
  313. /// <remarks>
  314. /// This is used for the various places we have context menus for printing reports.
  315. /// </remarks>
  316. /// <param name="allowdesign">Allow designing reports; if <see langword="true"/>, then also adds a "Manage Reports" button.</param>
  317. /// <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>
  318. public static void PopulateMenu(MenuItem menu, string sectionName, DataModel model, bool allowdesign, bool populate = false) =>
  319. PopulateMenu(menu as ItemsControl, sectionName, model, allowdesign, populate);
  320. /// <summary>
  321. /// Populate the <paramref name="menu"/> with a list of reports attached to this data model, loaded through <see cref="LoadReports(string, DataModel, Columns{ReportTemplate}?)"/>.
  322. /// </summary>
  323. /// <remarks>
  324. /// This is used for the various places we have context menus for printing reports.
  325. /// </remarks>
  326. /// <param name="allowdesign">Allow designing reports; if <see langword="true"/>, then also adds a "Manage Reports" button.</param>
  327. /// <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>
  328. public static void PopulateMenu(ContextMenu menu, string sectionName, DataModel model, bool allowdesign, bool populate = false) =>
  329. PopulateMenu(menu as ItemsControl, sectionName, model, allowdesign, populate);
  330. public static void PrintMenu(FrameworkElement? element, string sectionName, DataModel model, bool allowdesign, bool populate = false)
  331. {
  332. var menu = new ContextMenu();
  333. PopulateMenu(menu, sectionName, model, allowdesign, populate);
  334. if (menu.Items.Count > 0)
  335. {
  336. menu.PlacementTarget = element;
  337. menu.IsOpen = true;
  338. }
  339. }
  340. public static void PrintMenu<TType>(FrameworkElement? element, string sectionName, DataModel<TType> model, bool allowdesign, bool populate = false)
  341. where TType : Entity, IRemotable, IPersistent, new()
  342. {
  343. PrintMenu(element, sectionName, model, allowdesign, populate);
  344. }
  345. }
  346. }