FillDigitalSignatureControl.xaml.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644
  1. using ComPDFKit.DigitalSign;
  2. using ComPDFKit.Import;
  3. using ComPDFKit.PDFAnnotation;
  4. using ComPDFKit.PDFAnnotation.Form;
  5. using ComPDFKit.PDFDocument;
  6. using ComPDFKit.PDFPage;
  7. using Compdfkit_Tools.Helper;
  8. using System;
  9. using System.Collections.Generic;
  10. using System.Drawing;
  11. using System.Drawing.Imaging;
  12. using System.IO;
  13. using System.Reflection;
  14. using System.Runtime.Remoting.Messaging;
  15. using System.Text;
  16. using System.Windows;
  17. using System.Windows.Controls;
  18. using System.Windows.Controls.Primitives;
  19. using System.Windows.Ink;
  20. using System.Windows.Input;
  21. using System.Windows.Media;
  22. using System.Windows.Media.Imaging;
  23. using static System.Windows.Forms.VisualStyles.VisualStyleElement;
  24. using Color = System.Drawing.Color;
  25. using Pen = System.Windows.Media.Pen;
  26. using PixelFormat = System.Windows.Media.PixelFormat;
  27. using Point = System.Windows.Point;
  28. using Window = System.Windows.Window;
  29. namespace Compdfkit_Tools.PDFControl
  30. {
  31. /// <summary>
  32. /// Interaction logic for CPDFSignControl.xaml
  33. /// </summary>
  34. public partial class FillDigitalSignatureControl : UserControl
  35. {
  36. private readonly string logoPath = "Logo_opa40.png";
  37. private string imagePath = string.Empty;
  38. private string Text = string.Empty;
  39. private Dictionary<string, Border> TabDict { get; set; }
  40. private CPDFSignatureConfig tempSignatureConfig = new CPDFSignatureConfig();
  41. private CPDFSignatureCertificate signatureCertificate;
  42. public CPDFDocument Document;
  43. private string signatureName = string.Empty;
  44. private string location = string.Empty;
  45. private string reason = string.Empty;
  46. private float[] textColor = new float[] { 0, 0, 0 };
  47. private string _signaturePath = string.Empty;
  48. public string SignaturePath
  49. {
  50. get => _signaturePath;
  51. set
  52. {
  53. _signaturePath = value;
  54. }
  55. }
  56. private string _password = string.Empty;
  57. public string Password
  58. {
  59. get => _password;
  60. set
  61. {
  62. _password = value;
  63. signatureCertificate = CPDFPKCS12CertHelper.GetCertificateWithPKCS12Path(SignaturePath, Password);
  64. signatureName = DictionaryValueConverter.GetGrantorFromDictionary(signatureCertificate.SubjectDict);
  65. tempSignatureConfig.Text = signatureName;
  66. InitTempSignature();
  67. }
  68. }
  69. private void InitTempSignature()
  70. {
  71. NameChk.IsChecked = true;
  72. DateChk.IsChecked = true;
  73. LogoChk.IsChecked = true;
  74. TabChk.IsChecked = true;
  75. SetProperty();
  76. CreateTempSignature();
  77. KeyboardInPutTextBox.Text = signatureName;
  78. }
  79. public CPDFSignatureWidget signatureWidget { get; set; }
  80. public event EventHandler<string> AfterFillSignature;
  81. public FillDigitalSignatureControl()
  82. {
  83. InitializeComponent();
  84. TabDict = new Dictionary<string, Border>
  85. {
  86. ["Keyboard"] = KeyboardBorder,
  87. ["Trackpad"] = TrackpadBorder,
  88. ["Image"] = ImageBorder,
  89. ["None"] = NoneBorder
  90. };
  91. SetCheckedTab("Keyboard");
  92. ReasonCmb.SelectedIndex = 0;
  93. }
  94. private void CreateTempSignature()
  95. {
  96. CPDFDocument tempDocument = CPDFDocument.CreateDocument();
  97. tempDocument.InsertPage(0, 200, 200, string.Empty);
  98. CPDFPage page = tempDocument.PageAtIndex(0);
  99. CPDFSignatureWidget signatureWidget = page.CreateWidget(C_WIDGET_TYPE.WIDGET_SIGNATUREFIELDS) as CPDFSignatureWidget;
  100. signatureWidget.SetRect(new CRect(0, 100, 300, 0));
  101. tempSignatureConfig.IsDrawLogo = (bool)LogoChk.IsChecked;
  102. if (tempSignatureConfig.IsDrawLogo)
  103. {
  104. tempSignatureConfig.LogoBitmap = new Bitmap(logoPath);
  105. }
  106. tempSignatureConfig.Content = Text;
  107. tempSignatureConfig.TextColor = textColor;
  108. tempSignatureConfig.ContentColor = new float[] { 0, 0, 0 };
  109. signatureWidget.UpdataApWithSignature(tempSignatureConfig);
  110. byte[] signatureBitmapBytes = GetTempSignatureImage(signatureWidget, out int width, out int height);
  111. signatureWidget.ReleaseAnnot();
  112. if (signatureBitmapBytes.Length > 0)
  113. {
  114. PixelFormat fmt = PixelFormats.Bgra32;
  115. BitmapSource bps = BitmapSource.Create(width, height, 96, 96, fmt, null, signatureBitmapBytes, (width * fmt.BitsPerPixel + 7) / 8);
  116. imageControl.Source = bps;
  117. }
  118. else
  119. {
  120. imageControl.Source = null;
  121. }
  122. }
  123. public static byte[] GetTempSignatureImage(CPDFSignatureWidget signatureWidget, out int width, out int height)
  124. {
  125. CRect rect = signatureWidget.GetRect();
  126. var flags = BindingFlags.NonPublic | BindingFlags.Static;
  127. var dpiProperty = typeof(SystemParameters).GetProperty("Dpi", flags);
  128. int dpi = (int)dpiProperty.GetValue(null, null);
  129. width = (int)(rect.width() * dpi / 72D * 2);
  130. height = (int)(rect.height() * dpi / 72D * 2);
  131. byte[] imageData = new byte[width * height * 4];
  132. signatureWidget.RenderAnnot(width, height, imageData, CPDFAppearanceType.Normal);
  133. return imageData;
  134. }
  135. private void TextAlignBtn_Click(object sender, RoutedEventArgs e)
  136. {
  137. ToggleButton checkBtn = sender as ToggleButton;
  138. if (checkBtn == null)
  139. {
  140. return;
  141. }
  142. checkBtn.IsChecked = true;
  143. if (checkBtn != TextAlignLeftBtn)
  144. {
  145. tempSignatureConfig.IsContentAlignLeft = true;
  146. TextAlignLeftBtn.IsChecked = false;
  147. }
  148. if (checkBtn != TextAlignRightBtn)
  149. {
  150. tempSignatureConfig.IsContentAlignLeft = false;
  151. TextAlignRightBtn.IsChecked = false;
  152. }
  153. CreateTempSignature();
  154. }
  155. private void Border_MouseDown(object sender, MouseButtonEventArgs e)
  156. {
  157. Border clickBorder = sender as Border;
  158. if (clickBorder == null || clickBorder.Tag == null)
  159. {
  160. return;
  161. }
  162. SetCheckedTab(clickBorder.Tag.ToString());
  163. ImagePickPanel.Visibility = Visibility.Hidden;
  164. if (clickBorder == NoneBorder)
  165. {
  166. tempSignatureConfig.IsDrawOnlyContent = true;
  167. }
  168. else
  169. {
  170. tempSignatureConfig.IsDrawOnlyContent = false;
  171. if (clickBorder == KeyboardBorder)
  172. {
  173. tempSignatureConfig.Text = signatureName;
  174. tempSignatureConfig.ImageBitmap = null;
  175. KeyboardPopup.Visibility = Visibility.Visible;
  176. }
  177. else
  178. {
  179. tempSignatureConfig.Text = string.Empty;
  180. if (clickBorder == TrackpadBorder)
  181. {
  182. CanvaDrawPopup.Visibility = Visibility.Visible;
  183. }
  184. else if (clickBorder == ImageBorder)
  185. {
  186. ImagePickPanel.Visibility = Visibility.Visible;
  187. if (!string.IsNullOrEmpty(imagePath))
  188. {
  189. tempSignatureConfig.ImageBitmap = new Bitmap(imagePath);
  190. }
  191. }
  192. }
  193. }
  194. SetProperty();
  195. CreateTempSignature();
  196. }
  197. private void SetCheckedTab(string tab)
  198. {
  199. if (TabDict != null && TabDict.ContainsKey(tab))
  200. {
  201. foreach (string key in TabDict.Keys)
  202. {
  203. Border checkBorder = TabDict[key];
  204. if (checkBorder == null)
  205. {
  206. continue;
  207. }
  208. checkBorder.BorderThickness = new Thickness(0);
  209. if (key == tab)
  210. {
  211. checkBorder.BorderThickness = new Thickness(0, 0, 0, 2);
  212. }
  213. }
  214. }
  215. }
  216. private void CanvasPopupClose_Click(object sender, RoutedEventArgs e)
  217. {
  218. CanvaDrawPopup.Visibility = Visibility.Collapsed;
  219. }
  220. private void CanvasClearBtn_Click(object sender, RoutedEventArgs e)
  221. {
  222. DrawInkCanvas.Strokes.Clear();
  223. }
  224. private void CanvasPopupConfirm_Click(object sender, RoutedEventArgs e)
  225. {
  226. tempSignatureConfig.ImageBitmap = GetDrawInk();
  227. CanvaDrawPopup.Visibility = Visibility.Collapsed;
  228. SetProperty();
  229. CreateTempSignature();
  230. }
  231. public Bitmap GetDrawInk()
  232. {
  233. if (DrawInkCanvas != null && DrawInkCanvas.Strokes != null && DrawInkCanvas.Strokes.Count > 0)
  234. {
  235. Rect bound = DrawInkCanvas.Strokes.GetBounds();
  236. DrawingVisual drawVisual = new DrawingVisual();
  237. DrawingContext drawContext = drawVisual.RenderOpen();
  238. foreach (Stroke drawStroke in DrawInkCanvas.Strokes)
  239. {
  240. Pen drawPen = new Pen(new SolidColorBrush(drawStroke.DrawingAttributes.Color), drawStroke.DrawingAttributes.Width);
  241. PathGeometry drawPath = new PathGeometry();
  242. PathFigureCollection Figures = new PathFigureCollection();
  243. PathFigure AddFigure = new PathFigure();
  244. Figures.Add(AddFigure);
  245. drawPath.Figures = Figures;
  246. if (drawStroke.StylusPoints.Count > 1)
  247. {
  248. StylusPoint startPoint = drawStroke.StylusPoints[0];
  249. AddFigure.StartPoint = new Point(startPoint.X - bound.X, startPoint.Y - bound.Y);
  250. for (int i = 1; i < drawStroke.StylusPoints.Count; i++)
  251. {
  252. StylusPoint drawPoint = drawStroke.StylusPoints[i];
  253. Point offsetPoint = new Point(drawPoint.X - bound.X, drawPoint.Y - bound.Y);
  254. LineSegment drawSegment = new LineSegment();
  255. drawSegment.Point = offsetPoint;
  256. AddFigure.Segments.Add(drawSegment);
  257. }
  258. }
  259. if (AddFigure.Segments.Count > 0)
  260. {
  261. drawContext.DrawGeometry(null, drawPen, drawPath);
  262. }
  263. }
  264. drawContext.Close();
  265. RenderTargetBitmap renderBitmap = new RenderTargetBitmap((int)bound.Width, (int)bound.Height, 96, 96, PixelFormats.Pbgra32);
  266. renderBitmap.Render(drawVisual);
  267. BitmapFrame newFrame = BitmapFrame.Create(renderBitmap);
  268. PngBitmapEncoder pngEncoder = new PngBitmapEncoder();
  269. pngEncoder.Frames.Add(newFrame);
  270. using (MemoryStream newStream = new MemoryStream())
  271. {
  272. pngEncoder.Save(newStream);
  273. return new Bitmap(newStream);
  274. }
  275. }
  276. else
  277. {
  278. return null;
  279. }
  280. }
  281. private void SetProperty()
  282. {
  283. Text = string.Empty;
  284. if ((bool)NameChk.IsChecked)
  285. {
  286. if ((bool)TabChk.IsChecked)
  287. {
  288. Text += "Name: ";
  289. }
  290. Text += DictionaryValueConverter.GetGrantorFromDictionary(signatureCertificate.SubjectDict) + "\n";
  291. }
  292. if ((bool)DateChk.IsChecked)
  293. {
  294. if ((bool)TabChk.IsChecked)
  295. {
  296. Text += "Date: ";
  297. }
  298. DateTime currentDateTime = DateTime.Now;
  299. string customFormat = "yyyy.MM.dd HH:mm:ss";
  300. string formattedDateTime = currentDateTime.ToString(customFormat);
  301. Text += formattedDateTime + "\n";
  302. }
  303. if ((bool)LogoChk.IsChecked)
  304. {
  305. tempSignatureConfig.IsDrawLogo = true;
  306. }
  307. else
  308. {
  309. tempSignatureConfig.IsDrawLogo = false;
  310. }
  311. if ((bool)ReasonChk.IsChecked)
  312. {
  313. if ((bool)TabChk.IsChecked)
  314. {
  315. Text += "Reason: ";
  316. }
  317. Text += (ReasonCmb.SelectedItem as ComboBoxItem).Content.ToString() + "\n";
  318. }
  319. if ((bool)DistinguishableNameChk.IsChecked)
  320. {
  321. if ((bool)TabChk.IsChecked)
  322. {
  323. Text += "DN: ";
  324. }
  325. var keyOrder = new List<string> { "CN", "O", "OU", "emailAddress", "L", "ST", "C" };
  326. var keyMapping = new Dictionary<string, string>
  327. {
  328. { "CN", "cn" },
  329. { "OU", "ou" },
  330. { "O", "o" },
  331. { "L", "l" },
  332. { "ST", "st" },
  333. { "C", "c" },
  334. { "emailAddress", "email" }
  335. };
  336. var stringBuilder = new StringBuilder();
  337. foreach (var originalKey in keyOrder)
  338. {
  339. if (keyMapping.TryGetValue(originalKey, out string newKey) &&
  340. signatureCertificate.SubjectDict.TryGetValue(originalKey, out string value) && !string.IsNullOrEmpty(value))
  341. {
  342. if (stringBuilder.Length > 0)
  343. {
  344. stringBuilder.Append(",");
  345. }
  346. stringBuilder.Append(newKey + "=" + value);
  347. }
  348. }
  349. Text += stringBuilder.ToString()+"\n";
  350. }
  351. if ((bool)ComPDFKitVersionChk.IsChecked)
  352. {
  353. Assembly assembly = Assembly.GetExecutingAssembly();
  354. Version version = assembly.GetName().Version;
  355. if ((bool)TabChk.IsChecked)
  356. {
  357. Text += "ComPDFKit Version: ";
  358. }
  359. Text += version.Major.ToString() + "." + version.Minor.ToString() + "." + version.Build.ToString() + "." + version.Revision.ToString() + "\n";
  360. }
  361. if ((bool)PositionChk.IsChecked)
  362. {
  363. if ((bool)TabChk.IsChecked)
  364. {
  365. Text += "Position: ";
  366. }
  367. Text += PositionTbx.Text + "\n";
  368. }
  369. }
  370. private void ReasonCheckBox_Click(object sender, RoutedEventArgs e)
  371. {
  372. CheckBox checkItem = sender as CheckBox;
  373. if (checkItem == null)
  374. {
  375. return;
  376. }
  377. ReasonPanel.Visibility = checkItem.IsChecked == true ? Visibility.Visible : Visibility.Collapsed;
  378. }
  379. private void BrowseTxt_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
  380. {
  381. string filter = "Image files (*.jpg, *.jpeg, *.png, *.bmp)|*.jpg;*.jpeg;*.png;*.bmp";
  382. string pngPath = CommonHelper.GetExistedPathOrEmpty(filter);
  383. if (!string.IsNullOrEmpty(pngPath))
  384. {
  385. imagePath = pngPath;
  386. try
  387. {
  388. tempSignatureConfig.ImageBitmap = new Bitmap(imagePath);
  389. }
  390. catch (Exception exception)
  391. {
  392. MessageBox.Show("The image is invalid.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
  393. return;
  394. }
  395. SetProperty();
  396. CreateTempSignature();
  397. }
  398. }
  399. private void ClearTxt_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
  400. {
  401. imagePath = string.Empty;
  402. tempSignatureConfig.ImageBitmap = null;
  403. SetProperty();
  404. CreateTempSignature();
  405. }
  406. private void NameChk_Click(object sender, RoutedEventArgs e)
  407. {
  408. SetProperty();
  409. CreateTempSignature();
  410. }
  411. private void DateChk_Click(object sender, RoutedEventArgs e)
  412. {
  413. SetProperty();
  414. CreateTempSignature();
  415. }
  416. private void LogoChk_Click(object sender, RoutedEventArgs e)
  417. {
  418. SetProperty();
  419. CreateTempSignature();
  420. }
  421. private void ReasonChk_Click(object sender, RoutedEventArgs e)
  422. {
  423. if (!(bool)ReasonChk.IsChecked)
  424. {
  425. Reasonstp.Visibility = Visibility.Collapsed;
  426. }
  427. else
  428. {
  429. Reasonstp.Visibility = Visibility.Visible;
  430. }
  431. SetProperty();
  432. CreateTempSignature();
  433. }
  434. private void DistinguishableNameChk_Click(object sender, RoutedEventArgs e)
  435. {
  436. SetProperty();
  437. CreateTempSignature();
  438. }
  439. private void PositionChk_Click(object sender, RoutedEventArgs e)
  440. {
  441. if (!(bool)PositionChk.IsChecked)
  442. {
  443. PositionStp.Visibility = Visibility.Collapsed;
  444. }
  445. else
  446. {
  447. PositionStp.Visibility = Visibility.Visible;
  448. }
  449. SetProperty();
  450. CreateTempSignature();
  451. }
  452. private void TabChk_Click(object sender, RoutedEventArgs e)
  453. {
  454. SetProperty();
  455. CreateTempSignature();
  456. }
  457. private void ReasonCmb_SelectionChanged(object sender, SelectionChangedEventArgs e)
  458. {
  459. SetProperty();
  460. CreateTempSignature();
  461. }
  462. private void ComPDFKitVersionChk_Click(object sender, RoutedEventArgs e)
  463. {
  464. SetProperty();
  465. CreateTempSignature();
  466. }
  467. private void PositionTbx_TextChanged(object sender, TextChangedEventArgs e)
  468. {
  469. if (!(bool)PositionChk.IsChecked)
  470. {
  471. PositionStp.Visibility = Visibility.Collapsed;
  472. }
  473. else
  474. {
  475. PositionStp.Visibility = Visibility.Visible;
  476. }
  477. SetProperty();
  478. CreateTempSignature();
  479. }
  480. private void ContinueBtn_Click(object sender, RoutedEventArgs e)
  481. {
  482. string filePath = CommonHelper.GetGeneratePathOrEmpty("PDF files (*.pdf)|*.pdf", Document.FileName + "_Signed.pdf");
  483. if (string.IsNullOrEmpty(filePath))
  484. {
  485. return;
  486. }
  487. if (filePath.ToLower() == Document.FilePath.ToLower())
  488. {
  489. MessageBox.Show("Do not use the new file name that is the same as the current file name.");
  490. return;
  491. }
  492. if ((bool)ReasonChk.IsChecked)
  493. {
  494. reason = (ReasonCmb?.SelectedItem as ComboBoxItem)?.Content?.ToString();
  495. }
  496. else
  497. {
  498. reason = string.Empty;
  499. }
  500. if ((bool)PositionChk.IsChecked)
  501. {
  502. location = PositionTbx.Text;
  503. }
  504. else
  505. {
  506. location = string.Empty;
  507. }
  508. signatureWidget.UpdataApWithSignature(tempSignatureConfig);
  509. if (Document.WriteSignatureToFilePath(signatureWidget, filePath, SignaturePath, Password, location, reason, CPDFSignaturePermissions.CPDFSignaturePermissionsNone))
  510. {
  511. signatureCertificate.AddToTrustedCertificates();
  512. AfterFillSignature?.Invoke(sender, filePath);
  513. }
  514. CloseWindow(sender);
  515. }
  516. private void CancelBtn_Click(object sender, RoutedEventArgs e)
  517. {
  518. CloseWindow(sender);
  519. }
  520. private void CloseWindow(object sender)
  521. {
  522. Window parentWindow = Window.GetWindow(sender as DependencyObject);
  523. parentWindow?.Close();
  524. }
  525. private void TextColorPickerControl_Loaded(object sender, RoutedEventArgs e)
  526. {
  527. TextColorPickerControl.SetIsChecked(0);
  528. TextColorPickerControl.Brush = new SolidColorBrush(Colors.Black);
  529. }
  530. private void TextColorPickerControl_ColorChanged(object sender, EventArgs e)
  531. {
  532. KeyboardInPutTextBox.Foreground = TextColorPickerControl.Brush;
  533. }
  534. private void KeyboardCancel_Click(object sender, RoutedEventArgs e)
  535. {
  536. KeyboardPopup.Visibility = Visibility.Collapsed;
  537. }
  538. private void KeyboardClear_Click(object sender, RoutedEventArgs e)
  539. {
  540. KeyboardInPutTextBox.Text = string.Empty;
  541. }
  542. private void KeyboardSave_Click(object sender, RoutedEventArgs e)
  543. {
  544. signatureName = KeyboardInPutTextBox.Text;
  545. tempSignatureConfig.Text = signatureName;
  546. SolidColorBrush solidColorBrush = TextColorPickerControl.Brush as SolidColorBrush;
  547. float red = solidColorBrush.Color.R;
  548. float green = solidColorBrush.Color.G;
  549. float blue = solidColorBrush.Color.B;
  550. textColor = new[] { red / 255, green / 255, blue / 255 };
  551. KeyboardPopup.Visibility = Visibility.Collapsed;
  552. SetProperty();
  553. CreateTempSignature();
  554. }
  555. private void KeyboardPopupClose_Click(object sender, RoutedEventArgs e)
  556. {
  557. KeyboardPopup.Visibility = Visibility.Collapsed;
  558. }
  559. }
  560. }