MergeDialogViewModel.cs 20 KB

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