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. if (ThicknessListIndex >= 0)
  189. {
  190. DrawingAttributeObject.Width = DrawingAttributeObject.Height = Convert.ToDouble(ThicknessList[ThicknessListIndex].Substring(0, 3));
  191. UpDataToStrokesObject();
  192. }
  193. }
  194. }
  195. private int thicknessListIndex = 1;
  196. public int ThicknessListIndex
  197. {
  198. get { return thicknessListIndex; }
  199. set
  200. {
  201. SetProperty(ref thicknessListIndex, value);
  202. if (thicknessListIndex >= 0)
  203. {
  204. DrawingAttributeObject.Width = DrawingAttributeObject.Height = Convert.ToDouble(ThicknessList[thicknessListIndex].Substring(0, 3));
  205. UpDataToStrokesObject();
  206. }
  207. }
  208. }
  209. public string SaveToPath { get; private set; }
  210. public string RemoveBackgroundSaveToPath { get; private set; }
  211. public string DrawingSaveToPath { get; private set; }
  212. /// <summary>
  213. /// 用于判断是否更换了文件,更换了文件则需要重新计算去背功能
  214. /// </summary>
  215. private bool IsNewFile = false;
  216. //去背图片和原图的图片数据
  217. private BitmapSource originalimagePreviewSource = null;
  218. private BitmapSource removeBackgroundImagePreviewSource = null;
  219. public SignatureCreateDialogViewModel()
  220. {
  221. DrawingAttributeObject = new DrawingAttributes();
  222. StrokesObject = new StrokeCollection();
  223. FontNameList = new ObservableCollection<string>();
  224. ThicknessList = new ObservableCollection<string>() { "1.0pt", "2.0pt", "4.0pt", "6.0pt", "8.0pt" };//改了这里记得去改ThicknessListIndex的Set方法里面的取值
  225. CancelCommand = new DelegateCommand(Cancel);
  226. CreateCommnad = new DelegateCommand(Create);
  227. UpdataDrawingStrokesCommnad = new DelegateCommand(UpdataDrawingStrokes);
  228. CheckedCommnad = new DelegateCommand<object>(Checked);
  229. OpenImageCommnad = new DelegateCommand(OpenImage);
  230. ClearTextCommnad = new DelegateCommand(ClearText);
  231. ClearInkCanvasCommnad = new DelegateCommand(ClearInkCanvas);
  232. DrawingAttributeObject.Color = Colors.Black;
  233. DrawingAttributeObject.Width = StrokeWidth;
  234. DrawingAttributeObject.Height = StrokeHigh;
  235. WeakEventManager<StrokeCollection, StrokeCollectionChangedEventArgs>.AddHandler(StrokesObject, "StrokesChanged", StrokesObject_StrokesChanged);
  236. InitFontNameList();
  237. }
  238. private void StrokesObject_StrokesChanged(object sender, StrokeCollectionChangedEventArgs e)
  239. {
  240. DrawingAttributeObject.Width = StrokeWidth;
  241. DrawingAttributeObject.Height = StrokeHigh;
  242. }
  243. private void InitFontNameList()
  244. {
  245. System.Drawing.Text.InstalledFontCollection objFont = new System.Drawing.Text.InstalledFontCollection();
  246. foreach (var item in objFont.Families)
  247. {
  248. FontNameList.Add(item.Name);
  249. }
  250. }
  251. private void Checked(object index)
  252. {
  253. RadioButtonIndex = Convert.ToInt32(index);
  254. }
  255. public void UpDataImageRadioButtonIndex(int Index)
  256. {
  257. ImageRadioButtonIndex = Index;
  258. }
  259. public void UpDataRadioButtonIndex(int Index)
  260. {
  261. RadioButtonIndex = Index;
  262. }
  263. /// <summary>
  264. /// 更新画板所有内容状态
  265. /// </summary>
  266. private void UpDataToStrokesObject()
  267. {
  268. foreach (var item in StrokesObject)
  269. {
  270. item.DrawingAttributes = DrawingAttributeObject.Clone();
  271. }
  272. DrawingAttributeObject.Width = StrokeWidth;
  273. DrawingAttributeObject.Height = StrokeHigh;
  274. }
  275. private void ClearText()
  276. {
  277. InputText = "";
  278. }
  279. private void OpenImage()
  280. {
  281. OpenFileDialog openFile = new OpenFileDialog();
  282. openFile.Filter = "All Image Files(*.bmp;*.gif;*.jpeg;*.jpg;*.png;*.tiff)|*.bmp;*.gif;*.jpeg;*.jpg;*.png;*.tiff|(*.bmp)|*.bmp|" +
  283. "(*.gif)|*.gif|" +
  284. "(*.jpeg)|*.jpeg|" +
  285. "(*.jpg)|*.jpg|" +
  286. "(*.png)|*.png|" +
  287. "(*.tiff)|*.tiff";
  288. if (openFile.ShowDialog() == false)
  289. {
  290. return;
  291. }
  292. string path = App.CachePath.CustomStampPath;
  293. string name = Guid.NewGuid().ToString();
  294. if (!string.IsNullOrEmpty(path))
  295. {
  296. BitmapImage image = new BitmapImage(new Uri(openFile.FileName));
  297. double scale = Math.Min((double)600 / image.PixelWidth, (double)600 / image.PixelHeight);
  298. scale = Math.Min(scale, 1);
  299. BitmapEncoder encoder = new PngBitmapEncoder();
  300. var targetBitmap = new TransformedBitmap(image, new ScaleTransform(scale, scale));
  301. encoder.Frames.Add(BitmapFrame.Create(targetBitmap));
  302. path = System.IO.Path.Combine(path, name);
  303. using (FileStream stream = new FileStream(path, FileMode.Create))
  304. {
  305. encoder.Save(stream);
  306. }
  307. if (!string.IsNullOrEmpty(SaveToPath))
  308. {
  309. App.CachePath.AddToDeleteFiles(SaveToPath);
  310. }
  311. IsNewFile = true;
  312. SaveToPath = path;
  313. ImagePreviewSource = originalimagePreviewSource = targetBitmap;
  314. ShowImageButton = Visibility.Collapsed;
  315. if (IsRemoveBackground)
  316. {
  317. ImagePreviewSource = removeBackgroundImagePreviewSource = ToBitmapImage(KnockOutGzf());
  318. }
  319. }
  320. else
  321. {
  322. SaveToPath = "";
  323. }
  324. }
  325. private void ClearInkCanvas()
  326. {
  327. StrokesObject.Clear();
  328. }
  329. /// <summary>
  330. /// 去除白底
  331. /// </summary>
  332. private Bitmap KnockOutGzf()
  333. {
  334. System.Drawing.Image image = System.Drawing.Image.FromFile(SaveToPath);
  335. Bitmap bitmapProxy = new Bitmap(image);
  336. image.Dispose();
  337. for (int i = 0; i < bitmapProxy.Width; i++)
  338. {
  339. for (int j = 0; j < bitmapProxy.Height; j++)
  340. {
  341. System.Drawing.Color c = bitmapProxy.GetPixel(i, j);
  342. if (!(c.R < 240 || c.G < 240 || c.B < 240))
  343. {
  344. bitmapProxy.SetPixel(i, j, System.Drawing.Color.Transparent);
  345. }
  346. }
  347. }
  348. return bitmapProxy;
  349. }
  350. /// <summary>
  351. /// 将 Bitmap 转化为 BitmapSource
  352. /// </summary>
  353. /// <param name="bmp"/>要转换的 Bitmap
  354. /// <returns>转换后的 BitmapImage</returns>
  355. private BitmapImage ToBitmapImage(System.Drawing.Bitmap bmp)
  356. {
  357. System.IO.MemoryStream ms = new System.IO.MemoryStream();
  358. bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
  359. BitmapImage image = new BitmapImage();
  360. image.BeginInit();
  361. image.StreamSource = ms;
  362. image.CacheOption = BitmapCacheOption.OnLoad;
  363. image.EndInit();
  364. //编码,缓存到本地
  365. string path = App.CachePath.CustomStampPath;
  366. string name = Guid.NewGuid().ToString();
  367. BitmapEncoder encoder = new PngBitmapEncoder();
  368. encoder.Frames.Add(BitmapFrame.Create(image));
  369. path = System.IO.Path.Combine(path, name);
  370. using (FileStream stream = new FileStream(path, FileMode.Create))
  371. {
  372. encoder.Save(stream);
  373. }
  374. if (!string.IsNullOrEmpty(RemoveBackgroundSaveToPath))
  375. {
  376. App.CachePath.AddToDeleteFiles(RemoveBackgroundSaveToPath);
  377. }
  378. RemoveBackgroundSaveToPath = path;
  379. IsNewFile = false;
  380. return image;
  381. }
  382. /// <summary>
  383. /// 把文字转换成Bitmap
  384. /// </summary>
  385. /// <param name="text"></param>
  386. /// <param name="font"></param>
  387. /// <param name="rect">用于输出的矩形,文字在这个矩形内显示,为空时自动计算</param>
  388. /// <param name="fontcolor">字体颜色</param>
  389. /// <param name="backColor">背景颜色</param>
  390. /// <returns></returns>
  391. private Bitmap TextToBitmap(string text, string FontFamily, double size, Rectangle rect, System.Windows.Media.Brush fontcolor, System.Drawing.Color backColor)
  392. {
  393. FormattedText formatText = new FormattedText(text,
  394. CultureInfo.CurrentCulture,
  395. FlowDirection.LeftToRight,
  396. new Typeface(new System.Windows.Media.FontFamily(FontFamily), FontStyles.Normal, FontWeights.Normal, FontStretches.Normal),
  397. size,
  398. fontcolor, Helper.DpiHelpers.Dpi / 96F);
  399. DrawingVisual drawingVisual = new DrawingVisual();
  400. DrawingContext dc = drawingVisual.RenderOpen();
  401. dc.DrawText(formatText, new System.Windows.Point(2, 10));
  402. dc.Close();
  403. Rect x = drawingVisual.ContentBounds;
  404. Rect DrawRect = new Rect(0, 0, x.Width + (x.X / 2), x.Height + x.Y);
  405. RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap((int)((int)DrawRect.Width + (x.X / 2)), (int)((int)DrawRect.Height + x.Y), 96F, 96F, PixelFormats.Pbgra32);
  406. renderTargetBitmap.Render(drawingVisual);
  407. MemoryStream stream = new MemoryStream();
  408. BitmapEncoder encoder = new PngBitmapEncoder();
  409. encoder.Frames.Add(BitmapFrame.Create(renderTargetBitmap));
  410. encoder.Save(stream);
  411. Bitmap bitmap = new Bitmap(stream);
  412. return bitmap;
  413. }
  414. private void Cancel()
  415. {
  416. RequestClose.Invoke(new DialogResult(ButtonResult.Cancel));
  417. }
  418. private void Create()
  419. {
  420. switch (TabItemIndex)
  421. {
  422. case 0:
  423. {
  424. if (string.IsNullOrEmpty(InputText))
  425. {
  426. Cancel();
  427. return;
  428. }
  429. System.Windows.Media.Brush fontcolor = new SolidColorBrush((System.Windows.Media.Color)System.Windows.Media.ColorConverter.ConvertFromString("#252629"));
  430. switch (RadioButtonIndex)
  431. {
  432. case 1:
  433. fontcolor = new SolidColorBrush((System.Windows.Media.Color)System.Windows.Media.ColorConverter.ConvertFromString("#252629"));
  434. break;
  435. case 2:
  436. fontcolor = new SolidColorBrush((System.Windows.Media.Color)System.Windows.Media.ColorConverter.ConvertFromString("#F3465B"));
  437. break;
  438. case 3:
  439. fontcolor = new SolidColorBrush((System.Windows.Media.Color)System.Windows.Media.ColorConverter.ConvertFromString("#273C62"));
  440. break;
  441. case 4:
  442. fontcolor = new SolidColorBrush((System.Windows.Media.Color)System.Windows.Media.ColorConverter.ConvertFromString("#94989C"));
  443. break;
  444. default:
  445. break;
  446. }
  447. Bitmap bmp = TextToBitmap(InputText, FontNameList[fontNameIndex], 50, Rectangle.Empty, fontcolor, System.Drawing.Color.Transparent);
  448. string guid = Guid.NewGuid().ToString();
  449. string path = System.IO.Path.Combine(App.CachePath.SignatureStampPath, guid);
  450. bmp.Save(path, ImageFormat.Png);
  451. SaveToPath = path;
  452. }
  453. break;
  454. case 1:
  455. {
  456. var FreeHandpath = App.CachePath.SignatureFreeHandPath;
  457. string name = Guid.NewGuid().ToString();
  458. FreeHandpath = System.IO.Path.Combine(FreeHandpath, name);
  459. using (System.IO.FileStream stream = new System.IO.FileStream(FreeHandpath, System.IO.FileMode.Create))
  460. {
  461. StrokesObject.Save(stream);
  462. }
  463. StampAnnotArgs stampArgs = new StampAnnotArgs();
  464. List<List<System.Windows.Point>> RawPointList = new List<List<System.Windows.Point>>();
  465. for (int kk = 0; kk < StrokesObject.Count; kk++)
  466. {
  467. List<System.Windows.Point> p = new List<System.Windows.Point>();
  468. RawPointList.Add(p);
  469. for (int gg = 0; gg < StrokesObject[kk].StylusPoints.Count; gg++)
  470. {
  471. var point = StrokesObject[kk].StylusPoints[gg].ToPoint();
  472. if (point.X >= 0 && point.Y >= 0)
  473. RawPointList[kk].Add(point);
  474. }
  475. }
  476. DrawingSaveToPath = FreeHandpath;
  477. //根据当前选项创建预览图片
  478. double inkThickness;
  479. if (ThicknessListIndex >= 0)
  480. {
  481. inkThickness = Convert.ToDouble(ThicknessList[ThicknessListIndex].Substring(0, 3));
  482. }
  483. else
  484. {
  485. inkThickness = drawingAttributes.Width;
  486. }
  487. stampArgs.SetInkData(RawPointList, inkThickness, drawingAttributes.Color);
  488. var writeStamp = stampArgs.GetStampDrawing();
  489. FreeHandpath = App.CachePath.SignatureStampPath;
  490. string thumbnailName = Guid.NewGuid().ToString();
  491. FreeHandpath = System.IO.Path.Combine(FreeHandpath, thumbnailName);
  492. using (FileStream stream5 = new FileStream(FreeHandpath, FileMode.Create))
  493. {
  494. PngBitmapEncoder encoder5 = new PngBitmapEncoder();
  495. encoder5.Frames.Add(BitmapFrame.Create(writeStamp));
  496. encoder5.Save(stream5);
  497. }
  498. SaveToPath = FreeHandpath;
  499. }
  500. break;
  501. case 2:
  502. break;
  503. default:
  504. break;
  505. }
  506. DialogParameters valuePairs = new DialogParameters();
  507. valuePairs.Add(ParameterNames.DataModel, this);
  508. RequestClose.Invoke(new DialogResult(ButtonResult.OK, valuePairs));
  509. }
  510. /// <summary>
  511. /// 绘制时使用的画笔
  512. /// </summary>
  513. private void UpdataDrawingStrokes()
  514. {
  515. DrawingAttributeObject.Width = DrawingAttributeObject.Height = Convert.ToDouble(ThicknessList[thicknessListIndex].Substring(0, 3));
  516. }
  517. public bool CanCloseDialog()
  518. {
  519. return true;
  520. }
  521. public void OnDialogClosed()
  522. {
  523. return;
  524. }
  525. public void OnDialogOpened(IDialogParameters parameters)
  526. {
  527. if (parameters != null)
  528. {
  529. PDFViewer = parameters.GetValue<CPDFViewer>(ParameterNames.PDFViewer);
  530. if (PDFViewer != null)
  531. {
  532. }
  533. }
  534. return;
  535. }
  536. }
  537. }