MergeDialogViewModel.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  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. bool result = true;
  179. CPDFDocument SaveDoc = CPDFDocument.CreateDocument();
  180. for (int i = 0; i < MergeObjectlist.Count; i++)
  181. {
  182. //图片
  183. if (Path.GetExtension(MergeObjectlist[i].FilePath).Trim().ToLower() != ".pdf")
  184. {
  185. BitmapSource frame = MergeObjectlist[i].DocThumbnail;
  186. byte[] imageData = new byte[frame.PixelWidth * frame.PixelHeight * 4];
  187. if (frame.Format != PixelFormats.Bgra32)
  188. {
  189. FormatConvertedBitmap covert = new FormatConvertedBitmap(frame, PixelFormats.Bgra32, frame.Palette, 0);
  190. covert.CopyPixels(imageData, frame.PixelWidth * 4, 0);
  191. }
  192. else
  193. {
  194. frame.CopyPixels(imageData, frame.PixelWidth * 4, 0);
  195. }
  196. frame.CopyPixels(imageData, frame.PixelWidth * 4, 0);
  197. result = SaveDoc.InsertPage(0, frame.PixelWidth, frame.PixelHeight, imageData, CPDFDocumentImageMode.CPDFDocumentImageModeScaleToFill);
  198. if (!result)
  199. {
  200. SaveDoc.Release();
  201. return;
  202. }
  203. continue;
  204. }
  205. else
  206. {
  207. CPDFDocument tempDoc = CPDFDocument.InitWithFilePath(MergeObjectlist[i].FilePath);
  208. if (!string.IsNullOrEmpty(MergeObjectlist[i].Password))
  209. {
  210. tempDoc.UnlockWithPassword(MergeObjectlist[i].Password);
  211. }
  212. result = SaveDoc.ImportPages(tempDoc, MergeObjectlist[i].SetPageRange);
  213. if (!result)
  214. {
  215. SaveDoc.Release();
  216. tempDoc.Release();
  217. return;
  218. }
  219. tempDoc.Release();
  220. }
  221. }
  222. SaveFileDialog saveFileDialog = new SaveFileDialog();
  223. saveFileDialog.FileName = "Untitle";
  224. saveFileDialog.Filter = "PDF|*.pdf;";
  225. if (saveFileDialog.ShowDialog() == false)
  226. {
  227. return;
  228. }
  229. string path = saveFileDialog.FileName;
  230. System.Windows.Rect rect = new System.Windows.Rect();
  231. switch (pageSizeType)
  232. {
  233. case PageSizeType.kDefault:
  234. break;
  235. case PageSizeType.A4:
  236. rect.Width = CommonHelper.GetPageSizeFomrUnit(210);
  237. rect.Height = CommonHelper.GetPageSizeFomrUnit(297);
  238. break;
  239. case PageSizeType.A3:
  240. rect.Width = CommonHelper.GetPageSizeFomrUnit(297);
  241. rect.Height = CommonHelper.GetPageSizeFomrUnit(420);
  242. break;
  243. case PageSizeType.Letter:
  244. rect.Width = CommonHelper.GetPageSizeFomrUnit(216);
  245. rect.Height = CommonHelper.GetPageSizeFomrUnit(279);
  246. break;
  247. case PageSizeType.Legal:
  248. rect.Width = CommonHelper.GetPageSizeFomrUnit(216);
  249. rect.Height = CommonHelper.GetPageSizeFomrUnit(356);
  250. break;
  251. case PageSizeType.Customized:
  252. if (!string.IsNullOrEmpty(InputWidth) && !string.IsNullOrEmpty(InputHeight))
  253. {
  254. rect.Width = CommonHelper.GetPageSizeFomrUnit(Convert.ToInt32(InputWidth));
  255. rect.Height = CommonHelper.GetPageSizeFomrUnit(Convert.ToInt32(InputHeight));
  256. }
  257. else
  258. {
  259. rect.Width = CommonHelper.GetPageSizeFomrUnit(595);
  260. rect.Height = CommonHelper.GetPageSizeFomrUnit(841);
  261. }
  262. break;
  263. default:
  264. break;
  265. }
  266. if (rect.Width > 0 && rect.Height > 0)
  267. {
  268. //裁剪
  269. for (int i = 0; i < SaveDoc.PageCount; i++)
  270. {
  271. CPDFPage page = SaveDoc.PageAtIndex(i);
  272. page.CropPage(CPDFDisplayBox.MediaBox, rect);
  273. }
  274. }
  275. bool saveResult = SaveDoc.WriteToFilePath(path);
  276. SaveDoc.Release();
  277. CommonHelper.ShowFileBrowser(path);
  278. DialogParameters valuePairs = new DialogParameters();
  279. valuePairs.Add(ParameterNames.FilePath, path);
  280. RequestClose.Invoke(new DialogResult(ButtonResult.OK, valuePairs));
  281. }
  282. private void Clear()
  283. {
  284. MergeObjectlist.Clear();
  285. }
  286. private void SetPageSizeType(object button)
  287. {
  288. if (button is RadioButton)
  289. {
  290. pageSizeType = (PageSizeType)Convert.ToInt32((button as RadioButton).Tag);
  291. }
  292. }
  293. #endregion
  294. #region 公开方法
  295. public void DeleteItem(MergeObject merge)
  296. {
  297. MergeObjectlist.Remove(merge);
  298. }
  299. /// <summary>
  300. /// 拖拽插入
  301. /// </summary>
  302. public void MoveMerge(MergeObject targetNode, MergeObject soureNode)
  303. {
  304. int targetindex = MergeObjectlist.IndexOf(targetNode);
  305. MergeObjectlist.Remove(soureNode);
  306. if (targetNode.IsForward)
  307. {
  308. if (targetindex + 1 < MergeObjectlist.Count)
  309. {
  310. MergeObjectlist.Insert(targetindex + 1, soureNode);
  311. }
  312. else
  313. {
  314. MergeObjectlist.Add(soureNode);
  315. }
  316. }
  317. else
  318. {
  319. MergeObjectlist.Insert(targetindex, soureNode);
  320. }
  321. UpDataMergeObjectIndex();
  322. }
  323. public void AddFiles(string[] FilePath)
  324. {
  325. if (FilePath == null)
  326. {
  327. return;
  328. }
  329. bool result = true;
  330. for (int i = 0; i < FilePath.Length; i++)
  331. {
  332. MergeObject mergeObject = new MergeObject();
  333. mergeObject.FilePath = FilePath[i];
  334. //通过路径判断文件是否已添加
  335. bool IsExists = false;
  336. for (int j = 0; j < MergeObjectlist.Count; j++)
  337. {
  338. if (MergeObjectlist[j].FilePath == mergeObject.FilePath)
  339. {
  340. IsExists = true;
  341. }
  342. }
  343. if (IsExists)
  344. {
  345. continue;
  346. }
  347. string FileType = Path.GetExtension(mergeObject.FilePath).Trim().ToLower();
  348. if (string.IsNullOrEmpty(FileType))
  349. {
  350. AlertsMessage alertsMessage = new AlertsMessage();
  351. alertsMessage.ShowDialog("", "The file was not added successfully, please select the file again.","OK");
  352. if (alertsMessage.result == ContentResult.Ok)
  353. {
  354. //获取不到文件类型
  355. continue;
  356. }
  357. }
  358. if (FileType != ".pdf")
  359. {
  360. string imagetype = "*" + FileType;
  361. string[] x = Properties.Resources.imageex.ToLower().Split(';');
  362. List<string> list = x.ToList();
  363. int imageindex = list.IndexOf(imagetype);
  364. if (imageindex < 0)
  365. {
  366. AlertsMessage alertsMessage = new AlertsMessage();
  367. alertsMessage.ShowDialog("", "The file was not added successfully, please select the file again.", "OK");
  368. if (alertsMessage.result == ContentResult.Ok)
  369. {
  370. //图片格式不支持
  371. continue;
  372. }
  373. };
  374. mergeObject.DocName = Path.GetFileName(mergeObject.FilePath);
  375. mergeObject.DocPageCount = 1 + " " + App.MainPageLoader.GetString("Merge_ItemPages");
  376. mergeObject.SDKPageCount = 1;
  377. mergeObject.DocSize = CommonHelper.GetFileSize(mergeObject.FilePath);
  378. try
  379. {
  380. mergeObject.DocThumbnail = new BitmapImage(new Uri(mergeObject.FilePath));
  381. }
  382. catch (Exception)
  383. {
  384. AlertsMessage alertsMessage = new AlertsMessage();
  385. alertsMessage.ShowDialog("", "The file was not added successfully, please select the file again.", "OK");
  386. if (alertsMessage.result == ContentResult.Ok)
  387. {
  388. //解码错误
  389. continue;
  390. }
  391. }
  392. }
  393. else
  394. {
  395. CPDFDocument doc = CPDFDocument.InitWithFilePath(mergeObject.FilePath);
  396. if (doc == null)
  397. {
  398. AlertsMessage alertsMessage = new AlertsMessage();
  399. alertsMessage.ShowDialog("", "The file was not added successfully, please select the file again.", "OK");
  400. if (alertsMessage.result == ContentResult.Ok)
  401. {
  402. //PDF打开失败
  403. continue;
  404. }
  405. }
  406. VerifyPasswordResult condition = SecurityHelper.VerifyPasswordByPasswordKind(doc, EnumPasswordKind.StatusPermissionsPassword, dialogs);
  407. if (condition.IsDiscryptied)
  408. {
  409. if (condition.Password != null)
  410. {
  411. mergeObject.Password = condition.Password;
  412. doc.UnlockWithPassword(condition.Password);
  413. }
  414. }
  415. else
  416. {
  417. doc.Release();
  418. continue;
  419. }
  420. mergeObject.DocName = doc.FileName;
  421. mergeObject.DocPageCount = doc.PageCount.ToString() +" "+ App.MainPageLoader.GetString("Merge_ItemPages");
  422. mergeObject.SDKPageCount = doc.PageCount;
  423. mergeObject.DocSize = CommonHelper.GetFileSize(mergeObject.FilePath);
  424. //获取第一页缩略图
  425. CPDFPage page = doc.PageAtIndex(0);
  426. Size size = doc.GetPageSize(0);
  427. byte[] bmpData = new byte[(int)(size.Width * size.Height * 4)];
  428. WriteableBitmap WirteBitmap = new WriteableBitmap((int)size.Width, (int)size.Height, 96, 96, PixelFormats.Bgra32, null);
  429. page.RenderPageBitmap(0, 0, (int)size.Width, (int)size.Height, 0xFFFFFFFF, bmpData, 1);
  430. WirteBitmap.WritePixels(new Int32Rect(0, 0, (int)size.Width, (int)size.Height), bmpData, WirteBitmap.BackBufferStride, 0);
  431. WirteBitmap.Freeze();
  432. mergeObject.DocThumbnail = WirteBitmap;
  433. doc.Release();
  434. }
  435. MergeObjectlist.Add(mergeObject);
  436. }
  437. UpDataMergeObjectIndex();
  438. }
  439. #endregion
  440. }
  441. }