FillDigitalSignatureControl.xaml.cs 18 KB

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