MergeDialogViewModel.cs 21 KB

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