ReportUtils.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  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. foreach (string printer in PrinterSettings.InstalledPrinters)
  67. ReportPrinters.Register(printer);
  68. Application.Current.Dispatcher.BeginInvoke(() =>
  69. {
  70. RegisteredObjects.Add(typeof(MultiImageObject), "ReportPage", Wpf.Resources.multi_image, "Multi-Image");
  71. RegisteredObjects.Add(typeof(MultiSignatureObject), "ReportPage",Wpf.Resources.signature, "Multi-Signature");
  72. RegisteredObjects.Add(typeof(HTMLView), "ReportPage",Wpf.Resources.view, "HTML");
  73. });
  74. }
  75. public static void PreviewReport(ReportTemplate template, DataModel data, bool printandclose = false, bool allowdesigner = false)
  76. {
  77. if (template.IsRDL)
  78. {
  79. MessageBox.Show("RDL Reports are no longer supported!");
  80. }
  81. else
  82. {
  83. PreviewWindow window = new(template, data)
  84. {
  85. AllowDesign = allowdesigner,
  86. Title = string.Format("Report Preview - {0}", template.Name),
  87. Height = 800,
  88. Width = 1200,
  89. WindowState = WindowState.Maximized,
  90. };
  91. window.Show();
  92. }
  93. }
  94. public static Report SetupReport(ReportTemplate? template, DataModel data, bool repopulate)
  95. {
  96. var templaterdl = template != null ? string.IsNullOrWhiteSpace(template.RDL) ? "" : template.RDL : "";
  97. var tables = new List<string>();
  98. if (!string.IsNullOrWhiteSpace(templaterdl))
  99. {
  100. var xml = new XmlDocument();
  101. xml.LoadString(templaterdl);
  102. var datasources = xml.GetElementsByTagName("TableDataSource");
  103. for (var i = 0; i < datasources.Count; i++)
  104. {
  105. var datasource = datasources[i];
  106. tables.Add(datasource.Attributes.GetNamedItem("Name").Value);
  107. }
  108. }
  109. else
  110. {
  111. foreach(var table in data.DefaultTables)
  112. {
  113. tables.Add(table.TableName);
  114. }
  115. }
  116. var report = new Report();
  117. report.Log += (sender, args) =>
  118. Logger.Send(args.IsError ? LogType.Error : LogType.Information, "", args.Message);
  119. Config.ReportSettings.ShowProgress = false;
  120. report.LoadFromString(templaterdl);
  121. report.FileName = template?.Name ?? "";
  122. foreach(var tableName in data.TableNames)
  123. {
  124. var modelTable = data.GetDataModelTable(tableName);
  125. var dataSource = report.GetDataSource(tableName);
  126. if (dataSource != null && modelTable.Type is not null)
  127. {
  128. var columnNames = CoreUtils.GetColumnNames(modelTable.Type, x => true);
  129. foreach (var column in dataSource.Columns)
  130. {
  131. if(column is FastReport.Data.Column col && !col.Enabled)
  132. {
  133. //columns.Add(col.Name.Replace('_','.'));
  134. columnNames.Remove(col.Name.Replace('_', '.'));
  135. }
  136. /*if (column is FastReport.Data.Column col && col.DataType != null && col.DataType.IsAssignableTo(typeof(IEnumerable<byte[]>)))
  137. {
  138. col.BindableControl = ColumnBindableControl.Custom;
  139. col.CustomBindableControl = "MultiImageObject";
  140. }*/
  141. }
  142. modelTable.Columns = Columns.None(modelTable.Type).Add(columnNames);
  143. }
  144. }
  145. ScriptDocument? script = null;
  146. bool ScriptOK = false;
  147. if (!string.IsNullOrWhiteSpace(template?.Script))
  148. {
  149. script = new ScriptDocument(template.Script);
  150. if (script.Compile())
  151. {
  152. script.SetValue("Model", data);
  153. ScriptOK = script.Execute("Report", "Init");
  154. }
  155. }
  156. if (repopulate)
  157. data.LoadModel(tables);
  158. if (ScriptOK && script is not null)
  159. {
  160. script.SetValue("RequireTables", tables);
  161. script.Execute("Report", "Populate");
  162. }
  163. var ds = data.AsDataSet();
  164. report.RegisterData(ds);
  165. foreach (var tableName in data.TableNames)
  166. {
  167. var columnNames = data.GetColumns(tableName)?.ColumnNames().ToHashSet();
  168. var dataSource = report.GetDataSource(tableName);
  169. if(dataSource != null)
  170. {
  171. foreach (var column in dataSource.Columns)
  172. {
  173. if (column is FastReport.Data.Column col)
  174. {
  175. if (col.DataType != null && col.DataType.IsAssignableTo(typeof(IEnumerable<byte[]>)))
  176. {
  177. col.BindableControl = ColumnBindableControl.Custom;
  178. col.CustomBindableControl = "MultiImageObject";
  179. }
  180. col.Enabled = columnNames is null || columnNames.Contains(col.Name.Replace('_', '.'));
  181. }
  182. }
  183. }
  184. }
  185. if (string.IsNullOrWhiteSpace(templaterdl))
  186. {
  187. foreach (var table in data.DefaultTables)
  188. {
  189. var dataSource = report.GetDataSource(table.TableName);
  190. dataSource.Enabled = true;
  191. }
  192. foreach (Relation relation in report.Dictionary.Relations)
  193. if (data.DefaultTables.Any(x => x.TableName.Equals(relation.ParentDataSource.Alias)) &&
  194. data.DefaultTables.Any(x => x.TableName.Equals(relation.ChildDataSource.Alias)))
  195. relation.Enabled = true;
  196. }
  197. return report;
  198. }
  199. public static void DesignReport(ReportTemplate template, DataModel data, bool populate = false, Action<ReportTemplate>? saveTemplate = null)
  200. {
  201. var isrdl = template != null && template.IsRDL;
  202. var templaterdl = template != null ? string.IsNullOrWhiteSpace(template.RDL) ? "" : template.RDL : "";
  203. if (isrdl)
  204. MessageBox.Show("RDL Reports are not supported!");
  205. else
  206. {
  207. PreviewWindow window = new(template, data)
  208. {
  209. AllowDesign = true,
  210. Title = string.Format("Report Designer - {0}", template.Name),
  211. Height = 800,
  212. Width = 1200,
  213. WindowState = WindowState.Maximized,
  214. IsPreview = false,
  215. ShouldPopulate = populate,
  216. SaveTemplate = saveTemplate
  217. };
  218. window.Show();
  219. }
  220. }
  221. public static byte[] CompressPDF(byte[] original)
  222. {
  223. //Load the existing PDF document
  224. PdfLoadedDocument loadedDocument = new PdfLoadedDocument(original);
  225. //Create a new compression option.
  226. PdfCompressionOptions options = new PdfCompressionOptions();
  227. //Enable the compress image.
  228. options.CompressImages = true;
  229. //Set the image quality.
  230. options.ImageQuality = 50;
  231. //Assign the compression option to the document.
  232. loadedDocument.CompressionOptions = options;
  233. //Creating the stream object.
  234. using (MemoryStream stream = new MemoryStream())
  235. {
  236. //Save the document into stream.
  237. loadedDocument.Save(stream);
  238. return stream.GetBuffer();
  239. }
  240. }
  241. public static byte[] ReportToPDF(ReportTemplate template, DataModel data, bool repopulate = true)
  242. {
  243. byte[] result = null;
  244. if (template.IsRDL)
  245. MessageBox.Show("RDL Reports are not supported!");
  246. else
  247. using (var report = SetupReport(template, data, repopulate))
  248. {
  249. report.Prepare();
  250. var ms = new MemoryStream();
  251. report.Export(new PDFExport() { JpegCompression = true, JpegQuality = 65, Compressed = true }, ms);
  252. result = ms.GetBuffer();
  253. }
  254. return result;
  255. }
  256. public static Filter<ReportTemplate> GetReportFilter(string sectionName, DataModel model)
  257. {
  258. return new Filter<ReportTemplate>(x => x.DataModel).IsEqualTo(model.Name)
  259. .And(x => x.Section).IsEqualTo(sectionName)
  260. .And(x => x.Visible).IsEqualTo(true);
  261. }
  262. public static IEnumerable<ReportTemplate> LoadReports(string sectionName, DataModel model, Columns<ReportTemplate>? columns = null)
  263. {
  264. return new Client<ReportTemplate>().Query(
  265. GetReportFilter(sectionName, model),
  266. columns,
  267. new SortOrder<ReportTemplate>(x => x.Name))
  268. .ToObjects<ReportTemplate>();
  269. }
  270. private static void PopulateMenu(ItemsControl menu, string sectionName, DataModel model, bool allowdesign, bool populate = false)
  271. {
  272. var reports = LoadReports(sectionName, model);
  273. foreach (var report in reports)
  274. {
  275. var print = new MenuItem
  276. {
  277. Header = report.Name,
  278. Tag = report
  279. };
  280. print.Click += (sender, args) =>
  281. {
  282. PreviewReport(report, model, false, allowdesign);
  283. };
  284. menu.Items.Add(print);
  285. }
  286. if (allowdesign)
  287. {
  288. if (menu.Items.Count > 0 && menu.Items[^1] is not Separator)
  289. {
  290. menu.Items.Add(new Separator());
  291. }
  292. var manage = new MenuItem
  293. {
  294. Header = "Manage Reports"
  295. };
  296. manage.Click += (sender, args) =>
  297. {
  298. var manager = new ReportManager()
  299. {
  300. DataModel = model,
  301. Section = sectionName,
  302. Populate = populate
  303. };
  304. manager.ShowDialog();
  305. };
  306. menu.Items.Add(manage);
  307. }
  308. }
  309. /// <summary>
  310. /// Populate the <paramref name="menu"/> with a list of reports attached to this data model, loaded through <see cref="LoadReports(string, DataModel, Columns{ReportTemplate}?)"/>.
  311. /// </summary>
  312. /// <remarks>
  313. /// This is used for the various places we have context menus for printing reports.
  314. /// </remarks>
  315. /// <param name="allowdesign">Allow designing reports; if <see langword="true"/>, then also adds a "Manage Reports" button.</param>
  316. /// <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>
  317. public static void PopulateMenu(MenuItem menu, string sectionName, DataModel model, bool allowdesign, bool populate = false) =>
  318. PopulateMenu(menu as ItemsControl, sectionName, model, allowdesign, populate);
  319. /// <summary>
  320. /// Populate the <paramref name="menu"/> with a list of reports attached to this data model, loaded through <see cref="LoadReports(string, DataModel, Columns{ReportTemplate}?)"/>.
  321. /// </summary>
  322. /// <remarks>
  323. /// This is used for the various places we have context menus for printing reports.
  324. /// </remarks>
  325. /// <param name="allowdesign">Allow designing reports; if <see langword="true"/>, then also adds a "Manage Reports" button.</param>
  326. /// <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>
  327. public static void PopulateMenu(ContextMenu menu, string sectionName, DataModel model, bool allowdesign, bool populate = false) =>
  328. PopulateMenu(menu as ItemsControl, sectionName, model, allowdesign, populate);
  329. public static void PrintMenu(FrameworkElement? element, string sectionName, DataModel model, bool allowdesign, bool populate = false)
  330. {
  331. var menu = new ContextMenu();
  332. PopulateMenu(menu, sectionName, model, allowdesign, populate);
  333. if (menu.Items.Count > 0)
  334. {
  335. menu.PlacementTarget = element;
  336. menu.IsOpen = true;
  337. }
  338. }
  339. public static void PrintMenu<TType>(FrameworkElement? element, string sectionName, DataModel<TType> model, bool allowdesign, bool populate = false)
  340. where TType : Entity, IRemotable, IPersistent, new()
  341. {
  342. PrintMenu(element, sectionName, model, allowdesign, populate);
  343. }
  344. }
  345. }