MergeDialogViewModel.cs 23 KB

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