-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
294 lines (255 loc) · 10.4 KB
/
Program.cs
File metadata and controls
294 lines (255 loc) · 10.4 KB
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
using DynamicWebTWAIN.RestClient;
using DynamicWebTWAIN.Service;
namespace ConsoleApp;
class Program
{
private static string productKey = "DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9";
private static int totalScannedPages = 0;
static async Task Main(string[] args)
{
ServiceManager? serviceManager = null;
DWTClient? dwtClient = null;
string? documentId = null;
Scanner? selectedScanner = null;
try
{
Console.WriteLine("=== Dynamic Web TWAIN Console Application ===\n");
// Initialize service
Console.WriteLine("Initializing service...");
serviceManager = new ServiceManager();
serviceManager.CreateService();
dwtClient = new DWTClient(serviceManager.Service.BaseAddress, productKey);
Console.WriteLine("Service initialized successfully!\n");
// List all scanners
Console.WriteLine("Getting scanner list...");
var scanners = await dwtClient.ScannerControlClient.ScannerManager.GetScanners(EnumDeviceTypeMask.DT_TWAINSCANNER | EnumDeviceTypeMask.DT_WIASCANNER);
if (scanners == null || scanners.Count == 0)
{
Console.WriteLine("No scanners found.");
return;
}
// Create document
Console.WriteLine("Creating document...");
CreateDocumentOptions docOptions = new CreateDocumentOptions();
docOptions.Name = "ScannedDocument_" + DateTime.Now.ToString("yyyyMMdd_HHmmss");
var document = await dwtClient.DocumentManagerClient.CreateDocument(docOptions);
if (document == null)
{
Console.WriteLine("Failed to create document.");
return;
}
documentId = document.Uid;
Console.WriteLine($"Document created successfully, ID: {documentId}\n");
// Main menu loop
bool exit = false;
while (!exit)
{
Console.WriteLine("\n=== Main Menu ===");
Console.WriteLine($"Current Scanner: {(selectedScanner != null ? (selectedScanner.Type == EnumDeviceTypeMask.DT_WIASCANNER ? "WIA-" + selectedScanner.Name : selectedScanner.Name) : "Not selected")}");
Console.WriteLine($"Total scanned pages: {totalScannedPages}");
Console.WriteLine("1. Select Source");
Console.WriteLine("2. Scan");
Console.WriteLine("3. Save as PDF");
Console.WriteLine("4. Exit");
Console.Write("\nSelect option: ");
string? choice = Console.ReadLine();
switch (choice)
{
case "1":
selectedScanner = await SelectSource(scanners);
break;
case "2":
if (selectedScanner == null)
{
Console.WriteLine("\nPlease select a scanner first (Option 1).");
}
else
{
await ScanDocument(dwtClient, selectedScanner, documentId);
}
break;
case "3":
await SaveDocumentAsPDF(dwtClient, documentId);
break;
case "4":
exit = true;
break;
default:
Console.WriteLine("Invalid option. Please try again.");
break;
}
}
}
catch (Exception ex)
{
Console.WriteLine($"\nError occurred: {ex.Message}");
Console.WriteLine($"Details: {ex.StackTrace}");
}
finally
{
// Cleanup resources
dwtClient?.Dispose();
serviceManager?.Dispose();
Console.WriteLine("\nPress any key to exit...");
Console.ReadKey();
}
}
private static Task<Scanner?> SelectSource(IReadOnlyList<Scanner> scanners)
{
try
{
Console.WriteLine("\n--- Select Scanner Source ---");
Console.WriteLine($"\nFound {scanners.Count} scanner(s):");
for (int i = 0; i < scanners.Count; i++)
{
var scanner = scanners[i];
if (scanner.Type == EnumDeviceTypeMask.DT_WIASCANNER)
{
Console.WriteLine($" [{i}] {"WIA-" + scanners[i].Name}");
}
else
{
Console.WriteLine($" [{i}] {scanners[i].Name}");
}
}
Console.Write("\nSelect scanner index (default 0): ");
string? input = Console.ReadLine();
int selectedIndex = 0;
if (!string.IsNullOrWhiteSpace(input) && int.TryParse(input, out int index) && index >= 0 && index < scanners.Count)
{
selectedIndex = index;
}
var selectedScanner = scanners[selectedIndex];
if (selectedScanner.Type == EnumDeviceTypeMask.DT_WIASCANNER)
{
Console.WriteLine($"Selected: {"WIA-" + selectedScanner.Name}");
}
else
{
Console.WriteLine($"Selected: {selectedScanner.Name}");
}
return Task.FromResult<Scanner?>(selectedScanner);
}
catch (Exception ex)
{
Console.WriteLine($"Error selecting scanner: {ex.Message}");
return Task.FromResult<Scanner?>(null);
}
}
private static async Task ScanDocument(DWTClient dwtClient, Scanner scanner, string documentId)
{
IScannerJobClient? jobClient = null;
try
{
Console.WriteLine("\n--- Scanning ---");
// Configure scan job
CreateScanJobOptions options = new CreateScanJobOptions();
options.AutoRun = false;
options.Device = scanner.Device;
options.Config = new ScannerConfiguration();
options.Config.IfShowUI = false;
options.Config.IfFeederEnabled = false;
options.Config.IfDuplexEnabled = false;
options.Config.IfDisableSourceAfterAcquire = true;
options.Config.PixelType = EnumDWT_PixelType.TWPT_RGB;
// Create scan job
jobClient = await dwtClient.ScannerControlClient.ScannerJobs.CreateJob(options);
// Scan listener
var tcs = new TaskCompletionSource<bool>(TaskCreationOptions.RunContinuationsAsynchronously);
var scannedCount = 0;
var processingCount = 0;
var lockObj = new object();
jobClient.PageScanned += async (sender, e) =>
{
lock (lockObj)
{
processingCount++;
scannedCount++;
Console.WriteLine($"Processing page {scannedCount}...");
}
try
{
await dwtClient.DocumentManagerClient.AddImageToDocument(documentId, e.Url);
}
catch (Exception ex)
{
Console.WriteLine($"Error processing image: {ex.Message}");
}
finally
{
lock (lockObj) { processingCount--; }
}
};
jobClient.TransferEnded += async (sender, e) =>
{
// Wait for all pages to complete processing
for (int i = 0; i < 100; i++)
{
lock (lockObj)
{
if (processingCount == 0) break;
}
await Task.Delay(100);
}
tcs.TrySetResult(true);
};
// Start scanning
Console.WriteLine("Starting scan, please place document in scanner...");
await jobClient.StartJob();
// Wait for scan completion
var completedTask = await Task.WhenAny(tcs.Task, Task.Delay(TimeSpan.FromSeconds(120)));
if (completedTask != tcs.Task)
{
Console.WriteLine("\nScan timeout.");
return;
}
totalScannedPages += scannedCount;
Console.WriteLine($"\nScan completed! Pages scanned in this session: {scannedCount}");
Console.WriteLine($"Total scanned pages: {totalScannedPages}");
}
catch (Exception ex)
{
Console.WriteLine($"Error during scanning: {ex.Message}");
}
finally
{
// Cleanup
if (jobClient != null)
{
await jobClient.DeleteJob();
}
}
}
private static async Task SaveDocumentAsPDF(DWTClient dwtClient, string documentId)
{
try
{
if (totalScannedPages == 0)
{
Console.WriteLine("\nNo pages scanned yet. Please scan documents first.");
return;
}
Console.WriteLine("\n--- Saving as PDF ---");
Console.WriteLine("Generating PDF file...");
byte[] pdfBlob = await dwtClient.DocumentManagerClient.SaveDocumentAsPDF(documentId);
if (pdfBlob == null || pdfBlob.Length == 0)
{
Console.WriteLine("Failed to generate PDF.");
return;
}
// Save to desktop
string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string fileName = $"ScannedDocument_{DateTime.Now:yyyyMMdd_HHmmss}.pdf";
string filePath = Path.Combine(desktopPath, fileName);
File.WriteAllBytes(filePath, pdfBlob);
Console.WriteLine($"\n✓ PDF saved successfully!");
Console.WriteLine($" File location: {filePath}");
Console.WriteLine($" File size: {pdfBlob.Length / 1024.0:F2} KB");
Console.WriteLine($" Total pages: {totalScannedPages}");
}
catch (Exception ex)
{
Console.WriteLine($"Error saving PDF: {ex.Message}");
}
}
}