FillDigitalSignatureControl.xaml.cs 20 KB

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