SignatureCreateDialogViewModel.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614
  1. using ComPDFKitViewer.AnnotEvent;
  2. using ComPDFKitViewer.PdfViewer;
  3. using Microsoft.Win32;
  4. using PDF_Master.Model;
  5. using Prism.Commands;
  6. using Prism.Mvvm;
  7. using Prism.Regions;
  8. using Prism.Services.Dialogs;
  9. using System;
  10. using System.Collections.Generic;
  11. using System.Collections.ObjectModel;
  12. using System.Drawing;
  13. using System.Drawing.Imaging;
  14. using System.Globalization;
  15. using System.IO;
  16. using System.Linq;
  17. using System.Text;
  18. using System.Threading.Tasks;
  19. using System.Windows;
  20. using System.Windows.Ink;
  21. using System.Windows.Media;
  22. using System.Windows.Media.Imaging;
  23. namespace PDF_Master.ViewModels.PropertyPanel.AnnotPanel
  24. {
  25. class SignatureCreateDialogViewModel : BindableBase, IDialogAware
  26. {
  27. /// <summary>
  28. /// 非绘制时展示的画笔光标
  29. /// </summary>
  30. private const double StrokeWidth= 3;
  31. private const double StrokeHigh = 3;
  32. public string Title => "";
  33. private CPDFViewer PDFViewer;
  34. public event Action<IDialogResult> RequestClose;
  35. public DelegateCommand CancelCommand { get; set; }
  36. public DelegateCommand CreateCommnad { get; set; }
  37. public DelegateCommand UpdataDrawingStrokesCommnad { get; set; }
  38. public DelegateCommand<object> CheckedCommnad { get; set; }
  39. public DelegateCommand OpenImageCommnad { get; set; }
  40. public DelegateCommand ClearTextCommnad { get; set; }
  41. public DelegateCommand ClearInkCanvasCommnad { get; set; }
  42. public ObservableCollection<string> FontNameList { get; set; }
  43. public ObservableCollection<string> ThicknessList { get; set; }
  44. private int fontNameIndex = 0;
  45. public int FontNameIndex
  46. {
  47. get { return fontNameIndex; }
  48. set
  49. {
  50. SetProperty(ref fontNameIndex, value);
  51. }
  52. }
  53. private int radioButtonIndex = 1;
  54. public int RadioButtonIndex
  55. {
  56. get { return radioButtonIndex; }
  57. set
  58. {
  59. SetProperty(ref radioButtonIndex, value);
  60. }
  61. }
  62. private int tabItemIndex;
  63. public int TabItemIndex
  64. {
  65. get { return tabItemIndex; }
  66. set
  67. {
  68. SetProperty(ref tabItemIndex, value);
  69. }
  70. }
  71. private string inputText = "";
  72. public string InputText
  73. {
  74. get { return inputText; }
  75. set
  76. {
  77. SetProperty(ref inputText, value);
  78. }
  79. }
  80. private Visibility showTextButton = Visibility.Collapsed;
  81. public Visibility ShowTextButton
  82. {
  83. get { return showTextButton; }
  84. set
  85. {
  86. SetProperty(ref showTextButton, value);
  87. }
  88. }
  89. private Visibility showImageButton = Visibility.Visible;
  90. public Visibility ShowImageButton
  91. {
  92. get { return showImageButton; }
  93. set
  94. {
  95. SetProperty(ref showImageButton, value);
  96. }
  97. }
  98. private BitmapSource imagePreviewSource;
  99. public BitmapSource ImagePreviewSource
  100. {
  101. get { return imagePreviewSource; }
  102. set
  103. {
  104. SetProperty(ref imagePreviewSource, value);
  105. }
  106. }
  107. private bool issRemoveBackground;
  108. public bool IsRemoveBackground
  109. {
  110. get { return issRemoveBackground; }
  111. set
  112. {
  113. SetProperty(ref issRemoveBackground, value);
  114. if (issRemoveBackground)
  115. {
  116. if (IsNewFile)
  117. {
  118. removeBackgroundImagePreviewSource = ToBitmapImage(KnockOutGzf());
  119. }
  120. ImagePreviewSource = removeBackgroundImagePreviewSource;
  121. }
  122. else
  123. {
  124. ImagePreviewSource = originalimagePreviewSource;
  125. }
  126. }
  127. }
  128. private DrawingAttributes drawingAttributes;
  129. public DrawingAttributes DrawingAttributeObject
  130. {
  131. get { return drawingAttributes; }
  132. set
  133. {
  134. SetProperty(ref drawingAttributes, value);
  135. }
  136. }
  137. private StrokeCollection strokes;
  138. public StrokeCollection StrokesObject
  139. {
  140. get { return strokes; }
  141. set
  142. {
  143. SetProperty(ref strokes, value);
  144. }
  145. }
  146. private bool isMouseDown = false;
  147. public bool IsMouseDown
  148. {
  149. get { return isMouseDown; }
  150. set
  151. {
  152. SetProperty(ref isMouseDown, value);
  153. }
  154. }
  155. private Visibility showPlanGrid = Visibility.Visible;
  156. public Visibility ShowPlanGrid
  157. {
  158. get { return showPlanGrid; }
  159. set
  160. {
  161. SetProperty(ref showPlanGrid, value);
  162. }
  163. }
  164. private int imageRadioButtonIndex = 1;
  165. public int ImageRadioButtonIndex
  166. {
  167. get { return imageRadioButtonIndex; }
  168. set
  169. {
  170. SetProperty(ref imageRadioButtonIndex, value);
  171. switch (imageRadioButtonIndex)
  172. {
  173. case 1:
  174. DrawingAttributeObject.Color = System.Windows.Media.Color.FromArgb(0xFF, 0x25, 0x26, 0x29);
  175. break;
  176. case 2:
  177. DrawingAttributeObject.Color = System.Windows.Media.Color.FromArgb(0xFF, 0xF3, 0x46, 0x5B);
  178. break;
  179. case 3:
  180. DrawingAttributeObject.Color = System.Windows.Media.Color.FromArgb(0xFF, 0x27, 0x3C, 0x62);
  181. break;
  182. case 4:
  183. DrawingAttributeObject.Color = System.Windows.Media.Color.FromArgb(0xFF, 0x94, 0x98, 0x9C);
  184. break;
  185. default:
  186. break;
  187. }
  188. UpDataToStrokesObject();
  189. }
  190. }
  191. private int thicknessListIndex = 1;
  192. public int ThicknessListIndex
  193. {
  194. get { return thicknessListIndex; }
  195. set
  196. {
  197. SetProperty(ref thicknessListIndex, value);
  198. if (thicknessListIndex >= 0)
  199. {
  200. DrawingAttributeObject.Width = DrawingAttributeObject.Height = Convert.ToDouble(ThicknessList[thicknessListIndex].Substring(0, 3));
  201. UpDataToStrokesObject();
  202. }
  203. }
  204. }
  205. public string SaveToPath { get; private set; }
  206. public string RemoveBackgroundSaveToPath { get; private set; }
  207. public string DrawingSaveToPath { get; private set; }
  208. /// <summary>
  209. /// 用于判断是否更换了文件,更换了文件则需要重新计算去背功能
  210. /// </summary>
  211. private bool IsNewFile = false;
  212. //去背图片和原图的图片数据
  213. private BitmapSource originalimagePreviewSource = null;
  214. private BitmapSource removeBackgroundImagePreviewSource = null;
  215. public SignatureCreateDialogViewModel()
  216. {
  217. DrawingAttributeObject = new DrawingAttributes();
  218. StrokesObject = new StrokeCollection();
  219. FontNameList = new ObservableCollection<string>();
  220. ThicknessList = new ObservableCollection<string>() {"1.0pt", "2.0pt", "4.0pt", "6.0pt", "8.0pt" };//改了这里记得去改ThicknessListIndex的Set方法里面的取值
  221. CancelCommand = new DelegateCommand(Cancel);
  222. CreateCommnad = new DelegateCommand(Create);
  223. UpdataDrawingStrokesCommnad = new DelegateCommand(UpdataDrawingStrokes);
  224. CheckedCommnad = new DelegateCommand<object>(Checked);
  225. OpenImageCommnad = new DelegateCommand(OpenImage);
  226. ClearTextCommnad = new DelegateCommand(ClearText);
  227. ClearInkCanvasCommnad = new DelegateCommand(ClearInkCanvas);
  228. DrawingAttributeObject.Color = Colors.Black;
  229. DrawingAttributeObject.Width = StrokeWidth;
  230. DrawingAttributeObject.Height = StrokeHigh;
  231. WeakEventManager<StrokeCollection, StrokeCollectionChangedEventArgs>.AddHandler(StrokesObject, "StrokesChanged", StrokesObject_StrokesChanged);
  232. InitFontNameList();
  233. }
  234. private void StrokesObject_StrokesChanged(object sender, StrokeCollectionChangedEventArgs e)
  235. {
  236. DrawingAttributeObject.Width = StrokeWidth;
  237. DrawingAttributeObject.Height = StrokeHigh;
  238. }
  239. private void InitFontNameList()
  240. {
  241. System.Drawing.Text.InstalledFontCollection objFont = new System.Drawing.Text.InstalledFontCollection();
  242. foreach (var item in objFont.Families)
  243. {
  244. FontNameList.Add(item.Name);
  245. }
  246. }
  247. private void Checked(object index)
  248. {
  249. RadioButtonIndex = Convert.ToInt32(index);
  250. }
  251. public void UpDataImageRadioButtonIndex(int Index)
  252. {
  253. ImageRadioButtonIndex = Index;
  254. }
  255. public void UpDataRadioButtonIndex(int Index)
  256. {
  257. RadioButtonIndex = Index;
  258. }
  259. private void UpDataToStrokesObject()
  260. {
  261. foreach (var item in StrokesObject)
  262. {
  263. item.DrawingAttributes = DrawingAttributeObject.Clone();
  264. }
  265. DrawingAttributeObject.Width = DrawingAttributeObject.Height = 3;
  266. }
  267. private void ClearText()
  268. {
  269. InputText = "";
  270. }
  271. private void OpenImage()
  272. {
  273. OpenFileDialog openFile = new OpenFileDialog();
  274. openFile.Filter = "All Image Files(*.bmp;*.gif;*.jpeg;*.jpg;*.png;*.tiff)|*.bmp;*.gif;*.jpeg;*.jpg;*.png;*.tiff|(*.bmp)|*.bmp|" +
  275. "(*.gif)|*.gif|" +
  276. "(*.jpeg)|*.jpeg|" +
  277. "(*.jpg)|*.jpg|" +
  278. "(*.png)|*.png|" +
  279. "(*.tiff)|*.tiff";
  280. if (openFile.ShowDialog() == false)
  281. {
  282. return;
  283. }
  284. string path = App.CachePath.CustomStampPath;
  285. string name = Guid.NewGuid().ToString();
  286. if (!string.IsNullOrEmpty(path))
  287. {
  288. BitmapImage image = new BitmapImage(new Uri(openFile.FileName));
  289. double scale = Math.Min((double)600 / image.PixelWidth, (double)600 / image.PixelHeight);
  290. scale = Math.Min(scale, 1);
  291. string ext = Path.GetExtension(openFile.FileName);
  292. if (ext.ToUpper() == ".PNG")
  293. {
  294. BitmapEncoder encoder = new PngBitmapEncoder();
  295. var targetBitmap = new TransformedBitmap(image, new ScaleTransform(scale, scale));
  296. encoder.Frames.Add(BitmapFrame.Create(targetBitmap));
  297. path = System.IO.Path.Combine(path, name);
  298. using (FileStream stream = new FileStream(path, FileMode.Create))
  299. {
  300. encoder.Save(stream);
  301. }
  302. if (!string.IsNullOrEmpty(SaveToPath))
  303. {
  304. App.CachePath.AddToDeleteFiles(SaveToPath);
  305. }
  306. IsNewFile = true;
  307. SaveToPath = path;
  308. ImagePreviewSource = originalimagePreviewSource = targetBitmap;
  309. ShowImageButton = Visibility.Collapsed;
  310. }
  311. else
  312. {
  313. BitmapEncoder encoder = new JpegBitmapEncoder();
  314. TransformedBitmap targetBitmap = new TransformedBitmap(image, new ScaleTransform(scale, scale));
  315. encoder.Frames.Add(BitmapFrame.Create(targetBitmap));
  316. path = System.IO.Path.Combine(path, name);
  317. using (FileStream stream = new FileStream(path, FileMode.Create))
  318. {
  319. encoder.Save(stream);
  320. }
  321. if (!string.IsNullOrEmpty(SaveToPath))
  322. {
  323. App.CachePath.AddToDeleteFiles(SaveToPath);
  324. }
  325. IsNewFile = true;
  326. SaveToPath = path;
  327. ImagePreviewSource = originalimagePreviewSource = targetBitmap;
  328. ShowImageButton = Visibility.Collapsed;
  329. }
  330. }
  331. else
  332. {
  333. SaveToPath = "";
  334. }
  335. }
  336. private void ClearInkCanvas()
  337. {
  338. StrokesObject.Clear();
  339. }
  340. /// <summary>
  341. /// 去除白底
  342. /// </summary>
  343. private Bitmap KnockOutGzf()
  344. {
  345. System.Drawing.Image image = System.Drawing.Image.FromFile(SaveToPath);
  346. Bitmap bitmapProxy = new Bitmap(image);
  347. image.Dispose();
  348. for (int i = 0; i < bitmapProxy.Width; i++)
  349. {
  350. for (int j = 0; j < bitmapProxy.Height; j++)
  351. {
  352. System.Drawing.Color c = bitmapProxy.GetPixel(i, j);
  353. if (!(c.R < 240 || c.G < 240 || c.B < 240))
  354. {
  355. bitmapProxy.SetPixel(i, j, System.Drawing.Color.Transparent);
  356. }
  357. }
  358. }
  359. return bitmapProxy;
  360. }
  361. /// <summary>
  362. /// 将 Bitmap 转化为 BitmapSource
  363. /// </summary>
  364. /// <param name="bmp"/>要转换的 Bitmap
  365. /// <returns>转换后的 BitmapImage</returns>
  366. private BitmapImage ToBitmapImage(System.Drawing.Bitmap bmp)
  367. {
  368. System.IO.MemoryStream ms = new System.IO.MemoryStream();
  369. bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
  370. BitmapImage image = new BitmapImage();
  371. image.BeginInit();
  372. image.StreamSource = ms;
  373. image.CacheOption = BitmapCacheOption.OnLoad;
  374. image.EndInit();
  375. //编码,缓存到本地
  376. string path = App.CachePath.CustomStampPath;
  377. string name = Guid.NewGuid().ToString();
  378. BitmapEncoder encoder = new PngBitmapEncoder();
  379. encoder.Frames.Add(BitmapFrame.Create(image));
  380. path = System.IO.Path.Combine(path, name);
  381. using (FileStream stream = new FileStream(path, FileMode.Create))
  382. {
  383. encoder.Save(stream);
  384. }
  385. if (!string.IsNullOrEmpty(RemoveBackgroundSaveToPath))
  386. {
  387. App.CachePath.AddToDeleteFiles(RemoveBackgroundSaveToPath);
  388. }
  389. RemoveBackgroundSaveToPath = path;
  390. IsNewFile = false;
  391. return image;
  392. }
  393. /// <summary>
  394. /// 把文字转换成Bitmap
  395. /// </summary>
  396. /// <param name="text"></param>
  397. /// <param name="font"></param>
  398. /// <param name="rect">用于输出的矩形,文字在这个矩形内显示,为空时自动计算</param>
  399. /// <param name="fontcolor">字体颜色</param>
  400. /// <param name="backColor">背景颜色</param>
  401. /// <returns></returns>
  402. private Bitmap TextToBitmap(string text, string FontFamily,double size, Rectangle rect, System.Windows.Media.Brush fontcolor, System.Drawing.Color backColor)
  403. {
  404. FormattedText formatText = new FormattedText(text,
  405. CultureInfo.CurrentCulture,
  406. FlowDirection.LeftToRight,
  407. new Typeface(new System.Windows.Media.FontFamily(FontFamily), FontStyles.Normal, FontWeights.Normal, FontStretches.Normal),
  408. size,
  409. fontcolor, Helper.DpiHelpers.Dpi / 96F);
  410. DrawingVisual drawingVisual = new DrawingVisual();
  411. DrawingContext dc = drawingVisual.RenderOpen();
  412. dc.DrawText(formatText,new System.Windows.Point(2,10));
  413. dc.Close();
  414. Rect x = drawingVisual.ContentBounds;
  415. Rect DrawRect = new Rect(0, 0, x.Width + 2, x.Height +10);
  416. RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap((int)DrawRect.Width+2, (int)DrawRect.Height+10, 96F, 96F, PixelFormats.Pbgra32);
  417. renderTargetBitmap.Render(drawingVisual);
  418. MemoryStream stream = new MemoryStream();
  419. BitmapEncoder encoder = new PngBitmapEncoder();
  420. encoder.Frames.Add(BitmapFrame.Create(renderTargetBitmap));
  421. encoder.Save(stream);
  422. Bitmap bitmap = new Bitmap(stream);
  423. return bitmap;
  424. }
  425. private void Cancel()
  426. {
  427. RequestClose.Invoke(new DialogResult(ButtonResult.Cancel));
  428. }
  429. private void Create()
  430. {
  431. switch (TabItemIndex)
  432. {
  433. case 0:
  434. {
  435. if (string.IsNullOrEmpty(InputText))
  436. {
  437. Cancel();
  438. return;
  439. }
  440. System.Windows.Media.Brush fontcolor = new SolidColorBrush((System.Windows.Media.Color)System.Windows.Media.ColorConverter.ConvertFromString("#252629"));
  441. switch (RadioButtonIndex)
  442. {
  443. case 1:
  444. fontcolor = new SolidColorBrush((System.Windows.Media.Color)System.Windows.Media.ColorConverter.ConvertFromString("#252629"));
  445. break;
  446. case 2:
  447. fontcolor = new SolidColorBrush((System.Windows.Media.Color)System.Windows.Media.ColorConverter.ConvertFromString("#F3465B"));
  448. break;
  449. case 3:
  450. fontcolor = new SolidColorBrush((System.Windows.Media.Color)System.Windows.Media.ColorConverter.ConvertFromString("#273C62"));
  451. break;
  452. case 4:
  453. fontcolor = new SolidColorBrush((System.Windows.Media.Color)System.Windows.Media.ColorConverter.ConvertFromString("#94989C"));
  454. break;
  455. default:
  456. break;
  457. }
  458. Bitmap bmp = TextToBitmap(InputText, FontNameList[fontNameIndex], 20, Rectangle.Empty, fontcolor, System.Drawing.Color.Transparent);
  459. string guid = Guid.NewGuid().ToString();
  460. string path = System.IO.Path.Combine(App.CachePath.SignatureStampPath, guid);
  461. bmp.Save(path, ImageFormat.Png);
  462. SaveToPath = path;
  463. }
  464. break;
  465. case 1:
  466. {
  467. var FreeHandpath = App.CachePath.SignatureFreeHandPath;
  468. string name = Guid.NewGuid().ToString();
  469. FreeHandpath = System.IO.Path.Combine(FreeHandpath, name);
  470. using (System.IO.FileStream stream = new System.IO.FileStream(FreeHandpath, System.IO.FileMode.Create))
  471. {
  472. StrokesObject.Save(stream);
  473. }
  474. StampAnnotArgs stampArgs = new StampAnnotArgs();
  475. List<List<System.Windows.Point>> RawPointList = new List<List<System.Windows.Point>>();
  476. for (int kk = 0; kk < StrokesObject.Count; kk++)
  477. {
  478. List<System.Windows.Point> p = new List<System.Windows.Point>();
  479. RawPointList.Add(p);
  480. for (int gg = 0; gg < StrokesObject[kk].StylusPoints.Count; gg++)
  481. {
  482. var point = StrokesObject[kk].StylusPoints[gg].ToPoint();
  483. if (point.X >= 0 && point.Y >= 0)
  484. RawPointList[kk].Add(point);
  485. }
  486. }
  487. DrawingSaveToPath = FreeHandpath;
  488. stampArgs.SetInkData(RawPointList, drawingAttributes.Width, drawingAttributes.Color);
  489. var writeStamp = stampArgs.GetStampDrawing();
  490. FreeHandpath = App.CachePath.SignatureStampPath;
  491. string thumbnailName = Guid.NewGuid().ToString();
  492. FreeHandpath = System.IO.Path.Combine(FreeHandpath, thumbnailName);
  493. using (FileStream stream5 = new FileStream(FreeHandpath, FileMode.Create))
  494. {
  495. PngBitmapEncoder encoder5 = new PngBitmapEncoder();
  496. encoder5.Frames.Add(BitmapFrame.Create(writeStamp));
  497. encoder5.Save(stream5);
  498. }
  499. SaveToPath = FreeHandpath;
  500. }
  501. break;
  502. case 2:
  503. break;
  504. default:
  505. break;
  506. }
  507. DialogParameters valuePairs = new DialogParameters();
  508. valuePairs.Add(ParameterNames.DataModel, this);
  509. RequestClose.Invoke(new DialogResult(ButtonResult.OK, valuePairs));
  510. }
  511. /// <summary>
  512. /// 绘制时使用的画笔
  513. /// </summary>
  514. private void UpdataDrawingStrokes()
  515. {
  516. DrawingAttributeObject.Width = DrawingAttributeObject.Height = Convert.ToDouble(ThicknessList[thicknessListIndex].Substring(0, 3));
  517. }
  518. public bool CanCloseDialog()
  519. {
  520. return true;
  521. }
  522. public void OnDialogClosed()
  523. {
  524. return;
  525. }
  526. public void OnDialogOpened(IDialogParameters parameters)
  527. {
  528. if (parameters != null)
  529. {
  530. PDFViewer = parameters.GetValue<CPDFViewer>(ParameterNames.PDFViewer);
  531. if (PDFViewer != null)
  532. {
  533. }
  534. }
  535. return;
  536. }
  537. }
  538. }