-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathExporter.cs
94 lines (77 loc) · 2.94 KB
/
Exporter.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
using System;
using System.Threading;
using System.Threading.Tasks;
using GridExport.ViewModels;
using DevExpress.Drawing.Printing;
using DevExpress.Maui.DataGrid;
using DevExpress.Maui.DataGrid.Export;
namespace GridExport.Models;
public class Exporter {
object lockObject = new object();
CancellationTokenSource cancellationTokenSource;
public bool IsInExport => this.cancellationTokenSource != null;
Action onStartExport;
Action<Exception> onEndExport;
Action onCancelExport;
public Exporter(Action onStartExport, Action<Exception> onEndExport, Action onCancelExport) {
this.onStartExport = onStartExport;
this.onEndExport = onEndExport;
this.onCancelExport = onCancelExport;
}
public void Export(DataGridView grid, string path, ExportFormat format, PaperSize paperSize, bool isLandscape) {
Task.Factory.StartNew(() => {
try {
lock (this.lockObject) {
if (IsInExport) {
return;
}
this.cancellationTokenSource = new CancellationTokenSource();
}
this.onStartExport?.Invoke();
CancellationToken token = this.cancellationTokenSource.Token;
token.Register(this.onCancelExport);
DataGridExportLink exportLink = grid.GetExportLink();
exportLink.PaperKind = paperSize switch {
PaperSize.A3 => DXPaperKind.A3,
PaperSize.A4 => DXPaperKind.A4,
PaperSize.A5 => DXPaperKind.A5,
_ => DXPaperKind.A4
};
exportLink.Landscape = isLandscape;
token.ThrowIfCancellationRequested();
exportLink.CreateDocument();
token.ThrowIfCancellationRequested();
switch (format) {
case ExportFormat.Pdf:
exportLink.ExportToPdf(path);
break;
case ExportFormat.Xlsx:
exportLink.ExportToXlsx(path);
break;
case ExportFormat.Docx:
exportLink.ExportToDocx(path);
break;
}
token.ThrowIfCancellationRequested();
lock (this.lockObject) {
this.cancellationTokenSource = null;
}
this.onEndExport?.Invoke(null);
} catch (Exception ex) {
lock (this.lockObject) {
this.cancellationTokenSource = null;
}
this.onEndExport?.Invoke(ex);
}
});
}
public void Cancel() {
lock (this.lockObject) {
if (IsInExport) {
this.cancellationTokenSource.Cancel();
this.cancellationTokenSource = null;
}
}
}
}