MergeDialogViewModel.cs 18 KB

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