-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathForm1.cs
More file actions
1116 lines (957 loc) · 42.5 KB
/
Form1.cs
File metadata and controls
1116 lines (957 loc) · 42.5 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
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
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using Sig.DeviceAPI;
using Sig.SignAPI;
using Sig.PdfClient;
using iText.Kernel.Pdf;
using iText.Layout;
using iText.IO.Image;
using System.Security.Cryptography;
using System.Text;
using System.Management;
using PDFtoImage;
namespace StepOverModel
{
public partial class Form1 : Form
{
#region -----------------------------Variables and Objects----------------------------------------------
// number of pages
int pages = 0;
// Origin PDF file path
string source;
// License path
string licensePath = "License/FingerTech.xml";
// Create objects of the DeviceAPI
private static IDriver driverInterface = new Driver();
private static IReadSignatureImageOptions imageOptions = driverInterface.ReadSignatureImageOptions;
// Create objects of the SignAPI
private ISigning theSigningObject = null;
// Create objects of the SetCertificate and create certificate path
private ISetCertificate setCertificate = driverInterface.SetCertificate;
string certPath;
// WMI query to monitor for device arrival events
private ManagementEventWatcher arrivalWatcher;
// WMI query to monitor for device removal events
private ManagementEventWatcher removalWatcher;
// Device is plugged
private bool devicePlugged = false;
#endregion
#region -----------------------------Methods For Forms--------------------------------------------------
// Form is open
public Form1()
{
InitializeComponent();
// Check if the cache file exists
LoadConfig();
// Set the device
SearchDevice(devicePlugged);
// Set the value of the scroll bar x
sb_x.Value = int.Parse(tb_x.Text);
sb_x.Maximum = 595 - int.Parse(tb_sigWidth.Text);
// Create the tmp folder
if (!Directory.Exists("tmp"))
{
Directory.CreateDirectory("tmp");
}
driverInterface.IsSignFinishedEnabled = false;
// Initialize the WMI event watchers
InitializeWmiWatchers();
// Events
SubscribeToEvents();
}
// Form is closed
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
// Save the configuration
SaveConfig();
// Dispose the image
if (pb_pdfView.Image != null)
{
pb_pdfView.Image.Dispose();
}
// Delete the "tmp/" folder and its contents
if (Directory.Exists("tmp"))
{
Directory.Delete("tmp", true);
}
// Stop the WMI event watchers
arrivalWatcher.Stop();
arrivalWatcher.Dispose();
removalWatcher.Stop();
removalWatcher.Dispose();
}
#endregion
#region -----------------------------Methods For Events-------------------------------------------------
// Subscribe to events
private void SubscribeToEvents()
{
// Event for signature image changed
driverInterface.SignImgChanged += (object sender, EventArgs e) =>
{
pb_signature.Invoke((MethodInvoker)(() => UpdateSignatureImage()));
};
}
// Initialize WMI event watchers
private void InitializeWmiWatchers()
{
// WMI query to monitor for device arrival events
string arrivalQuery = "SELECT * FROM Win32_DeviceChangeEvent WHERE EventType = 2";
arrivalWatcher = new ManagementEventWatcher(arrivalQuery);
arrivalWatcher.EventArrived += ArrivalEventArrived;
arrivalWatcher.Start();
// WMI query to monitor for device removal events
string removalQuery = "SELECT * FROM Win32_DeviceChangeEvent WHERE EventType = 3";
removalWatcher = new ManagementEventWatcher(removalQuery);
removalWatcher.EventArrived += RemovalEventArrived;
removalWatcher.Start();
}
private void tb_passCert_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Enter)
{
bt_setCert_Click(sender, e);
}
}
#endregion
#region -----------------------------Methods Called-----------------------------------------------------
// Error Message
private void ShowErrorMessage(Error error)
{
if (error != Error.SUCCESS)
MessageBox.Show("Error: \n" + error.ToString());
}
// Convert PDF to TIFF
public void ConvertPDFtoImg(string source, int page)
{
// clear the pb_pdfView.image if have content
if (pb_pdfView.Image != null)
{
pb_pdfView.Image.Dispose();
}
using (var pdfstream = File.OpenRead(source))
{
var options = new RenderOptions
{
Width = pb_pdfView.Width, // Set the FitToSizeWidth property to the width of pb_pdfView
Height = pb_pdfView.Height, // Set the FitToSizeHeight property to the height of pb_pdfView
};
Conversion.SaveJpeg("tmp/Output.bmp", pdfstream, page: page, options: options);
pb_pdfView.Image = System.Drawing.Image.FromFile("tmp/Output.bmp");
}
}
// Get the destination path
private string GetDestinPath()
{
string destSource = "";
// Create variable to number of the signature if necessary
int number = 2;
// Check if source file is unsigned and if exist a signed file
if (!source.Contains("_signed") && !File.Exists(source.Replace(".pdf", "_signed.pdf")))
{
destSource = source.Replace(".pdf", "_signed.pdf");
}
else // If the file is signed
{
if (source.Contains("_signed.pdf")) // If the file is signed and dont have a number in the end
{
// Check if the file with the number 2 dont exists
if (!File.Exists(source.Replace("_signed.pdf", "_signed" + number + ".pdf")))
{
destSource = source.Replace("_signed.pdf", "_signed" + number + ".pdf");
}
else // If the file with the number 2 exists
{
number++; // Increment the number
// Check if the file with the next number exists
while (File.Exists(source.Replace("_signed.pdf", "_signed" + number + ".pdf")))
{
number++;
}
destSource = source.Replace("_signed.pdf", "_signed" + number + ".pdf");
}
}
else if (!source.Contains("_signed")) // If the file is signed and have a number in the end
{
// Check if the file with the number 2 dont exists and if the file with the number 2 exists increment the number
// And check if the file with the next number exists
while (File.Exists(source.Replace(".pdf", "_signed" + number + ".pdf")))
{
number++;
}
destSource = source.Replace(".pdf", "_signed" + number + ".pdf");
}
else // If the file is signed and have a number in the end
{
string letter = source[^5..]; // Get the number of the file
while (File.Exists(source.Replace(letter, number + ".pdf"))) // Check the file with the number exists, ascending the number sequentially
{
number++;
}
destSource = source.Replace(letter, number + ".pdf");
}
}
return destSource; // Old path + _Signed
}
#endregion
#region -----------------------------Confg Save and Load------------------------------------------------
// Save the configuration
private void SaveConfig()
{
// if certPath is empty, return
if (!string.IsNullOrEmpty(certPath) || !string.IsNullOrEmpty(licensePath) && licensePath != "License/FingerTech.xml")
{
// Create a file to write to.
string filepath = "cache.txt";
// Create a byte array for additional entropy when using Protect method
byte[] entropy = { 1, 2, 3, 4, 1, 2, 3, 4 };
// Encrypt the password
byte[] encryptedPassword = ProtectedData.Protect(Encoding.UTF8.GetBytes(tb_passCert.Text), entropy, DataProtectionScope.CurrentUser);
// Convert the encrypted data to a string
string encryptedPasswordString = Convert.ToBase64String(encryptedPassword);
if (tb_passCert.Text == "")
{
encryptedPasswordString = "";
}
// Combine the certPath and passCert
string combinedStrings = certPath + Environment.NewLine + encryptedPasswordString + Environment.NewLine + licensePath;
// Verify if the file exists
if (!File.Exists(filepath))
{
// Create a file to write to.
using (StreamWriter sw = File.CreateText(filepath))
{
sw.WriteLine(combinedStrings);
}
}
else
{
// Open the file to read from.
using (StreamReader sr = File.OpenText(filepath))
{
// Verify if the certPath and passCert already modified
bool change = false;
string s = "";
// Count the lines
int line = 0;
// Read the file
while ((s = sr.ReadLine()) != null)
{
if (s != tb_passCert.Text && s.Contains(".pfx") || s != certPath && line == 1 || s != licensePath && s.Contains(".xml"))
{
change = true;
break;
}
line++;
}
sr.Close();
// If the certPath and passCert already modified
if (change)
{
File.WriteAllText(filepath, combinedStrings);
}
}
}
}
}
// Load the configuration
private void LoadConfig()
{
// Verify if the file exists
if (File.Exists("cache.txt"))
{
// Open the file to read from.
using (StreamReader sr = File.OpenText("cache.txt"))
{
string s = "";
while ((s = sr.ReadLine()) != null)
{
if (s.Contains(".pfx"))
{
certPath = s;
}
else if (s.Contains(".xml"))
{
licensePath = s;
}
else if (s != "" && s != certPath && s != licensePath)
{
// Convert the encrypted data to a byte array
byte[] encryptedPasswordBytes = Convert.FromBase64String(s);
// Define the entropy used during encryption (if any).
byte[] entropy = { 1, 2, 3, 4, 1, 2, 3, 4 }; // This should match the entropy used during encryption.
// Decrypt the byte array.
byte[] decryptedPasswordBytes = ProtectedData.Unprotect(encryptedPasswordBytes, entropy, DataProtectionScope.CurrentUser);
// Convert the decrypted byte array back to a string.
string decryptedPassword = Encoding.UTF8.GetString(decryptedPasswordBytes);
// Set the value of the text box passCert
tb_passCert.Text = decryptedPassword;
}
}
}
}
}
#endregion
#region -----------------------------Usb----------------------------------------------------------------
// For the usb arrival and removal events
private void ArrivalEventArrived(object sender, EventArgs e)
{
// USB device was plugged in
SearchDevice(devicePlugged);
}
private void RemovalEventArrived(object sender, EventArgs e)
{
// USB device was removed
SearchDevice(devicePlugged);
}
// Search the device
private void SearchDevice(bool plugged)
{
string[]? deviceNames;
int guiOption = 0;
// Filter the device
FilterDeviceKind DeviceFilter = FilterDeviceKind.dkStepOver;
driverInterface.DeviceSearch(out deviceNames, guiOption, DeviceFilter);
if (deviceNames.Length == 0)
{
// Show the message
if (this.InvokeRequired)
{
this.Invoke(new Action(() => lb_DeviceInfo.Text = ("No device found!" +
"\nSignature options is disable.")));
}
else
{
lb_DeviceInfo.Text = ("No device found!" +
"\nSignature options is disable.");
}
// Disable the buttons
if (this.InvokeRequired)
{
this.Invoke(new Action(() => gb_sign.Enabled = false));
this.Invoke(new Action(() => bt_StopSignature.Enabled = false));
this.Invoke(new Action(() => bt_saveImage.Enabled = false));
this.Invoke(new Action(() => bt_lineColor.Enabled = false));
this.Invoke(new Action(() => lb_license.Text = ""));
if (bt_signPDFImg.Enabled)
{
this.Invoke(new Action(() => bt_signPDF.Enabled = false));
}
if (bt_license.Visible)
{
this.Invoke(new Action(() => bt_license.Visible = false));
}
}
else
{
gb_sign.Enabled = false;
bt_StopSignature.Enabled = false;
bt_saveImage.Enabled = false;
bt_lineColor.Enabled = false;
lb_license.Text = "";
lb_license.ForeColor = Color.Red;
if (bt_signPDFImg.Enabled)
{
bt_signPDF.Enabled = false;
}
if (bt_license.Visible)
{
bt_license.Visible = false;
}
}
devicePlugged = false;
}
else if (!devicePlugged)
{
// Set the device
Error r = driverInterface.SetDevice(deviceNames[0]);
if (r == Error.SUCCESS)
{
// Activate buttons
if (this.InvokeRequired)
{
this.Invoke(new Action(() => gb_sign.Enabled = true));
this.Invoke(new Action(() => bt_StopSignature.Enabled = false));
this.Invoke(new Action(() => bt_saveImage.Enabled = false));
this.Invoke(new Action(() => bt_lineColor.Enabled = true));
if (bt_signPDFImg.Enabled)
{
this.Invoke(new Action(() => bt_signPDF.Enabled = true));
}
}
else
{
gb_sign.Enabled = true;
bt_StopSignature.Enabled = false;
bt_saveImage.Enabled = false;
bt_lineColor.Enabled = true;
if (bt_signPDFImg.Enabled)
{
bt_signPDF.Enabled = true;
}
}
devicePlugged = true;
}
// Load the license
r = driverInterface.LoadLicense(licensePath);
if (r != Error.SUCCESS)
{
if (this.InvokeRequired)
{
this.Invoke(new Action(() => lb_license.Text = Char.ConvertFromUtf32(0x274C)));
this.Invoke(new Action(() => lb_license.ForeColor = Color.Red));
this.Invoke(new Action(() => bt_license.Visible = true));
}
else
{
lb_license.Text = Char.ConvertFromUtf32(0x274C);
lb_license.ForeColor = Color.Red;
bt_license.Visible = true;
}
}
else
{
if (this.InvokeRequired)
{
this.Invoke(new Action(() => lb_license.Text = Char.ConvertFromUtf32(0x2714) + Char.ConvertFromUtf32(0xFE0F)));
this.Invoke(new Action(() => lb_license.ForeColor = Color.Green));
this.Invoke(new Action(() => bt_license.Visible = false));
}
else
{
lb_license.Text = Char.ConvertFromUtf32(0x2714) + Char.ConvertFromUtf32(0xFE0F);
lb_license.ForeColor = Color.Green;
bt_license.Visible = false;
}
}
// Show the device info
if (this.InvokeRequired)
{
this.Invoke(new Action(() => lb_DeviceInfo.Text = ("Device Info: " + deviceNames[0])));
}
else
{
lb_DeviceInfo.Text = ("Device Info: " + deviceNames[0]);
}
}
}
#endregion
#region -----------------------------Methods For Singing------------------------------------------------
// Button to start signature
private void bt_StartSignature_Click(object sender, EventArgs e)
{
Error r = driverInterface.StartSignatureMode(SignMode.StandardSign);
ShowErrorMessage(r);
bt_StopSignature.Enabled = true;
bt_saveImage.Enabled = true;
}
// Button to stop signature
private void bt_StopSignature_Click(object sender, EventArgs e)
{
driverInterface.StopSignatureCapture();
// Clear the device screen
driverInterface.UploadPromoScreen("Custom.png", 1, DisplayOrientation.DEG_0, 10);
// Disable the button
bt_StopSignature.Enabled = false;
}
// Button to save signature image
private void bt_saveImage_Click(object sender, EventArgs e)
{
// Check if have signature image
if (pb_signature.Image == null)
{
MessageBox.Show("No signature image to save");
return;
}
// Show save file dialog
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "BMP Image|*.bmp|SOI Image|*.soi|JPEG Image|*.jpg|PNG Image|*.png";
saveFileDialog.Title = "Save Signature Image";
saveFileDialog.ShowDialog();
// Get the selected file path and name
string filePath = saveFileDialog.FileName;
// If Cancel button was pressed, return
if (string.IsNullOrEmpty(filePath))
return;
// Show a message box with the save options
DialogResult result = MessageBox.Show("Save without background?", "Save", MessageBoxButtons.YesNo);
// Check the result
if (result == DialogResult.Yes)
{
// Check if a file was selected
if (!string.IsNullOrEmpty(filePath))
{
// Save the signature image
pb_signature.Image.Save(filePath);
}
}
else if (result == DialogResult.No)
{
// Checl if a file was selected
if (!string.IsNullOrEmpty(filePath))
{
driverInterface.ReadSignatureImage(pb_signature.Width, pb_signature.Height, filePath);
}
}
// Disable the button
bt_saveImage.Enabled = false;
}
// Button to modify the color of the signature line
private void bt_lineColor_Click(object sender, EventArgs e)
{
ColorDialog colorDialog = new ColorDialog();
colorDialog.Color = imageOptions.LineColor;
colorDialog.ShowDialog();
imageOptions.LineColor = colorDialog.Color;
}
// Update signature image in picture box
void UpdateSignatureImage()
{
Error error = driverInterface.ReadSignatureImage(pb_signature.Width, pb_signature.Height, out Bitmap bitmap); // API which gets the Signature image
bool source_is_wider = (float)bitmap.Width / bitmap.Height > (float)pb_signature.Width / pb_signature.Height;
var resized = new Bitmap(pb_signature.Width, pb_signature.Height);
var g = Graphics.FromImage(resized);
g.Clear(Color.Transparent); // Set the background color to transparent
var dest_rect = new System.Drawing.Rectangle(0, 0, pb_signature.Width, pb_signature.Height);
System.Drawing.Rectangle src_rect;
if (source_is_wider)
{
float size_ratio = (float)pb_signature.Height / bitmap.Height;
int sample_width = (int)(pb_signature.Width / size_ratio);
src_rect = new System.Drawing.Rectangle((bitmap.Width - sample_width) / 2, 0, sample_width, bitmap.Height);
}
else
{
float size_ratio = (float)pb_signature.Width / bitmap.Width;
int sample_height = (int)(pb_signature.Height / size_ratio);
src_rect = new System.Drawing.Rectangle(0, (bitmap.Height - sample_height) / 2, bitmap.Width, sample_height);
}
g.DrawImage(bitmap, dest_rect, src_rect, GraphicsUnit.Pixel);
g.Dispose();
pb_signature.Image = resized;
pb_signPrev.Image = resized;
}
#endregion
#region -----------------------------Methods For manipulate PDF-----------------------------------------
// Load PDF file
private void bt_loadPDF_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "PDF Files|*.pdf";
openFileDialog.Title = "Select a PDF File";
openFileDialog.ShowDialog();
if (openFileDialog.FileName != "")
{
// Set the origin PDF file path and save the signed PDF file path
source = openFileDialog.FileName;
// Convert the pages to images
try
{
ConvertPDFtoImg(source, 0);
}
catch (Exception ex)
{
MessageBox.Show("Error: \n" + ex.Message);
// Clear the picture box and disable the buttons
pb_pdfView.Image = null;
bt_signPDFImg.Enabled = false;
tb_page.Enabled = false;
tb_x.Enabled = false;
tb_y.Enabled = false;
tb_sigWidth.Enabled = false;
tb_sigHeight.Enabled = false;
sb_x.Enabled = false;
sb_y.Enabled = false;
bt_previousPage.Visible = false;
bt_nextPage.Visible = false;
pb_pdfView.Enabled = false;
pb_signPrev.Visible = false;
// Clear source
source = null;
return;
}
// Initialize the PDF file
iText.Kernel.Pdf.PdfDocument pdfDocument = new iText.Kernel.Pdf.PdfDocument(new PdfReader(source));
// Get Number of pages and set the number of pages for the text box
pages = pdfDocument.GetNumberOfPages();
tb_page.Text = "1";
lb_nPages.Text = "/ " + pages;
// Get the PDF file size
iText.Kernel.Geom.Rectangle pageSize = pdfDocument.GetFirstPage().GetPageSize();
tb_a4x.Text = ((int)Math.Round(pageSize.GetWidth())).ToString();
tb_a4y.Text = ((int)Math.Round(pageSize.GetHeight())).ToString();
// Dispose the pdf document
pdfDocument.Close();
// Att tb_x, tb_y, tb_sigWidth, tb_sigHeight
tb_x_TextChanged(sender, e);
tb_y_TextChanged(sender, e);
tb_sigWidth_TextChanged(sender, e);
tb_sigHeight_TextChanged(sender, e);
// Enable the button to sign PDF file with image
bt_signPDFImg.Enabled = true;
tb_x.Enabled = true;
tb_y.Enabled = true;
tb_sigWidth.Enabled = true;
tb_sigHeight.Enabled = true;
sb_x.Enabled = true;
sb_y.Enabled = true;
pb_pdfView.Enabled = true;
pb_signPrev.Visible = true;
if (pages == 1)
{
bt_previousPage.Visible = false;
bt_nextPage.Visible = false;
}
else
{
tb_page.Enabled = true;
bt_previousPage.Visible = false;
bt_nextPage.Visible = true;
}
if (bt_StartSignature.Enabled)
{
bt_signPDF.Enabled = true;
}
}
}
// Button to sign PDF file with image
private void bt_signPDFImg_Click(object sender, EventArgs e)
{
// Create variable to destination PDF file path
string destSource = GetDestinPath();
// Create variable to signature image path
string imgpath = "";
// Check if have the signature image in the picture box
if (pb_signature.Image != null)
{
// Check if user like to use the current signature
DialogResult imageUse = MessageBox.Show("Use current signature?", "Signature", MessageBoxButtons.YesNo);
if (imageUse == DialogResult.Yes)
{
// Save the temporary signature image
pb_signature.Image.Save("tmp/Sign.bmp");
imgpath = "tmp/Sign.bmp";
}
}
else
{
// Select the image to add to the PDF file
OpenFileDialog openFileDialogImage = new OpenFileDialog();
openFileDialogImage.Filter = "Image Files|*.bmp;*.jpg;*.jpeg;*.png";
openFileDialogImage.Title = "Select an sign Image File";
openFileDialogImage.ShowDialog();
imgpath = openFileDialogImage.FileName;
}
if (imgpath != "")
{
// Modify the PDF file
iText.Kernel.Pdf.PdfDocument pdfDocument = new iText.Kernel.Pdf.PdfDocument(new PdfReader(source), new PdfWriter(destSource));
// Document object to modify the PDF file
Document document = new Document(pdfDocument);
// Add the image
ImageData imageData = ImageDataFactory.Create(imgpath);
iText.Layout.Element.Image signImage = new iText.Layout.Element.Image(imageData);
signImage.ScaleAbsolute(Convert.ToInt32(tb_sigWidth.Text), Convert.ToInt32(tb_sigHeight.Text));
// Set the position of the image
signImage.SetFixedPosition(Convert.ToInt32(tb_page.Text), Convert.ToInt32(tb_x.Text), Convert.ToInt32(tb_y.Text));
// Add the image to the PDF file
document.Add(signImage);
// Close the document
document.Close();
ConvertPDFtoImg(destSource, int.Parse(tb_page.Text) - 1);
bt_signPDFImg.Enabled = false;
bt_signPDF.Enabled = false;
tb_page.Enabled = false;
tb_x.Enabled = false;
tb_y.Enabled = false;
tb_sigWidth.Enabled = false;
tb_sigHeight.Enabled = false;
sb_x.Enabled = false;
sb_y.Enabled = false;
bt_previousPage.Visible = false;
bt_nextPage.Visible = false;
pb_pdfView.Enabled = false;
pb_signPrev.Visible = false;
// Clear source
source = "";
}
else
{
MessageBox.Show("No image to sign");
}
}
#endregion
#region -----------------------------Methods For sign PDF-----------------------------------------------
private async void bt_signPDF_Click(object sender, EventArgs e)
{
// Create variable to destination PDF file path
string destSource = GetDestinPath();
// Create variable to document octets
byte[] documentOctets = File.ReadAllBytes(source);
// Set the certificate
if (certPath != "" && tb_passCert.Text != "")
{
Error r = setCertificate.FromPKCS12File(certPath, tb_passCert.Text);
ShowErrorMessage(r);
}
// Set the object of the Signing
using (theSigningObject = await SigningFactory.StartAsync(driverInterface, documentOctets)) // Auto-Dispose in the end
{
// Get the device properties
IDeviceProperties deviceProperties = driverInterface.DeviceProperties;
// Set the coordinate of the signature
FieldPosition fieldPosition = new FieldPosition((int.Parse(tb_a4y.Text) - int.Parse(tb_y.Text)),
int.Parse(tb_x.Text),
(int.Parse(tb_a4y.Text) - int.Parse(tb_y.Text) - int.Parse(tb_sigHeight.Text)),
int.Parse(tb_x.Text) + int.Parse(tb_sigWidth.Text));
// Get the page number
fieldPosition.PageNumber = int.Parse(tb_page.Text) - 1;
// Show the signInfo form
SignInfo signInfo = new SignInfo();
signInfo.ShowDialog();
if (!signInfo.Ok)
{
MessageBox.Show("signature canceled");
signInfo.Dispose();
return;
}
// Set the device signature image
signInfo.behaviour.UseRectangle(Sig.SignAPI.Rectangle.FromBottomLeft(0, 0, deviceProperties.Hardware.DisplayWidth, deviceProperties.Hardware.DisplayHeight)); // Set the SigImg size in device
// Set the device end sign in 3 seconds
driverInterface.IsSignFinishedEnabled = true;
// Sign the PDF file
_ = await theSigningObject.SignAsync(signInfo.signatureInfo.Name, fieldPosition, signInfo.signatureInfo, signInfo.behaviour);
// Download the signed PDF file
byte[] signedDocument = await theSigningObject.Client.DownloadPdfAsync();
File.WriteAllBytes(destSource, signedDocument);
// Restore the device end sign
driverInterface.IsSignFinishedEnabled = false;
// Get new imag and Disable the buttons
ConvertPDFtoImg(destSource, int.Parse(tb_page.Text) - 1);
bt_signPDFImg.Enabled = false;
bt_signPDF.Enabled = false;
tb_page.Enabled = false;
tb_x.Enabled = false;
tb_y.Enabled = false;
tb_sigWidth.Enabled = false;
tb_sigHeight.Enabled = false;
sb_x.Enabled = false;
sb_y.Enabled = false;
bt_previousPage.Visible = false;
bt_nextPage.Visible = false;
pb_pdfView.Enabled = false;
pb_signPrev.Visible = false;
// Clear source
source = "";
}
// Show the message
MessageBox.Show("PDF file signed and saved in: \n" + destSource);
// Clear the device screen
driverInterface.UploadPromoScreen("Custom.png", 1, DisplayOrientation.DEG_0, 10);
}
#endregion
#region -----------------------------Methods For Certificate--------------------------------------------
// Get the certificate path
private void bt_setCert_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "PFX Files|*.pfx";
openFileDialog.Title = "Select a PFX File";
openFileDialog.ShowDialog();
if (openFileDialog.FileName != "")
{
certPath = openFileDialog.FileName;
}
}
#endregion
#region -----------------------------Methods For License------------------------------------------------
private void bt_license_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "XML Files|*.xml";
openFileDialog.Title = "Select a License File";
openFileDialog.ShowDialog();
if (openFileDialog.FileName != "")
{
Error r = driverInterface.LoadLicense(openFileDialog.FileName);
if (r != Error.SUCCESS)
{
ShowErrorMessage(r);
}
else
{
licensePath = openFileDialog.FileName;
bt_license.Visible = false;
lb_license.Text = Char.ConvertFromUtf32(0x2714) + Char.ConvertFromUtf32(0xFE0F);
lb_license.ForeColor = Color.Green;
}
}
}
#endregion
#region -----------------------------Methods For PDF Page-----------------------------------------------
// Limit the value of the text box page
private void tb_page_TextChanged(object sender, EventArgs e)
{
// Check the value of the text box
if (string.IsNullOrEmpty(tb_page.Text) || !int.TryParse(tb_page.Text, out _))
{
tb_page.Text = "1";
}
else if (int.Parse(tb_page.Text) > pages)
{
tb_page.Text = pages.ToString();
}
else if (int.Parse(tb_page.Text) < 1)
{
tb_page.Text = "1";
}
}
// Button to go to the previous page
private void bt_previousPage_Click(object sender, EventArgs e)
{
int currentPage = int.Parse(tb_page.Text);
if (currentPage > 1)
{
tb_page.Text = (currentPage - 1).ToString();
}
if (currentPage - 1 == 1)
{
bt_previousPage.Visible = false;
bt_nextPage.Visible = true;
}
// Focus the Sign PDF button
bt_signPDFImg.Focus();
// Update the img
ConvertPDFtoImg(source, currentPage - 2);
}
// Button to go to the next page
private void bt_nextPage_Click(object sender, EventArgs e)
{
int currentPage = int.Parse(tb_page.Text);
if (currentPage < pages)
{
tb_page.Text = (currentPage + 1).ToString();
}
if (currentPage + 1 == pages)
{
bt_nextPage.Visible = false;
bt_previousPage.Visible = true;
}
// Focus the Sign PDF button
bt_signPDFImg.Focus();
// Update the img
ConvertPDFtoImg(source, currentPage);
}
#endregion
#region -----------------------------Methods For Sign Coordnates----------------------------------------
// tb x adujstment
private void tb_x_TextChanged(object sender, EventArgs e)
{
// Check the value of the text box
if (string.IsNullOrEmpty(tb_x.Text) || !int.TryParse(tb_x.Text, out _))
{
tb_x.Text = "0";
}
else if (int.Parse(tb_x.Text) > ((int)Math.Round(float.Parse(tb_a4x.Text)) - (int)Math.Round(float.Parse(tb_sigWidth.Text))))
{
tb_x.Text = Convert.ToString((int)Math.Round(float.Parse(tb_a4x.Text)) - (int)Math.Round(float.Parse(tb_sigWidth.Text)));