SignatureCreateDialogViewModel.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625
  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. //调整加载图片的方式,从Uri创建,路径中包含空格的图片无法成功添加 例如这个名称的图片:200200_6kb_jpg.jpg
  297. // 从文件中创建一个 Image 对象
  298. Image img = Image.FromFile(openFile.FileName);
  299. // 将 Image 对象转换成 BitmapImage 对象
  300. MemoryStream ms = new MemoryStream();
  301. img.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
  302. BitmapImage image = new BitmapImage();
  303. image.BeginInit();
  304. image.CacheOption = BitmapCacheOption.OnLoad;
  305. image.StreamSource = ms;
  306. image.EndInit();
  307. double scale = Math.Min((double)600 / image.PixelWidth, (double)600 / image.PixelHeight);
  308. scale = Math.Min(scale, 1);
  309. BitmapEncoder encoder = new PngBitmapEncoder();
  310. var targetBitmap = new TransformedBitmap(image, new ScaleTransform(scale, scale));
  311. encoder.Frames.Add(BitmapFrame.Create(targetBitmap));
  312. path = System.IO.Path.Combine(path, name);
  313. using (FileStream stream = new FileStream(path, FileMode.Create))
  314. {
  315. encoder.Save(stream);
  316. }
  317. if (!string.IsNullOrEmpty(SaveToPath))
  318. {
  319. App.CachePath.AddToDeleteFiles(SaveToPath);
  320. }
  321. IsNewFile = true;
  322. SaveToPath = path;
  323. ImagePreviewSource = originalimagePreviewSource = targetBitmap;
  324. ShowImageButton = Visibility.Collapsed;
  325. if (IsRemoveBackground)
  326. {
  327. ImagePreviewSource = removeBackgroundImagePreviewSource = ToBitmapImage(KnockOutGzf());
  328. }
  329. }
  330. else
  331. {
  332. SaveToPath = "";
  333. }
  334. }
  335. private void ClearInkCanvas()
  336. {
  337. StrokesObject.Clear();
  338. }
  339. /// <summary>
  340. /// 去除白底
  341. /// </summary>
  342. private Bitmap KnockOutGzf()
  343. {
  344. System.Drawing.Image image = System.Drawing.Image.FromFile(SaveToPath);
  345. Bitmap bitmapProxy = new Bitmap(image);
  346. image.Dispose();
  347. for (int i = 0; i < bitmapProxy.Width; i++)
  348. {
  349. for (int j = 0; j < bitmapProxy.Height; j++)
  350. {
  351. System.Drawing.Color c = bitmapProxy.GetPixel(i, j);
  352. if (!(c.R < 240 || c.G < 240 || c.B < 240))
  353. {
  354. bitmapProxy.SetPixel(i, j, System.Drawing.Color.Transparent);
  355. }
  356. }
  357. }
  358. return bitmapProxy;
  359. }
  360. /// <summary>
  361. /// 将 Bitmap 转化为 BitmapSource
  362. /// </summary>
  363. /// <param name="bmp"/>要转换的 Bitmap
  364. /// <returns>转换后的 BitmapImage</returns>
  365. private BitmapImage ToBitmapImage(System.Drawing.Bitmap bmp)
  366. {
  367. System.IO.MemoryStream ms = new System.IO.MemoryStream();
  368. bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
  369. BitmapImage image = new BitmapImage();
  370. image.BeginInit();
  371. image.StreamSource = ms;
  372. image.CacheOption = BitmapCacheOption.OnLoad;
  373. image.EndInit();
  374. //编码,缓存到本地
  375. string path = App.CachePath.CustomStampPath;
  376. string name = Guid.NewGuid().ToString();
  377. BitmapEncoder encoder = new PngBitmapEncoder();
  378. encoder.Frames.Add(BitmapFrame.Create(image));
  379. path = System.IO.Path.Combine(path, name);
  380. using (FileStream stream = new FileStream(path, FileMode.Create))
  381. {
  382. encoder.Save(stream);
  383. }
  384. if (!string.IsNullOrEmpty(RemoveBackgroundSaveToPath))
  385. {
  386. App.CachePath.AddToDeleteFiles(RemoveBackgroundSaveToPath);
  387. }
  388. RemoveBackgroundSaveToPath = path;
  389. IsNewFile = false;
  390. return image;
  391. }
  392. /// <summary>
  393. /// 把文字转换成Bitmap
  394. /// </summary>
  395. /// <param name="text"></param>
  396. /// <param name="font"></param>
  397. /// <param name="rect">用于输出的矩形,文字在这个矩形内显示,为空时自动计算</param>
  398. /// <param name="fontcolor">字体颜色</param>
  399. /// <param name="backColor">背景颜色</param>
  400. /// <returns></returns>
  401. private Bitmap TextToBitmap(string text, string FontFamily, double size, Rectangle rect, System.Windows.Media.Brush fontcolor, System.Drawing.Color backColor)
  402. {
  403. FormattedText formatText = new FormattedText(text,
  404. CultureInfo.CurrentCulture,
  405. FlowDirection.LeftToRight,
  406. new Typeface(new System.Windows.Media.FontFamily(FontFamily), FontStyles.Normal, FontWeights.Normal, FontStretches.Normal),
  407. size,
  408. fontcolor, Helper.DpiHelpers.Dpi / 96F);
  409. DrawingVisual drawingVisual = new DrawingVisual();
  410. DrawingContext dc = drawingVisual.RenderOpen();
  411. dc.DrawText(formatText, new System.Windows.Point(2, 10));
  412. dc.Close();
  413. Rect x = drawingVisual.ContentBounds;
  414. Rect DrawRect = new Rect(0, 0, x.Width + (x.X / 2), x.Height + x.Y);
  415. RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap((int)((int)DrawRect.Width + (x.X / 2)), (int)((int)DrawRect.Height + x.Y), 96F, 96F, PixelFormats.Pbgra32);
  416. renderTargetBitmap.Render(drawingVisual);
  417. MemoryStream stream = new MemoryStream();
  418. BitmapEncoder encoder = new PngBitmapEncoder();
  419. encoder.Frames.Add(BitmapFrame.Create(renderTargetBitmap));
  420. encoder.Save(stream);
  421. Bitmap bitmap = new Bitmap(stream);
  422. return bitmap;
  423. }
  424. private void Cancel()
  425. {
  426. RequestClose.Invoke(new DialogResult(ButtonResult.Cancel));
  427. }
  428. private void Create()
  429. {
  430. switch (TabItemIndex)
  431. {
  432. case 0:
  433. {
  434. if (string.IsNullOrEmpty(InputText))
  435. {
  436. Cancel();
  437. return;
  438. }
  439. System.Windows.Media.Brush fontcolor = new SolidColorBrush((System.Windows.Media.Color)System.Windows.Media.ColorConverter.ConvertFromString("#252629"));
  440. switch (RadioButtonIndex)
  441. {
  442. case 1:
  443. fontcolor = new SolidColorBrush((System.Windows.Media.Color)System.Windows.Media.ColorConverter.ConvertFromString("#252629"));
  444. break;
  445. case 2:
  446. fontcolor = new SolidColorBrush((System.Windows.Media.Color)System.Windows.Media.ColorConverter.ConvertFromString("#F3465B"));
  447. break;
  448. case 3:
  449. fontcolor = new SolidColorBrush((System.Windows.Media.Color)System.Windows.Media.ColorConverter.ConvertFromString("#273C62"));
  450. break;
  451. case 4:
  452. fontcolor = new SolidColorBrush((System.Windows.Media.Color)System.Windows.Media.ColorConverter.ConvertFromString("#94989C"));
  453. break;
  454. default:
  455. break;
  456. }
  457. Bitmap bmp = TextToBitmap(InputText, FontNameList[fontNameIndex], 50, Rectangle.Empty, fontcolor, System.Drawing.Color.Transparent);
  458. string guid = Guid.NewGuid().ToString();
  459. string path = System.IO.Path.Combine(App.CachePath.SignatureStampPath, guid);
  460. bmp.Save(path, ImageFormat.Png);
  461. SaveToPath = path;
  462. }
  463. break;
  464. case 1:
  465. {
  466. var FreeHandpath = App.CachePath.SignatureFreeHandPath;
  467. string name = Guid.NewGuid().ToString();
  468. FreeHandpath = System.IO.Path.Combine(FreeHandpath, name);
  469. using (System.IO.FileStream stream = new System.IO.FileStream(FreeHandpath, System.IO.FileMode.Create))
  470. {
  471. StrokesObject.Save(stream);
  472. }
  473. StampAnnotArgs stampArgs = new StampAnnotArgs();
  474. List<List<System.Windows.Point>> RawPointList = new List<List<System.Windows.Point>>();
  475. for (int kk = 0; kk < StrokesObject.Count; kk++)
  476. {
  477. List<System.Windows.Point> p = new List<System.Windows.Point>();
  478. RawPointList.Add(p);
  479. for (int gg = 0; gg < StrokesObject[kk].StylusPoints.Count; gg++)
  480. {
  481. var point = StrokesObject[kk].StylusPoints[gg].ToPoint();
  482. if (point.X >= 0 && point.Y >= 0)
  483. RawPointList[kk].Add(point);
  484. }
  485. }
  486. DrawingSaveToPath = FreeHandpath;
  487. //根据当前选项创建预览图片
  488. double inkThickness;
  489. if (ThicknessListIndex >= 0)
  490. {
  491. inkThickness = Convert.ToDouble(ThicknessList[ThicknessListIndex].Substring(0, 3));
  492. }
  493. else
  494. {
  495. inkThickness = drawingAttributes.Width;
  496. }
  497. stampArgs.SetInkData(RawPointList, inkThickness, drawingAttributes.Color);
  498. var writeStamp = stampArgs.GetStampDrawing();
  499. FreeHandpath = App.CachePath.SignatureStampPath;
  500. string thumbnailName = Guid.NewGuid().ToString();
  501. FreeHandpath = System.IO.Path.Combine(FreeHandpath, thumbnailName);
  502. using (FileStream stream5 = new FileStream(FreeHandpath, FileMode.Create))
  503. {
  504. PngBitmapEncoder encoder5 = new PngBitmapEncoder();
  505. encoder5.Frames.Add(BitmapFrame.Create(writeStamp));
  506. encoder5.Save(stream5);
  507. }
  508. SaveToPath = FreeHandpath;
  509. }
  510. break;
  511. case 2:
  512. break;
  513. default:
  514. break;
  515. }
  516. DialogParameters valuePairs = new DialogParameters();
  517. valuePairs.Add(ParameterNames.DataModel, this);
  518. RequestClose.Invoke(new DialogResult(ButtonResult.OK, valuePairs));
  519. }
  520. /// <summary>
  521. /// 绘制时使用的画笔
  522. /// </summary>
  523. private void UpdataDrawingStrokes()
  524. {
  525. DrawingAttributeObject.Width = DrawingAttributeObject.Height = Convert.ToDouble(ThicknessList[thicknessListIndex].Substring(0, 3));
  526. }
  527. public bool CanCloseDialog()
  528. {
  529. return true;
  530. }
  531. public void OnDialogClosed()
  532. {
  533. return;
  534. }
  535. public void OnDialogOpened(IDialogParameters parameters)
  536. {
  537. if (parameters != null)
  538. {
  539. PDFViewer = parameters.GetValue<CPDFViewer>(ParameterNames.PDFViewer);
  540. if (PDFViewer != null)
  541. {
  542. }
  543. }
  544. return;
  545. }
  546. }
  547. }