MergeDialogViewModel.cs 23 KB

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