MergeDialogViewModel.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574
  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. bool result = true;
  224. CPDFDocument SaveDoc = CPDFDocument.CreateDocument();
  225. for (int i = 0; i < MergeObjectlist.Count; i++)
  226. {
  227. //图片
  228. if (Path.GetExtension(MergeObjectlist[i].FilePath).Trim().ToLower() != ".pdf")
  229. {
  230. BitmapSource frame = MergeObjectlist[i].DocThumbnail;
  231. byte[] imageData = new byte[frame.PixelWidth * frame.PixelHeight * 4];
  232. if (frame.Format != PixelFormats.Bgra32)
  233. {
  234. FormatConvertedBitmap covert = new FormatConvertedBitmap(frame, PixelFormats.Bgra32, frame.Palette, 0);
  235. covert.CopyPixels(imageData, frame.PixelWidth * 4, 0);
  236. }
  237. else
  238. {
  239. frame.CopyPixels(imageData, frame.PixelWidth * 4, 0);
  240. }
  241. frame.CopyPixels(imageData, frame.PixelWidth * 4, 0);
  242. result = SaveDoc.InsertPage(0, frame.PixelWidth, frame.PixelHeight, imageData, CPDFDocumentImageMode.CPDFDocumentImageModeScaleToFill);
  243. if (!result)
  244. {
  245. SaveDoc.Release();
  246. return;
  247. }
  248. continue;
  249. }
  250. else
  251. {
  252. CPDFDocument tempDoc = CPDFDocument.InitWithFilePath(MergeObjectlist[i].FilePath);
  253. if (!string.IsNullOrEmpty(MergeObjectlist[i].Password))
  254. {
  255. tempDoc.UnlockWithPassword(MergeObjectlist[i].Password);
  256. }
  257. if (!string.IsNullOrEmpty(MergeObjectlist[i].SetPageRangeStr))
  258. {
  259. result = SaveDoc.ImportPages(tempDoc, MergeObjectlist[i].SetPageRangeStr);
  260. }
  261. else
  262. {
  263. //下拉框控件传出来的list是页面索引集合,
  264. //此处传给SDK的合并接口的是页码集合,因此需要将集合项遍历+1,只有合并接口是接收页码集合,其余接口是接受页面索引集合
  265. List<int> pageIndexs = new List<int>();
  266. for (int j = 0; j < MergeObjectlist[i].SetPageRange.Count; j++)
  267. {
  268. pageIndexs.Add(MergeObjectlist[i].SetPageRange[j] + 1);
  269. }
  270. result = SaveDoc.ImportPages(tempDoc, CommonHelper.GetPageParmFromList(pageIndexs));
  271. }
  272. if (!result)
  273. {
  274. SaveDoc.Release();
  275. tempDoc.Release();
  276. return;
  277. }
  278. tempDoc.Release();
  279. }
  280. }
  281. SaveFileDialog saveFileDialog = new SaveFileDialog();
  282. saveFileDialog.FileName = "Untitle";
  283. saveFileDialog.Filter = "PDF|*.pdf;";
  284. if (saveFileDialog.ShowDialog() == false)
  285. {
  286. return;
  287. }
  288. string path = saveFileDialog.FileName;
  289. System.Windows.Rect rect = new System.Windows.Rect();
  290. switch (pageSizeType)
  291. {
  292. case PageSizeType.kDefault:
  293. break;
  294. case PageSizeType.A4:
  295. rect.Width = CommonHelper.GetPageSizeFomrUnit(210);
  296. rect.Height = CommonHelper.GetPageSizeFomrUnit(297);
  297. break;
  298. case PageSizeType.A3:
  299. rect.Width = CommonHelper.GetPageSizeFomrUnit(297);
  300. rect.Height = CommonHelper.GetPageSizeFomrUnit(420);
  301. break;
  302. case PageSizeType.Letter:
  303. rect.Width = CommonHelper.GetPageSizeFomrUnit(216);
  304. rect.Height = CommonHelper.GetPageSizeFomrUnit(279);
  305. break;
  306. case PageSizeType.Legal:
  307. rect.Width = CommonHelper.GetPageSizeFomrUnit(216);
  308. rect.Height = CommonHelper.GetPageSizeFomrUnit(356);
  309. break;
  310. case PageSizeType.Customized:
  311. if (!string.IsNullOrEmpty(InputWidth) && !string.IsNullOrEmpty(InputHeight))
  312. {
  313. rect.Width = CommonHelper.GetPageSizeFomrUnit(Convert.ToInt32(InputWidth));
  314. rect.Height = CommonHelper.GetPageSizeFomrUnit(Convert.ToInt32(InputHeight));
  315. }
  316. else
  317. {
  318. rect.Width = CommonHelper.GetPageSizeFomrUnit(595);
  319. rect.Height = CommonHelper.GetPageSizeFomrUnit(841);
  320. }
  321. break;
  322. default:
  323. break;
  324. }
  325. if (rect.Width > 0 && rect.Height > 0)
  326. {
  327. //裁剪
  328. for (int i = 0; i < SaveDoc.PageCount; i++)
  329. {
  330. CPDFPage page = SaveDoc.PageAtIndex(i);
  331. page.CropPage(CPDFDisplayBox.MediaBox, rect);
  332. }
  333. }
  334. bool saveResult = SaveDoc.WriteToFilePath(path);
  335. SaveDoc.Release();
  336. CommonHelper.ShowFileBrowser(path);
  337. DialogParameters valuePairs = new DialogParameters();
  338. valuePairs.Add(ParameterNames.FilePath, path);
  339. RequestClose.Invoke(new DialogResult(ButtonResult.OK, valuePairs));
  340. }
  341. private void Clear()
  342. {
  343. MergeObjectlist.Clear();
  344. }
  345. private void SetPageSizeType(object button)
  346. {
  347. if (button is RadioButton)
  348. {
  349. pageSizeType = (PageSizeType)Convert.ToInt32((button as RadioButton).Tag);
  350. }
  351. }
  352. #endregion
  353. #region 公开方法
  354. public void DeleteItem(MergeObject merge)
  355. {
  356. MergeObjectlist.Remove(merge);
  357. UpDataMergeObjectIndex();
  358. }
  359. /// <summary>
  360. /// 拖拽插入
  361. /// </summary>
  362. public void MoveMerge(MergeObject targetNode, MergeObject soureNode)
  363. {
  364. int targetindex = MergeObjectlist.IndexOf(targetNode);
  365. MergeObjectlist.Remove(soureNode);
  366. if (targetNode.IsForward)
  367. {
  368. if (targetindex + 1 < MergeObjectlist.Count)
  369. {
  370. MergeObjectlist.Insert(targetindex + 1, soureNode);
  371. }
  372. else
  373. {
  374. MergeObjectlist.Add(soureNode);
  375. }
  376. }
  377. else
  378. {
  379. MergeObjectlist.Insert(targetindex, soureNode);
  380. }
  381. UpDataMergeObjectIndex();
  382. }
  383. public void AddFiles(string[] FilePath)
  384. {
  385. if (FilePath == null)
  386. {
  387. return;
  388. }
  389. bool showDialog = false;
  390. for (int i = 0; i < FilePath.Length; i++)
  391. {
  392. MergeObject mergeObject = new MergeObject();
  393. mergeObject.FilePath = FilePath[i];
  394. //通过路径判断文件是否已添加
  395. bool IsExists = false;
  396. for (int j = 0; j < MergeObjectlist.Count; j++)
  397. {
  398. if (MergeObjectlist[j].FilePath == mergeObject.FilePath)
  399. {
  400. IsExists = true;
  401. }
  402. }
  403. if (IsExists)
  404. {
  405. continue;
  406. }
  407. string FileType = Path.GetExtension(mergeObject.FilePath).Trim().ToLower();
  408. if (string.IsNullOrEmpty(FileType))
  409. {
  410. showDialog = true;
  411. //获取不到文件类型
  412. continue;
  413. }
  414. if (FileType != ".pdf")
  415. {
  416. string imagetype = "*" + FileType;
  417. string[] x = Properties.Resources.imageex.ToLower().Split(';');
  418. List<string> list = x.ToList();
  419. int imageindex = list.IndexOf(imagetype);
  420. if (imageindex < 0)
  421. {
  422. showDialog = true;
  423. //图片格式不支持
  424. continue;
  425. };
  426. mergeObject.DocName = Path.GetFileName(mergeObject.FilePath);
  427. mergeObject.DocPageCount = 1 + " " + App.MainPageLoader.GetString("Merge_ItemPages");
  428. mergeObject.SDKPageCount = 1;
  429. mergeObject.DocSize = CommonHelper.GetFileSize(mergeObject.FilePath);
  430. try
  431. {
  432. mergeObject.DocThumbnail = new BitmapImage(new Uri(mergeObject.FilePath));
  433. }
  434. catch (Exception)
  435. {
  436. showDialog = true;
  437. //解码错误
  438. continue;
  439. }
  440. }
  441. else
  442. {
  443. CPDFDocument doc = CPDFDocument.InitWithFilePath(mergeObject.FilePath);
  444. if (doc == null)
  445. {
  446. showDialog = true;
  447. //PDF打开失败
  448. continue;
  449. }
  450. ///Fix:
  451. ///情况分为:
  452. ///开启路径是当前路径:
  453. ///已解锁或本身就无密码->直接加入
  454. ///未解锁-> release
  455. ///
  456. /// 不是当前路径
  457. ///解锁或取消->
  458. ///
  459. if(CurrentFilePath == doc.FilePath)
  460. {
  461. if ((!(!doc.IsLocked&&(SecurityHelper.CheckHaveAllPermissions(doc)))) &&
  462. (!(!string.IsNullOrEmpty(currentLoadedPassword) &&
  463. doc.UnlockWithPassword(currentLoadedPassword) &&
  464. (doc.CheckOwnerPassword(currentLoadedPassword)||SecurityHelper.CheckHaveAllPermissions(doc)))))
  465. {
  466. doc.Release();
  467. continue;
  468. }
  469. }
  470. else
  471. {
  472. VerifyPasswordResult condition = SecurityHelper.VerifyPasswordByPasswordKind(doc, EnumPasswordKind.StatusPermissionsPassword, dialogs);
  473. if (condition.IsDiscryptied)
  474. {
  475. if (condition.Password != null)
  476. {
  477. mergeObject.Password = condition.Password;
  478. if(doc.UnlockWithPassword(condition.Password)&& doc.CheckOwnerPassword(condition.Password))
  479. {
  480. }
  481. }
  482. }
  483. else
  484. {
  485. doc.Release();
  486. continue;
  487. }
  488. }
  489. mergeObject.DocName = doc.FileName;
  490. mergeObject.DocPageCount = doc.PageCount.ToString() + " " + App.MainPageLoader.GetString("Merge_ItemPages");
  491. mergeObject.SDKPageCount = doc.PageCount;
  492. mergeObject.DocSize = CommonHelper.GetFileSize(mergeObject.FilePath);
  493. //获取第一页缩略图
  494. CPDFPage page = doc.PageAtIndex(0);
  495. Size size = doc.GetPageSize(0);
  496. byte[] bmpData = new byte[(int)(size.Width * size.Height * 4)];
  497. WriteableBitmap WirteBitmap = new WriteableBitmap((int)size.Width, (int)size.Height, 96, 96, PixelFormats.Bgra32, null);
  498. page.RenderPageBitmap(0, 0, (int)size.Width, (int)size.Height, 0xFFFFFFFF, bmpData, 1);
  499. WirteBitmap.WritePixels(new Int32Rect(0, 0, (int)size.Width, (int)size.Height), bmpData, WirteBitmap.BackBufferStride, 0);
  500. WirteBitmap.Freeze();
  501. mergeObject.DocThumbnail = WirteBitmap;
  502. doc.Release();
  503. }
  504. MergeObjectlist.Add(mergeObject);
  505. UpDataMergeObjectIndex();
  506. }
  507. if (showDialog)
  508. {
  509. AlertsMessage alertsMessage = new AlertsMessage();
  510. alertsMessage.ShowDialog("", App.MainPageLoader.GetString("ErrorFile_Warning"), App.ServiceLoader.GetString("Text_ok"));
  511. if (alertsMessage.result == ContentResult.Ok)
  512. {
  513. }
  514. }
  515. }
  516. #endregion
  517. }
  518. }