MergeDialogViewModel.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596
  1. using ComPDFKit.PDFDocument;
  2. using ComPDFKit.PDFPage;
  3. using ComPDFKitViewer.PdfViewer;
  4. using Microsoft.Win32;
  5. using PDF_Master.CustomControl;
  6. using PDF_Master.EventAggregators;
  7. using PDF_Master.Helper;
  8. using PDF_Master.Model;
  9. using PDF_Master.Model.Dialog.ToolsDialogs;
  10. using PDF_Master.Properties;
  11. using PDF_Master.Views.Dialog;
  12. using Prism.Commands;
  13. using Prism.Events;
  14. using Prism.Mvvm;
  15. using Prism.Services.Dialogs;
  16. using System;
  17. using System.Collections.Generic;
  18. using System.Collections.ObjectModel;
  19. using System.IO;
  20. using System.Linq;
  21. using System.Text;
  22. using System.Threading.Tasks;
  23. using System.Windows;
  24. using System.Windows.Controls;
  25. using System.Windows.Media;
  26. using System.Windows.Media.Imaging;
  27. using static Dropbox.Api.TeamLog.PaperDownloadFormat;
  28. using static PDF_Master.Model.Dialog.ToolsDialogs.SaftyDialogs.DeleteSafetySettintgsModel;
  29. namespace PDF_Master.ViewModels.Dialog.ToolsDialogs
  30. {
  31. class MergeDialogViewModel : BindableBase, IDialogAware
  32. {
  33. // Fix:存储当前程序加载的文档的路径和tag,
  34. //如果路径相同则用tag里的密码解锁,
  35. //解锁失败再另行提权
  36. private string CurrentFilePath = string.Empty;
  37. private string currentLoadedPassword = string.Empty;
  38. private IEventAggregator eventAggregator;
  39. enum PageSizeType
  40. {
  41. kDefault = 0,
  42. A4 = 1,
  43. A3 = 2,
  44. Letter = 3,
  45. Legal = 4,
  46. Customized = 5,
  47. }
  48. #region 框架内容
  49. public string Title => "";
  50. public event Action<IDialogResult> RequestClose;
  51. public bool CanCloseDialog()
  52. {
  53. return true;
  54. }
  55. public void OnDialogClosed()
  56. {
  57. }
  58. public void OnDialogOpened(IDialogParameters parameters)
  59. {
  60. CPDFViewer pdfViewer = null;
  61. if (parameters.TryGetValue<CPDFViewer>(ParameterNames.PDFViewer, out pdfViewer)&&pdfViewer!=null&&pdfViewer.Document!=null)
  62. {
  63. VerifyPasswordResult condition = SecurityHelper.VerifyPasswordByPasswordKind(pdfViewer.Document, EnumPasswordKind.StatusPermissionsPassword, dialogs);
  64. if (condition.IsDiscryptied)
  65. {
  66. if (!string.IsNullOrEmpty(condition.Password))
  67. {
  68. if (pdfViewer.Document.UnlockWithPassword(condition.Password))
  69. {
  70. pdfViewer.Document.CheckOwnerPassword(condition.Password);
  71. }
  72. }
  73. string unicode;
  74. if (parameters.TryGetValue<string>(ParameterNames.Unicode, out unicode))
  75. {
  76. this.eventAggregator.GetEvent<ShowTipEvent>().Publish(new ShowTipEventArgs() { enumTipKind = EnumTipKind.StatusNone, Unicode = unicode });
  77. }
  78. }
  79. currentLoadedPassword = pdfViewer.Document.Password;
  80. }
  81. if (pdfViewer != null&&pdfViewer.Document!=null)
  82. {
  83. CurrentFilePath = pdfViewer.Document.FilePath;
  84. List<string> list = new List<string>();
  85. list.Add(CurrentFilePath);
  86. AddFiles(list.ToArray());
  87. }
  88. string[] Paths;
  89. parameters.TryGetValue<string[]>(ParameterNames.FilePath, out Paths);
  90. if (Paths != null)
  91. {
  92. AddFiles(Paths);
  93. }
  94. }
  95. #endregion
  96. #region 定义与初始化
  97. public ObservableCollection<MergeObject> MergeObjectlist { get; set; }
  98. public DelegateCommand CancelCommand { get; set; }
  99. public DelegateCommand MergeCommand { get; set; }
  100. public DelegateCommand<object> AddFilesCommand { get; set; }
  101. public DelegateCommand ClearCommand { get; set; }
  102. public DelegateCommand<object> SetPageSizeTypeCommand { get; set; }
  103. public IDialogService dialogs;
  104. private PageSizeType pageSizeType = PageSizeType.kDefault;
  105. private string inputWidth;
  106. public string InputWidth
  107. {
  108. get { return inputWidth; }
  109. set
  110. {
  111. SetProperty(ref inputWidth, value);
  112. }
  113. }
  114. private string inputHeight;
  115. public string InputHeight
  116. {
  117. get { return inputHeight; }
  118. set
  119. {
  120. SetProperty(ref inputHeight, value);
  121. }
  122. }
  123. private int comboBoxSelectedIndex = 0;
  124. public int ComboBoxSelectedIndex
  125. {
  126. get { return comboBoxSelectedIndex; }
  127. set
  128. {
  129. SetProperty(ref comboBoxSelectedIndex, value);
  130. }
  131. }
  132. public MergeDialogViewModel(IDialogService dialogService, IEventAggregator eventAggregator)
  133. {
  134. this.eventAggregator = eventAggregator;
  135. dialogs = dialogService;
  136. MergeObjectlist = new ObservableCollection<MergeObject>();
  137. CancelCommand = new DelegateCommand(Cancel);
  138. AddFilesCommand = new DelegateCommand<object>(ButtonAddFiles);
  139. MergeCommand = new DelegateCommand(Merge);
  140. ClearCommand = new DelegateCommand(Clear);
  141. SetPageSizeTypeCommand = new DelegateCommand<object>(SetPageSizeType);
  142. }
  143. #endregion
  144. #region 私有方法
  145. private void UpDataMergeObjectIndex()
  146. {
  147. for (int i = 0; i < MergeObjectlist.Count; i++)
  148. {
  149. MergeObjectlist[i].ItemIndex = i + 1;
  150. }
  151. }
  152. private void Cancel()
  153. {
  154. Clear();
  155. RequestClose.Invoke(new DialogResult(ButtonResult.Cancel));
  156. }
  157. public void ButtonAddFiles(object data)
  158. {
  159. int index = Convert.ToInt32(data);
  160. switch (index)
  161. {
  162. case 0:
  163. //打开文件
  164. ComboBoxSelectedIndex = 0;//打开文件弹窗会影响UI更新,所以手动更新
  165. AddFiles(OpenFile());
  166. break;
  167. case 1:
  168. //打开文件夹
  169. ComboBoxSelectedIndex = 1;//打开文件夹弹窗会影响UI更新,所以手动更新
  170. AddFiles(OpenFileFolder());
  171. break;
  172. case 2:
  173. //打开当前文件
  174. List<string> list = new List<string>();
  175. for (int i = 0; i < App.OpenedFileList.Count; i++)
  176. {
  177. list.Add(App.OpenedFileList[i]);
  178. }
  179. AddFiles(list.ToArray());
  180. break;
  181. default:
  182. break;
  183. }
  184. }
  185. private string[] OpenFileFolder()
  186. {
  187. System.Windows.Forms.FolderBrowserDialog openFile = new System.Windows.Forms.FolderBrowserDialog();
  188. if (openFile.ShowDialog() == System.Windows.Forms.DialogResult.Cancel)
  189. {
  190. return null;
  191. }
  192. DirectoryInfo tempfolder = new DirectoryInfo(openFile.SelectedPath);
  193. FileInfo[] fileInfos = tempfolder.GetFiles();
  194. List<string> list = new List<string>();
  195. foreach (FileInfo item in fileInfos)
  196. {
  197. list.Add(item.FullName);
  198. }
  199. DirectoryInfo[] directoryInfos= tempfolder.GetDirectories();
  200. foreach (DirectoryInfo fileInfo in directoryInfos)
  201. {
  202. FileInfo[] fileinfo = fileInfo.GetFiles();
  203. foreach (FileInfo item in fileinfo)
  204. {
  205. list.Add(item.FullName);
  206. }
  207. }
  208. return list.ToArray();
  209. }
  210. private string[] OpenFile()
  211. {
  212. OpenFileDialog openFile = new OpenFileDialog();
  213. openFile.Multiselect = true;
  214. openFile.Filter = Properties.Resources.imageex.ToLower() + "|*";
  215. if (openFile.ShowDialog() == false)
  216. {
  217. return null;
  218. }
  219. return openFile.FileNames;
  220. }
  221. private void Merge()
  222. {
  223. //判断本地有没有token,没有显示登录,有再判断登录状态
  224. if (Settings.Default.AppProperties.LoginToken != "")
  225. {
  226. if (ServiceHelper.GetUser() == "401")
  227. {
  228. App.mainWindowViewModel.UserVis = Visibility.Collapsed;
  229. App.mainWindowViewModel.LoginVis = Visibility.Visible;
  230. App.mainWindowViewModel.OphVis = Visibility.Visible;
  231. }
  232. }
  233. else
  234. {
  235. App.mainWindowViewModel.UserVis = Visibility.Collapsed;
  236. App.mainWindowViewModel.LoginVis = Visibility.Visible;
  237. App.mainWindowViewModel.OphVis = Visibility.Visible;
  238. }
  239. //付费锁
  240. if (!App.IsLogin)
  241. {
  242. dialogs.ShowDialog(DialogNames.IAPCompareDialog);
  243. return;
  244. }
  245. bool result = true;
  246. CPDFDocument SaveDoc = CPDFDocument.CreateDocument();
  247. for (int i = 0; i < MergeObjectlist.Count; i++)
  248. {
  249. //图片
  250. if (Path.GetExtension(MergeObjectlist[i].FilePath).Trim().ToLower() != ".pdf")
  251. {
  252. BitmapSource frame = MergeObjectlist[i].DocThumbnail;
  253. byte[] imageData = new byte[frame.PixelWidth * frame.PixelHeight * 4];
  254. if (frame.Format != PixelFormats.Bgra32)
  255. {
  256. FormatConvertedBitmap covert = new FormatConvertedBitmap(frame, PixelFormats.Bgra32, frame.Palette, 0);
  257. covert.CopyPixels(imageData, frame.PixelWidth * 4, 0);
  258. }
  259. else
  260. {
  261. frame.CopyPixels(imageData, frame.PixelWidth * 4, 0);
  262. }
  263. frame.CopyPixels(imageData, frame.PixelWidth * 4, 0);
  264. result = SaveDoc.InsertPage(0, frame.PixelWidth, frame.PixelHeight, imageData, CPDFDocumentImageMode.CPDFDocumentImageModeScaleToFill);
  265. if (!result)
  266. {
  267. SaveDoc.Release();
  268. return;
  269. }
  270. continue;
  271. }
  272. else
  273. {
  274. CPDFDocument tempDoc = CPDFDocument.InitWithFilePath(MergeObjectlist[i].FilePath);
  275. if (!string.IsNullOrEmpty(MergeObjectlist[i].Password))
  276. {
  277. tempDoc.UnlockWithPassword(MergeObjectlist[i].Password);
  278. }
  279. if (!string.IsNullOrEmpty(MergeObjectlist[i].SetPageRangeStr))
  280. {
  281. result = SaveDoc.ImportPages(tempDoc, MergeObjectlist[i].SetPageRangeStr);
  282. }
  283. else
  284. {
  285. //下拉框控件传出来的list是页面索引集合,
  286. //此处传给SDK的合并接口的是页码集合,因此需要将集合项遍历+1,只有合并接口是接收页码集合,其余接口是接受页面索引集合
  287. List<int> pageIndexs = new List<int>();
  288. for (int j = 0; j < MergeObjectlist[i].SetPageRange.Count; j++)
  289. {
  290. pageIndexs.Add(MergeObjectlist[i].SetPageRange[j] + 1);
  291. }
  292. result = SaveDoc.ImportPages(tempDoc, CommonHelper.GetPageParmFromList(pageIndexs));
  293. }
  294. if (!result)
  295. {
  296. SaveDoc.Release();
  297. tempDoc.Release();
  298. return;
  299. }
  300. tempDoc.Release();
  301. }
  302. }
  303. SaveFileDialog saveFileDialog = new SaveFileDialog();
  304. saveFileDialog.FileName = "Untitle";
  305. saveFileDialog.Filter = "PDF|*.pdf;";
  306. if (saveFileDialog.ShowDialog() == false)
  307. {
  308. return;
  309. }
  310. string path = saveFileDialog.FileName;
  311. System.Windows.Rect rect = new System.Windows.Rect();
  312. switch (pageSizeType)
  313. {
  314. case PageSizeType.kDefault:
  315. break;
  316. case PageSizeType.A4:
  317. rect.Width = CommonHelper.GetPageSizeFomrUnit(210);
  318. rect.Height = CommonHelper.GetPageSizeFomrUnit(297);
  319. break;
  320. case PageSizeType.A3:
  321. rect.Width = CommonHelper.GetPageSizeFomrUnit(297);
  322. rect.Height = CommonHelper.GetPageSizeFomrUnit(420);
  323. break;
  324. case PageSizeType.Letter:
  325. rect.Width = CommonHelper.GetPageSizeFomrUnit(216);
  326. rect.Height = CommonHelper.GetPageSizeFomrUnit(279);
  327. break;
  328. case PageSizeType.Legal:
  329. rect.Width = CommonHelper.GetPageSizeFomrUnit(216);
  330. rect.Height = CommonHelper.GetPageSizeFomrUnit(356);
  331. break;
  332. case PageSizeType.Customized:
  333. if (!string.IsNullOrEmpty(InputWidth) && !string.IsNullOrEmpty(InputHeight))
  334. {
  335. rect.Width = CommonHelper.GetPageSizeFomrUnit(Convert.ToInt32(InputWidth));
  336. rect.Height = CommonHelper.GetPageSizeFomrUnit(Convert.ToInt32(InputHeight));
  337. }
  338. else
  339. {
  340. rect.Width = CommonHelper.GetPageSizeFomrUnit(595);
  341. rect.Height = CommonHelper.GetPageSizeFomrUnit(841);
  342. }
  343. break;
  344. default:
  345. break;
  346. }
  347. if (rect.Width > 0 && rect.Height > 0)
  348. {
  349. //裁剪
  350. for (int i = 0; i < SaveDoc.PageCount; i++)
  351. {
  352. CPDFPage page = SaveDoc.PageAtIndex(i);
  353. page.CropPage(CPDFDisplayBox.MediaBox, rect);
  354. }
  355. }
  356. bool saveResult = SaveDoc.WriteToFilePath(path);
  357. SaveDoc.Release();
  358. CommonHelper.ShowFileBrowser(path);
  359. DialogParameters valuePairs = new DialogParameters();
  360. valuePairs.Add(ParameterNames.FilePath, path);
  361. RequestClose.Invoke(new DialogResult(ButtonResult.OK, valuePairs));
  362. }
  363. private void Clear()
  364. {
  365. MergeObjectlist.Clear();
  366. }
  367. private void SetPageSizeType(object button)
  368. {
  369. if (button is RadioButton)
  370. {
  371. pageSizeType = (PageSizeType)Convert.ToInt32((button as RadioButton).Tag);
  372. }
  373. }
  374. #endregion
  375. #region 公开方法
  376. public void DeleteItem(MergeObject merge)
  377. {
  378. MergeObjectlist.Remove(merge);
  379. UpDataMergeObjectIndex();
  380. }
  381. /// <summary>
  382. /// 拖拽插入
  383. /// </summary>
  384. public void MoveMerge(MergeObject targetNode, MergeObject soureNode)
  385. {
  386. int targetindex = MergeObjectlist.IndexOf(targetNode);
  387. MergeObjectlist.Remove(soureNode);
  388. if (targetNode.IsForward)
  389. {
  390. if (targetindex + 1 < MergeObjectlist.Count)
  391. {
  392. MergeObjectlist.Insert(targetindex + 1, soureNode);
  393. }
  394. else
  395. {
  396. MergeObjectlist.Add(soureNode);
  397. }
  398. }
  399. else
  400. {
  401. MergeObjectlist.Insert(targetindex, soureNode);
  402. }
  403. UpDataMergeObjectIndex();
  404. }
  405. public void AddFiles(string[] FilePath)
  406. {
  407. if (FilePath == null)
  408. {
  409. return;
  410. }
  411. bool showDialog = false;
  412. for (int i = 0; i < FilePath.Length; i++)
  413. {
  414. MergeObject mergeObject = new MergeObject();
  415. mergeObject.FilePath = FilePath[i];
  416. //通过路径判断文件是否已添加
  417. bool IsExists = false;
  418. for (int j = 0; j < MergeObjectlist.Count; j++)
  419. {
  420. if (MergeObjectlist[j].FilePath == mergeObject.FilePath)
  421. {
  422. IsExists = true;
  423. }
  424. }
  425. if (IsExists)
  426. {
  427. continue;
  428. }
  429. string FileType = Path.GetExtension(mergeObject.FilePath).Trim().ToLower();
  430. if (string.IsNullOrEmpty(FileType))
  431. {
  432. showDialog = true;
  433. //获取不到文件类型
  434. continue;
  435. }
  436. if (FileType != ".pdf")
  437. {
  438. string imagetype = "*" + FileType;
  439. string[] x = Properties.Resources.imageex.ToLower().Split(';');
  440. List<string> list = x.ToList();
  441. int imageindex = list.IndexOf(imagetype);
  442. if (imageindex < 0)
  443. {
  444. showDialog = true;
  445. //图片格式不支持
  446. continue;
  447. };
  448. mergeObject.DocName = Path.GetFileName(mergeObject.FilePath);
  449. mergeObject.DocPageCount = 1 + " " + App.MainPageLoader.GetString("Merge_ItemPages");
  450. mergeObject.SDKPageCount = 1;
  451. mergeObject.DocSize = CommonHelper.GetFileSize(mergeObject.FilePath);
  452. try
  453. {
  454. mergeObject.DocThumbnail = new BitmapImage(new Uri(mergeObject.FilePath));
  455. }
  456. catch (Exception)
  457. {
  458. showDialog = true;
  459. //解码错误
  460. continue;
  461. }
  462. }
  463. else
  464. {
  465. CPDFDocument doc = CPDFDocument.InitWithFilePath(mergeObject.FilePath);
  466. if (doc == null)
  467. {
  468. showDialog = true;
  469. //PDF打开失败
  470. continue;
  471. }
  472. ///Fix:
  473. ///情况分为:
  474. ///开启路径是当前路径:
  475. ///已解锁或本身就无密码->直接加入
  476. ///未解锁-> release
  477. ///
  478. /// 不是当前路径
  479. ///解锁或取消->
  480. ///
  481. if(CurrentFilePath == doc.FilePath)
  482. {
  483. if ((!(!doc.IsLocked&&(SecurityHelper.CheckHaveAllPermissions(doc)))) && (!(!string.IsNullOrEmpty(currentLoadedPassword) && doc.UnlockWithPassword(currentLoadedPassword) && doc.CheckOwnerPassword(currentLoadedPassword))))
  484. {
  485. doc.Release();
  486. continue;
  487. }
  488. }
  489. else
  490. {
  491. VerifyPasswordResult condition = SecurityHelper.VerifyPasswordByPasswordKind(doc, EnumPasswordKind.StatusPermissionsPassword, dialogs);
  492. if (condition.IsDiscryptied)
  493. {
  494. if (condition.Password != null)
  495. {
  496. mergeObject.Password = condition.Password;
  497. if(doc.UnlockWithPassword(condition.Password))
  498. {
  499. doc.CheckOwnerPassword(condition.Password);
  500. }
  501. }
  502. }
  503. else
  504. {
  505. doc.Release();
  506. continue;
  507. }
  508. }
  509. mergeObject.DocName = doc.FileName;
  510. mergeObject.DocPageCount = doc.PageCount.ToString() + " " + App.MainPageLoader.GetString("Merge_ItemPages");
  511. mergeObject.SDKPageCount = doc.PageCount;
  512. mergeObject.DocSize = CommonHelper.GetFileSize(mergeObject.FilePath);
  513. //获取第一页缩略图
  514. CPDFPage page = doc.PageAtIndex(0);
  515. Size size = doc.GetPageSize(0);
  516. byte[] bmpData = new byte[(int)(size.Width * size.Height * 4)];
  517. WriteableBitmap WirteBitmap = new WriteableBitmap((int)size.Width, (int)size.Height, 96, 96, PixelFormats.Bgra32, null);
  518. page.RenderPageBitmap(0, 0, (int)size.Width, (int)size.Height, 0xFFFFFFFF, bmpData, 1);
  519. WirteBitmap.WritePixels(new Int32Rect(0, 0, (int)size.Width, (int)size.Height), bmpData, WirteBitmap.BackBufferStride, 0);
  520. WirteBitmap.Freeze();
  521. mergeObject.DocThumbnail = WirteBitmap;
  522. doc.Release();
  523. }
  524. MergeObjectlist.Add(mergeObject);
  525. UpDataMergeObjectIndex();
  526. }
  527. if (showDialog)
  528. {
  529. AlertsMessage alertsMessage = new AlertsMessage();
  530. alertsMessage.ShowDialog("", "The file was not added successfully, please select the file again.", "OK");
  531. if (alertsMessage.result == ContentResult.Ok)
  532. {
  533. }
  534. }
  535. }
  536. #endregion
  537. }
  538. }