MergeDialogViewModel.cs 18 KB

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