MergeDialogViewModel.cs 20 KB

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