-
Notifications
You must be signed in to change notification settings - Fork 27
/
Report.cs
500 lines (432 loc) · 20.7 KB
/
Report.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Printing;
using System.Reflection;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Xps;
using System.Windows.Xps.Packaging;
using Microsoft.Win32;
using PdfSharp.Xps;
#pragma warning disable 1591
namespace SimpleWPFReporting
{
public static class Report
{
const int DIUPerInch = 96;
private static readonly Thickness defaultMargin = new Thickness(25);
public static void ExportVisualAsXps(Visual visual)
{
SaveFileDialog saveFileDialog = new SaveFileDialog
{
DefaultExt = ".xps",
Filter = "XPS Documents (.xps)|*.xps"
};
bool? result = saveFileDialog.ShowDialog();
if (result != true) return;
XpsDocument xpsDocument = new XpsDocument(saveFileDialog.FileName, FileAccess.Write);
XpsDocumentWriter xpsDocumentWriter = XpsDocument.CreateXpsDocumentWriter(xpsDocument);
xpsDocumentWriter.Write(visual);
xpsDocument.Close();
}
public static void ExportVisualAsPdf(Visual visual)
{
SaveFileDialog saveFileDialog = new SaveFileDialog
{
DefaultExt = ".pdf",
Filter = "PDF Documents (.pdf)|*.pdf"
};
bool? result = saveFileDialog.ShowDialog();
if (result != true) return;
using (MemoryStream memoryStream = new MemoryStream())
{
System.IO.Packaging.Package package = System.IO.Packaging.Package.Open(memoryStream, FileMode.Create);
XpsDocument xpsDocument = new XpsDocument(package);
XpsDocumentWriter xpsDocumentWriter = XpsDocument.CreateXpsDocumentWriter(xpsDocument);
xpsDocumentWriter.Write(visual);
xpsDocument.Close();
package.Close();
var pdfXpsDoc = PdfSharp.Xps.XpsModel.XpsDocument.Open(memoryStream);
XpsConverter.Convert(pdfXpsDoc, saveFileDialog.FileName, 0);
}
}
private static readonly Lazy<int> dpiX = new Lazy<int>(() =>
{
PropertyInfo dpiXProperty = typeof(SystemParameters).GetProperty("DpiX", BindingFlags.NonPublic | BindingFlags.Static);
return (int)dpiXProperty.GetValue(null, null);
});
private static readonly Lazy<int> dpiY = new Lazy<int>(() =>
{
var dpiYProperty = typeof(SystemParameters).GetProperty("Dpi", BindingFlags.NonPublic | BindingFlags.Static);
return (int)dpiYProperty.GetValue(null, null);
});
private static void SaveFrameworkElementAsImage(FrameworkElement element, string filePath, BitmapEncoder bitmapEncoder)
{
RenderTargetBitmap bitmap = new RenderTargetBitmap(
pixelWidth: Convert.ToInt32((element.ActualWidth / DIUPerInch) * dpiX.Value),
pixelHeight: Convert.ToInt32((element.ActualHeight / DIUPerInch) * dpiY.Value),
dpiX: dpiX.Value,
dpiY: dpiY.Value,
pixelFormat: PixelFormats.Pbgra32);
bitmap.Render(element);
bitmapEncoder.Frames.Add(BitmapFrame.Create(bitmap));
using (Stream fs = File.Create(filePath))
{
bitmapEncoder.Save(fs);
}
}
public static void ExportFrameworkElementAsJpg(FrameworkElement element)
{
SaveFileDialog saveFileDialog = new SaveFileDialog
{
DefaultExt = ".jpg",
Filter = "JPG Images (.jpg)|*.jpg"
};
bool? result = saveFileDialog.ShowDialog();
if (result != true) return;
SaveFrameworkElementAsImage(element, saveFileDialog.FileName, new JpegBitmapEncoder {QualityLevel = 100});
}
public static void ExportFrameworkElementAsBmp(FrameworkElement element)
{
SaveFileDialog saveFileDialog = new SaveFileDialog
{
DefaultExt = ".bmp",
Filter = "BMP Images (.bmp)|*.bmp"
};
bool? result = saveFileDialog.ShowDialog();
if (result != true) return;
SaveFrameworkElementAsImage(element, saveFileDialog.FileName, new BmpBitmapEncoder());
}
public static void ExportFrameworkElementAsPng(FrameworkElement element)
{
SaveFileDialog saveFileDialog = new SaveFileDialog
{
DefaultExt = ".png",
Filter = "PNG Images (.png)|*.png"
};
bool? result = saveFileDialog.ShowDialog();
if (result != true) return;
SaveFrameworkElementAsImage(element, saveFileDialog.FileName, new PngBitmapEncoder());
}
/// <summary>
/// Divides elements of reportContainer into pages and prints them
/// </summary>
/// <param name="reportContainer">StackPanel containing report elements</param>
/// <param name="dataContext">Data Context used in the report</param>
/// <param name="margin">Margin of a report page</param>
/// <param name="orientation">Landscape or Portrait orientation</param>
/// <param name="resourceDictionary">Resources used in report</param>
/// <param name="backgroundBrush">Brush that will be used as background for report page</param>
/// <param name="reportHeaderDataTemplate">
/// Optional header for each page
/// Note: You can use DynamicResource PageNumber in this template to display page number
/// </param>
/// <param name="headerOnlyOnTheFirstPage">Use header only on the first page (default is false)</param>
/// <param name="reportFooterDataTemplate">
/// Optional footer for each page
/// Note: You can use DynamicResource PageNumber in this template to display page number
/// </param>
/// <param name="footerStartsFromTheSecondPage">Do not use footer on the first page (default is false)</param>
public static void PrintReport(
StackPanel reportContainer,
object dataContext,
Thickness margin,
ReportOrientation orientation,
ResourceDictionary resourceDictionary = null,
Brush backgroundBrush = null,
DataTemplate reportHeaderDataTemplate = null,
bool headerOnlyOnTheFirstPage = false,
DataTemplate reportFooterDataTemplate = null,
bool footerStartsFromTheSecondPage = false)
{
PrintDialog printDialog = new PrintDialog();
bool? result = printDialog.ShowDialog();
if (result != true) return;
Size reportSize = GetReportSize(reportContainer, margin, orientation, printDialog);
List<FrameworkElement> ReportElements = new List<FrameworkElement>(reportContainer.Children.Cast<FrameworkElement>());
reportContainer.Children.Clear(); //to avoid exception "Specified element is already the logical child of another element."
List<ReportPage> ReportPages =
GetReportPages(
resourceDictionary,
backgroundBrush,
ReportElements,
dataContext,
margin,
reportSize,
reportHeaderDataTemplate,
headerOnlyOnTheFirstPage,
reportFooterDataTemplate,
footerStartsFromTheSecondPage);
try
{
ReportPages.ForEach(reportPage => reportPage.Scale(reportSize, printDialog));
ReportPages.ForEach((reportPage, index) => printDialog.PrintVisual(reportPage.LayoutRoot, $"Карточка Точки {index + 1}"));
}
finally
{
ReportPages.ForEach(reportPage => reportPage.ClearChildren());
ReportElements.ForEach(elm => reportContainer.Children.Add(elm));
reportContainer.UpdateLayout();
}
}
/// <summary>
/// Divides elements of reportContainer into pages and prints them
/// NOTE: this overload uses default margin of 25
/// </summary>
/// <param name="reportContainer">StackPanel containing report elements</param>
/// <param name="dataContext">Data Context used in the report</param>
/// <param name="orientation">Landscape or Portrait orientation</param>
/// <param name="resourceDictionary">Resources used in report</param>
/// <param name="backgroundBrush">Brush that will be used as background for report page</param>
/// <param name="reportHeaderDataTemplate">
/// Optional header for each page
/// Note: You can use DynamicResource PageNumber in this template to display page number
/// </param>
/// <param name="headerOnlyOnTheFirstPage">Use header only on the first page (default is false)</param>
/// <param name="reportFooterDataTemplate">
/// Optional footer for each page
/// Note: You can use DynamicResource PageNumber in this template to display page number
/// </param>
/// <param name="footerStartsFromTheSecondPage">Do not use footer on the first page (default is false)</param>
public static void PrintReport(
StackPanel reportContainer,
object dataContext,
ReportOrientation orientation,
ResourceDictionary resourceDictionary = null,
Brush backgroundBrush = null,
DataTemplate reportHeaderDataTemplate = null,
bool headerOnlyOnTheFirstPage = false,
DataTemplate reportFooterDataTemplate = null,
bool footerStartsFromTheSecondPage = false)
{
PrintReport(
reportContainer,
dataContext,
defaultMargin,
orientation,
resourceDictionary,
backgroundBrush,
reportHeaderDataTemplate,
headerOnlyOnTheFirstPage,
reportFooterDataTemplate,
footerStartsFromTheSecondPage);
}
/// <summary>
/// Divides elements of reportContainer into pages and exports them as PDF
/// </summary>
/// <param name="reportContainer">StackPanel containing report elements</param>
/// <param name="dataContext">Data Context used in the report</param>
/// <param name="margin">Margin of a report page</param>
/// <param name="orientation">Landscape or Portrait orientation</param>
/// <param name="resourceDictionary">Resources used in report</param>
/// <param name="backgroundBrush">Brush that will be used as background for report page</param>
/// <param name="reportHeaderDataTemplate">
/// Optional header for each page
/// Note: You can use DynamicResource PageNumber in this template to display page number
/// </param>
/// <param name="headerOnlyOnTheFirstPage">Use header only on the first page (default is false)</param>
/// <param name="reportFooterDataTemplate">
/// Optional footer for each page
/// Note: You can use DynamicResource PageNumber in this template to display page number
/// </param>
/// <param name="footerStartsFromTheSecondPage">Do not use footer on the first page (default is false)</param>
public static void ExportReportAsPdf(
StackPanel reportContainer,
object dataContext,
Thickness margin,
ReportOrientation orientation,
ResourceDictionary resourceDictionary = null,
Brush backgroundBrush = null,
DataTemplate reportHeaderDataTemplate = null,
bool headerOnlyOnTheFirstPage = false,
DataTemplate reportFooterDataTemplate = null,
bool footerStartsFromTheSecondPage = false)
{
SaveFileDialog saveFileDialog = new SaveFileDialog
{
DefaultExt = ".pdf",
Filter = "PDF Documents (.pdf)|*.pdf"
};
bool? result = saveFileDialog.ShowDialog();
if (result != true) return;
Size reportSize = GetReportSize(reportContainer, margin, orientation);
List<FrameworkElement> ReportElements = new List<FrameworkElement>(reportContainer.Children.Cast<FrameworkElement>());
reportContainer.Children.Clear(); //to avoid exception "Specified element is already the logical child of another element."
List<ReportPage> ReportPages =
GetReportPages(
resourceDictionary,
backgroundBrush,
ReportElements,
dataContext,
margin,
reportSize,
reportHeaderDataTemplate,
headerOnlyOnTheFirstPage,
reportFooterDataTemplate,
footerStartsFromTheSecondPage);
FixedDocument fixedDocument = new FixedDocument();
try
{
using (MemoryStream memoryStream = new MemoryStream())
{
System.IO.Packaging.Package package = System.IO.Packaging.Package.Open(memoryStream, FileMode.Create);
XpsDocument xpsDocument = new XpsDocument(package);
XpsDocumentWriter xpsDocumentWriter = XpsDocument.CreateXpsDocumentWriter(xpsDocument);
foreach (Grid reportPage in ReportPages.Select(reportPage => reportPage.LayoutRoot))
{
reportPage.Width = reportPage.ActualWidth;
reportPage.Height = reportPage.ActualHeight;
FixedPage newFixedPage = new FixedPage();
newFixedPage.Children.Add(reportPage);
newFixedPage.Measure(reportSize);
newFixedPage.Arrange(new Rect(reportSize));
newFixedPage.Width = newFixedPage.ActualWidth;
newFixedPage.Height = newFixedPage.ActualHeight;
newFixedPage.Background = backgroundBrush;
newFixedPage.UpdateLayout();
PageContent pageContent = new PageContent();
((IAddChild)pageContent).AddChild(newFixedPage);
fixedDocument.Pages.Add(pageContent);
}
xpsDocumentWriter.Write(fixedDocument);
xpsDocument.Close();
package.Close();
var pdfXpsDoc = PdfSharp.Xps.XpsModel.XpsDocument.Open(memoryStream);
XpsConverter.Convert(pdfXpsDoc, saveFileDialog.FileName, 0);
}
}
finally
{
ReportPages.ForEach(reportPage => reportPage.ClearChildren());
ReportElements.ForEach(elm => reportContainer.Children.Add(elm));
reportContainer.UpdateLayout();
}
}
/// <summary>
/// Divides elements of reportContainer into pages and exports them as PDF
/// NOTE: this overload uses default margin of 25
/// </summary>
/// <param name="reportContainer">StackPanel containing report elements</param>
/// <param name="dataContext">Data Context used in the report</param>
/// <param name="orientation">Landscape or Portrait orientation</param>
/// <param name="resourceDictionary">Resources used in report</param>
/// <param name="backgroundBrush">Brush that will be used as background for report page</param>
/// <param name="reportHeaderDataTemplate">
/// Optional header for each page
/// Note: You can use DynamicResource PageNumber in this template to display page number
/// </param>
/// <param name="headerOnlyOnTheFirstPage">Use header only on the first page (default is false)</param>
/// <param name="reportFooterDataTemplate">
/// Optional footer for each page
/// Note: You can use DynamicResource PageNumber in this template to display page number
/// </param>
/// <param name="footerStartsFromTheSecondPage">Do not use footer on the first page (default is false)</param>
public static void ExportReportAsPdf(
StackPanel reportContainer,
object dataContext,
ReportOrientation orientation,
ResourceDictionary resourceDictionary = null,
Brush backgroundBrush = null,
DataTemplate reportHeaderDataTemplate = null,
bool headerOnlyOnTheFirstPage = false,
DataTemplate reportFooterDataTemplate = null,
bool footerStartsFromTheSecondPage = false)
{
ExportReportAsPdf(
reportContainer,
dataContext,
defaultMargin,
orientation,
resourceDictionary,
backgroundBrush,
reportHeaderDataTemplate,
headerOnlyOnTheFirstPage,
reportFooterDataTemplate,
footerStartsFromTheSecondPage);
}
private static List<ReportPage> GetReportPages(
ResourceDictionary resourceDictionary,
Brush backgroundBrush,
List<FrameworkElement> ReportElements,
object dataContext,
Thickness margin,
Size reportSize,
DataTemplate reportHeaderDataTemplate,
bool headerOnlyOnTheFirstPage,
DataTemplate reportFooterDataTemplate,
bool footerStartsFromTheSecondPage)
{
int pageNumber = 1;
List<ReportPage> ReportPages =
new List<ReportPage>
{
new ReportPage(
reportSize,
backgroundBrush,
margin,
dataContext,
resourceDictionary,
reportHeaderDataTemplate,
(footerStartsFromTheSecondPage) ? null : reportFooterDataTemplate,
pageNumber)
};
foreach (FrameworkElement reportVisualElement in ReportElements)
{
if (ReportPages.Last().GetChildrenActualHeight() + GetActualHeightPlusMargin(reportVisualElement) > reportSize.Height - margin.Top - margin.Bottom)
{
pageNumber++;
ReportPages.Add(
new ReportPage(
reportSize,
backgroundBrush,
margin,
dataContext,
resourceDictionary,
(headerOnlyOnTheFirstPage) ? null : reportHeaderDataTemplate,
reportFooterDataTemplate,
pageNumber));
}
ReportPages.Last().AddElement(reportVisualElement);
}
foreach (ReportPage reportPage in ReportPages)
{
reportPage.LayoutRoot.Measure(reportSize);
reportPage.LayoutRoot.Arrange(new Rect(reportSize));
reportPage.LayoutRoot.UpdateLayout();
}
return ReportPages;
}
private static double GetActualHeightPlusMargin(FrameworkElement elm)
{
return elm.ActualHeight + elm.Margin.Top + elm.Margin.Bottom;
}
private static Size GetReportSize(StackPanel reportContainer, Thickness margin, ReportOrientation orientation, PrintDialog printDialog = null)
{
if (printDialog == null)
printDialog = new PrintDialog();
double reportWidth = reportContainer.ActualWidth + margin.Left + margin.Right;
if (orientation == ReportOrientation.Landscape)
printDialog.PrintTicket.PageOrientation = PageOrientation.Landscape;
double reportHeight = (reportWidth / printDialog.PrintableAreaWidth) * printDialog.PrintableAreaHeight;
return new Size(reportWidth, reportHeight);
}
private static void ForEach<T>(this IEnumerable<T> enumeration, Action<T, int> action)
{
if (enumeration == null)
return;
int index = 0;
foreach (T item in enumeration)
{
action(item, index);
index++;
}
}
}
}
#pragma warning restore 1591