FillDigitalSignatureControl.xaml.cs 21 KB

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