MergeDialogViewModel.cs 18 KB

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