-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMainActivity.cs
379 lines (343 loc) · 18.9 KB
/
MainActivity.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
using Android.App;
using Android.Content;
using Android.OS;
using Docutain.SDK.Xamarin.Android;
using Java.IO;
using System.Threading.Tasks;
using Uri = Android.Net.Uri;
using AndroidX.AppCompat.App;
using AndroidX.RecyclerView.Widget;
using Xamarin.Essentials;
using Google.Android.Material.Dialog;
namespace Docutain_SDK_Example_Xamarin_Android
{
[Activity(Label = "Docutain SDK Example", MainLauncher = true)]
public class MainActivity : AppCompatActivity
{
//A valid license key is required, you can generate one on our website https://sdk.docutain.com/TrialLicense?Source=1311235
private string licenseKey = "YOUR_LICENSE_KEY_HERE";
private ItemType selectedOption = ItemType.NONE;
private SettingsSharedPreferences _settingsSharedPreferences;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
//the Docutain SDK needs to be initialized prior to using any functionality of it
//a valid license key is required, you can generate one on our website https://sdk.docutain.com/TrialLicense?Source=1311235
if (!DocutainSDK.InitSDK(Application, licenseKey))
{
//init of Docutain SDK failed, get the last error message
System.Console.WriteLine("Initialization of the Docutain SDK failed: " + DocutainSDK.LastError);
//your logic to deactivate access to SDK functionality
if (licenseKey == "YOUR_LICENSE_KEY_HERE")
ShowLicenseEmptyInfo();
else
ShowLicenseErrorInfo();
return;
}
//If you want to use text detection (OCR) and/or data extraction features, you need to set the AnalyzeConfiguration
//in order to start all the necessary processes
var analyzeConfig = new AnalyzeConfiguration
{
ReadBIC = true,
ReadPaymentState = true
};
if (!DocumentDataReader.SetAnalyzeConfiguration(analyzeConfig))
{
System.Console.WriteLine("Setting AnalyzeConfiguration failed: " + DocutainSDK.LastError);
}
//Depending on your needs, you can set the Logger's level
Logger.SetLogLevel(Logger.Level.Verbose);
//Depending on the log level that you have set, some temporary files get written on the filesystem
//You can delete all temporary files by using the following method
DocutainSDK.DeleteTempFiles(true);
_settingsSharedPreferences = new SettingsSharedPreferences(this);
if (_settingsSharedPreferences.IsEmpty())
_settingsSharedPreferences.DefaultSettings();
SetContentView(Resource.Layout.activity_main);
SetupRecyclerView();
}
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, Android.Content.PM.Permission[] grantResults)
{
Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);
base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
}
private void SetupRecyclerView()
{
var recyclerView = FindViewById<RecyclerView>(Resource.Id.recycler_view);
LinearLayoutManager linear = new LinearLayoutManager(this);
recyclerView.SetLayoutManager(linear);
recyclerView.SetAdapter(new ListAdapter(item =>
{
switch (item.Type)
{
case ItemType.DOCUMENT_SCAN:
selectedOption = ItemType.NONE;
StartScan(false);
break;
case ItemType.DATA_EXTRACTION:
selectedOption = ItemType.DATA_EXTRACTION;
StartDataExtraction();
break;
case ItemType.TEXT_RECOGNITION:
selectedOption = ItemType.TEXT_RECOGNITION;
StartTextRecognition();
break;
case ItemType.PDF_GENERATING:
selectedOption = ItemType.PDF_GENERATING;
StartPDFGenerating();
break;
case ItemType.SETTINGS:
StartActivity(new Intent(this, typeof(SettingsActivity)));
break;
default:
selectedOption = ItemType.NONE;
System.Console.WriteLine("Invalid item clicked");
break;
}
}));
var dividerItemDecoration = new DividerItemDecoration(recyclerView.Context, LinearLayoutManager.Vertical);
recyclerView.AddItemDecoration(dividerItemDecoration);
}
private void HandleScanResult()
{
// Proceed depending on the previously selected option
switch (selectedOption)
{
case ItemType.PDF_GENERATING:
GeneratePDF(null);
break;
case ItemType.DATA_EXTRACTION:
OpenDataResultActivity(null);
break;
case ItemType.TEXT_RECOGNITION:
OpenTextResultActivity(null);
break;
default:
System.Console.WriteLine("Select an input option first");
break;
}
}
private async void StartScan(bool imageImport)
{
//There are a lot of settings to configure the scanner to match your specific needs
//Check out the documentation to learn more https://docs.docutain.com/docs/Xamarin/docScan#change-default-scan-behaviour
var scanConfig = new DocumentScannerConfiguration();
if (imageImport)
scanConfig.Source = Source.GalleryMultiple;
//In this sample app we provide a settings page which the user can use to alter the scan settings
//The settings are stored in and read from SharedPreferences
//This is supposed to be just an example, you do not need to implement it in that exact way
//If you do not want to provide your users the possibility to alter the settings themselves at all
//You can just set the settings according to the apps needs
//scan settings
scanConfig.AllowCaptureModeSetting = _settingsSharedPreferences.GetScanItem(ScanSettings.AllowCaptureModeSetting).CheckValue;
scanConfig.AutoCapture = _settingsSharedPreferences.GetScanItem(ScanSettings.AutoCapture).CheckValue;
scanConfig.AutoCrop = _settingsSharedPreferences.GetScanItem(ScanSettings.AutoCrop).CheckValue;
scanConfig.MultiPage = _settingsSharedPreferences.GetScanItem(ScanSettings.MultiPage).CheckValue;
scanConfig.PreCaptureFocus = _settingsSharedPreferences.GetScanItem(ScanSettings.PreCaptureFocus).CheckValue;
scanConfig.DefaultScanFilter = _settingsSharedPreferences.GetScanFilterItem(ScanSettings.DefaultScanFilter).ScanValue;
//edit settings
scanConfig.PageEditConfig.AllowPageFilter = _settingsSharedPreferences.GetEditItem(EditSettings.AllowPageFilter).EditValue;
scanConfig.PageEditConfig.AllowPageRotation = _settingsSharedPreferences.GetEditItem(EditSettings.AllowPageRotation).EditValue;
scanConfig.PageEditConfig.AllowPageArrangement = _settingsSharedPreferences.GetEditItem(EditSettings.AllowPageArrangement).EditValue;
scanConfig.PageEditConfig.AllowPageCropping = _settingsSharedPreferences.GetEditItem(EditSettings.AllowPageCropping).EditValue;
scanConfig.PageEditConfig.PageArrangementShowDeleteButton = _settingsSharedPreferences.GetEditItem(EditSettings.PageArrangementShowDeleteButton).EditValue;
scanConfig.PageEditConfig.PageArrangementShowPageNumber = _settingsSharedPreferences.GetEditItem(EditSettings.PageArrangementShowPageNumber).EditValue;
//color settings
var colorPrimary = _settingsSharedPreferences.GetColorItem(ColorSettings.ColorPrimary);
scanConfig.ColorConfig.ColorPrimary = new DocutainColor(colorPrimary.LightCircle, colorPrimary.DarkCircle);
var colorSecondary = _settingsSharedPreferences.GetColorItem(ColorSettings.ColorSecondary);
scanConfig.ColorConfig.ColorSecondary = new DocutainColor(colorSecondary.LightCircle, colorSecondary.DarkCircle);
var colorOnSecondary = _settingsSharedPreferences.GetColorItem(ColorSettings.ColorOnSecondary);
scanConfig.ColorConfig.ColorOnSecondary = new DocutainColor(colorOnSecondary.LightCircle, colorOnSecondary.DarkCircle);
var colorScanButtonsLayoutBackground = _settingsSharedPreferences.GetColorItem(ColorSettings.ColorScanButtonsLayoutBackground);
scanConfig.ColorConfig.ColorScanButtonsLayoutBackground = new DocutainColor(colorScanButtonsLayoutBackground.LightCircle, colorScanButtonsLayoutBackground.DarkCircle);
var colorScanButtonsForeground = _settingsSharedPreferences.GetColorItem(ColorSettings.ColorScanButtonsForeground);
scanConfig.ColorConfig.ColorScanButtonsForeground = new DocutainColor(colorScanButtonsForeground.LightCircle, colorScanButtonsForeground.DarkCircle);
var colorScanPolygon = _settingsSharedPreferences.GetColorItem(ColorSettings.ColorScanPolygon);
scanConfig.ColorConfig.ColorScanPolygon = new DocutainColor(colorScanPolygon.LightCircle, colorScanPolygon.DarkCircle);
var colorBottomBarBackground = _settingsSharedPreferences.GetColorItem(ColorSettings.ColorBottomBarBackground);
scanConfig.ColorConfig.ColorBottomBarBackground = new DocutainColor(colorBottomBarBackground.LightCircle, colorBottomBarBackground.DarkCircle);
var colorBottomBarForeground = _settingsSharedPreferences.GetColorItem(ColorSettings.ColorBottomBarForeground);
scanConfig.ColorConfig.ColorBottomBarForeground = new DocutainColor(colorBottomBarForeground.LightCircle, colorBottomBarForeground.DarkCircle);
var colorTopBarBackground = _settingsSharedPreferences.GetColorItem(ColorSettings.ColorTopBarBackground);
scanConfig.ColorConfig.ColorTopBarBackground = new DocutainColor(colorTopBarBackground.LightCircle, colorTopBarBackground.DarkCircle);
var colorTopBarForeground = _settingsSharedPreferences.GetColorItem(ColorSettings.ColorTopBarForeground);
scanConfig.ColorConfig.ColorTopBarForeground = new DocutainColor(colorTopBarForeground.LightCircle, colorTopBarForeground.DarkCircle);
// alter the onboarding image source if you like
//scanConfig.OnboardingImageSource = ...
// detailed information about theming possibilities can be found here: https://docs.docutain.com/docs/Xamarin/theming
//scanConfig.Theme = ...
//start the document scanner
bool success = await UI.ScanDocument(this, scanConfig);
if (success)
HandleScanResult();
else
System.Console.WriteLine("canceled scan process");
}
private async void StartPDFImport()
{
FileResult pdfFile = null;
switch (selectedOption)
{
case ItemType.PDF_GENERATING:
System.Console.WriteLine("Generating a PDF from a file which is already a PDF makes no sense, please scan a document or import an image.");
break;
case ItemType.DATA_EXTRACTION:
pdfFile = await FilePicker.PickAsync(new PickOptions
{
FileTypes = FilePickerFileType.Pdf
});
if(pdfFile != null)
OpenDataResultActivity(pdfFile.FullPath);
else
System.Console.WriteLine("canceled PDF import");
break;
case ItemType.TEXT_RECOGNITION:
pdfFile = await FilePicker.PickAsync(new PickOptions
{
FileTypes = FilePickerFileType.Pdf
});
if (pdfFile != null)
OpenTextResultActivity(pdfFile.FullPath);
else
System.Console.WriteLine("canceled PDF import");
break;
default:
System.Console.WriteLine("Select an input option first");
break;
}
}
private void StartDataExtraction()
{
ShowInputOptionAlert();
}
private void StartTextRecognition()
{
ShowInputOptionAlert();
}
private void StartPDFGenerating()
{
ShowInputOptionAlert(false);
}
private void ShowInputOptionAlert(bool showPDFImport = true)
{
var items = showPDFImport ? new string[] { GetString(Resource.String.input_option_scan), GetString(Resource.String.input_option_image), GetString(Resource.String.input_option_PDF) } :
new string[] { GetString(Resource.String.input_option_scan), GetString(Resource.String.input_option_image) };
var builder = new MaterialAlertDialogBuilder(this);
builder.SetTitle(Resource.String.title_input_option)
.SetItems(items, (sender, args) =>
{
switch (args.Which)
{
case 0:
StartScan(false);
break;
case 1:
StartScan(true);
break;
case 2:
StartPDFImport();
break;
}
});
builder.Create().Show();
}
private void GeneratePDF(string filePath)
{
Task.Run(() =>
{
if (!string.IsNullOrEmpty(filePath))
{
// If a filePath is available, it means we have imported a file. If so, we need to load it into the SDK first.
if (!DocumentDataReader.LoadFile(filePath))
{
// An error occurred, get the latest error message.
System.Console.WriteLine($"DocumentDataReader.LoadFile failed, last error: {DocutainSDK.LastError}");
return;
}
}
// Define the output file for the PDF.
var file = new File(FilesDir, "SamplePDF");
// Generate the PDF from the currently loaded document.
// The generated PDF also contains the detected text, making the PDF searchable.
// See https://docs.docutain.com/docs/Xamarin/pdfCreation for more details.
var pdfFile = Document.WritePDF(file, true, Document.PDFPageFormat.A4);
if (pdfFile == null)
{
// An error occurred, get the latest error message.
System.Console.WriteLine($"DocumentDataReader.loadFile failed, last error: {DocutainSDK.LastError}");
return;
}
else
{
//display the PDF by using the system's default viewer for demonstration purposes
var pdfUri = FileProvider.GetUriForFile(this, "de.docutain.Docutain_SDK_Example_Xamarin_Android.attachments", pdfFile);
var intent = new Intent(Intent.ActionView);
intent.AddFlags(ActivityFlags.GrantReadUriPermission);
intent.SetDataAndType(pdfUri, "application/pdf");
try
{
StartActivity(intent);
}
catch (ActivityNotFoundException ex)
{
System.Console.WriteLine("No Activity available for displaying the PDF");
}
}
});
}
private void OpenDataResultActivity(string filePath)
{
var intent = new Intent(this, typeof(DataResultActivity));
if (!string.IsNullOrEmpty(filePath))
intent.PutExtra("filePath", filePath);
StartActivity(intent);
}
private void OpenTextResultActivity(string filePath)
{
var intent = new Intent(this, typeof(TextResultActivity));
if (!string.IsNullOrEmpty(filePath))
intent.PutExtra("filePath", filePath);
StartActivity(intent);
}
private void ShowLicenseEmptyInfo()
{
new MaterialAlertDialogBuilder(this)
.SetTitle("License empty")
.SetMessage("A valid license key is required. Please click \"GET LICENSE\" in order to create a free trial license key on our website.")
.SetPositiveButton("Get License", (sender, args) =>
{
Intent intent = new Intent(Intent.ActionView, Uri.Parse("https://sdk.docutain.com/TrialLicense?Source=1311235"));
StartActivity(intent);
Finish();
})
.SetCancelable(false)
.Show();
}
private void ShowLicenseErrorInfo()
{
new MaterialAlertDialogBuilder(this)
.SetTitle("License error")
.SetMessage("A valid license key is required. Please contact our support to get an extended trial license.")
.SetPositiveButton("Contact Support", (sender, args) =>
{
Intent intent = new Intent(Intent.ActionSendto, Uri.Parse("mailto:[email protected]"));
intent.PutExtra(Intent.ExtraSubject, "Trial License Error");
intent.PutExtra(Intent.ExtraText, $"Please keep your following trial license key in this e-mail: {licenseKey}");
if (intent.ResolveActivity(PackageManager) != null)
{
StartActivity(intent);
Finish();
}
else
{
System.Console.WriteLine("No Mail App available, please contact us manually via [email protected]");
}
})
.SetCancelable(false)
.Show();
}
}
}