MergeDialogViewModel.cs 18 KB

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