MergeDialogViewModel.cs 22 KB

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