MainContentViewModel.cs 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710
  1. using ComPDFKitViewer.PdfViewer;
  2. using Microsoft.Win32;
  3. using PDF_Master.CustomControl;
  4. using PDF_Master.EventAggregators;
  5. using PDF_Master.Views;
  6. using Prism.Commands;
  7. using Prism.Events;
  8. using Prism.Ioc;
  9. using Prism.Mvvm;
  10. using Prism.Regions;
  11. using Prism.Services.Dialogs;
  12. using System;
  13. using System.Collections.Generic;
  14. using System.Diagnostics;
  15. using System.Linq;
  16. using System.Text;
  17. using System.Threading.Tasks;
  18. using System.Windows;
  19. using PDF_Master.Model;
  20. using System.ComponentModel;
  21. using PDF_Master.Helper;
  22. using PDFSettings.Settings;
  23. using System.Drawing;
  24. using System.IO;
  25. using System.Drawing.Imaging;
  26. using ComPDFKit.PDFDocument;
  27. using static PDF_Master.Model.Dialog.ToolsDialogs.SaftyDialogs.DeleteSafetySettintgsModel;
  28. using PDF_Master.Model.Dialog.ToolsDialogs.SaftyDialogs;
  29. using PDF_Master.Properties;
  30. using WIA;
  31. namespace PDF_Master.ViewModels
  32. {
  33. public class MainContentViewModel : BindableBase, INavigationAware
  34. {
  35. #region 文案
  36. private string T_rename;
  37. public string T_Rename
  38. {
  39. get { return T_rename; }
  40. set
  41. {
  42. SetProperty(ref T_rename, value);
  43. }
  44. }
  45. private string T_floder;
  46. public string T_Floder
  47. {
  48. get { return T_floder; }
  49. set
  50. {
  51. SetProperty(ref T_floder, value);
  52. }
  53. }
  54. private string T_close;
  55. public string T_Close
  56. {
  57. get { return T_close; }
  58. set
  59. {
  60. SetProperty(ref T_close, value);
  61. }
  62. }
  63. private string T_closeAll;
  64. public string T_CloseAll
  65. {
  66. get { return T_closeAll; }
  67. set
  68. {
  69. SetProperty(ref T_closeAll, value);
  70. }
  71. }
  72. private void InitString()
  73. {
  74. FileName = App.MainPageLoader.GetString("MultipleTabs_Default");
  75. T_Rename = App.MainPageLoader.GetString("MultipleTabs_Rename");
  76. T_Floder = App.MainPageLoader.GetString("MultipleTabs_ Folder");
  77. T_Close = App.MainPageLoader.GetString("MultipleTabs_ Close");
  78. T_CloseAll = App.MainPageLoader.GetString("MultipleTabs_ CloseAll");
  79. }
  80. #endregion
  81. /// <summary>
  82. /// 是否处于阅读模式
  83. /// </summary>
  84. public bool IsBookMode = false;
  85. private string fileName = "Home";
  86. public string FileName
  87. {
  88. get { return fileName; }
  89. set
  90. {
  91. SetProperty(ref fileName, value);
  92. if (IsReNameTextShow == Visibility.Visible)
  93. {
  94. dorenameFile();
  95. }
  96. }
  97. }
  98. private string filePath;
  99. public string FilePath
  100. {
  101. get { return filePath; }
  102. set
  103. {
  104. SetProperty(ref filePath, value);
  105. if (!string.IsNullOrEmpty(filePath))
  106. {
  107. FileName = System.IO.Path.GetFileName(filePath);
  108. }
  109. }
  110. }
  111. private Visibility fileChanged = Visibility.Collapsed;
  112. public Visibility FileChanged
  113. {
  114. get { return fileChanged; }
  115. set { SetProperty(ref fileChanged, value); }
  116. }
  117. private bool isNewDocument = false;
  118. public CPDFViewer PDFViewer { get; set; }
  119. public DelegateCommand<object> CloseTab { get; set; }
  120. public DelegateCommand UnLoaded { get; set; }
  121. public DelegateCommand ShowInFolderCommand { get; set; }
  122. public DelegateCommand RenameCommand { get; set; }
  123. public ViewContentViewModel viewContentViewModel { get; set; }
  124. public MainWindowViewModel mainWindowViewModel { get; set; }
  125. public HomeContentViewModel homeContentViewModel { get; set; }
  126. private string regionName;
  127. public string MainContentRegionName
  128. {
  129. get { return regionName; }
  130. set { SetProperty(ref regionName, value); }
  131. }
  132. private bool isReNameEnable = false;
  133. /// <summary>
  134. /// 是否能够重命名
  135. /// </summary>
  136. public bool IsReNameEnable
  137. {
  138. get { return isReNameEnable; }
  139. set
  140. {
  141. SetProperty(ref isReNameEnable, value);
  142. }
  143. }
  144. private bool isShowInFolderEnable = false;
  145. /// <summary>
  146. /// 是否能够显示文件浏览器
  147. /// </summary>
  148. public bool IsShowInFolderEnable
  149. {
  150. get { return isShowInFolderEnable; }
  151. set
  152. {
  153. SetProperty(ref isShowInFolderEnable, value);
  154. }
  155. }
  156. private Visibility isRenameTextShow = Visibility.Collapsed;
  157. public Visibility IsReNameTextShow
  158. {
  159. get { return isRenameTextShow; }
  160. set
  161. {
  162. SetProperty(ref isRenameTextShow, value);
  163. }
  164. }
  165. public IRegionManager toolregion;
  166. public IEventAggregator eventer;
  167. public IContainerProvider container;
  168. public IDialogService dialogs;
  169. public MainContentViewModel(IRegionManager regionManager, IEventAggregator eventAggregator, IContainerProvider containerProvider, IDialogService dialogService)
  170. {
  171. toolregion = regionManager;
  172. eventer = eventAggregator;
  173. container = containerProvider;
  174. dialogs = dialogService;
  175. CloseTab = new DelegateCommand<object>(CloseTabItem);
  176. ShowInFolderCommand = new DelegateCommand(showInFolder);
  177. RenameCommand = new DelegateCommand(rename);
  178. UnLoaded = new DelegateCommand(unload);
  179. MainContentRegionName = Guid.NewGuid().ToString();
  180. InitString();
  181. }
  182. //关闭页签
  183. private void unload()
  184. {
  185. if (PDFViewer != null)
  186. {
  187. PDFViewer.CloseDocument();
  188. }
  189. }
  190. /// <summary>
  191. /// 执行重命名操作
  192. /// </summary>
  193. private void dorenameFile()
  194. {
  195. var folder = PDFViewer.Document.FilePath.Substring(0, PDFViewer.Document.FilePath.LastIndexOf("\\"));
  196. ////File.Replace(PDFViewer.Document.FilePath,Path.Combine(folder,FileName),Path.Combine(folder,"back.bak"),true);
  197. ///TODO:会被占用 无法操作
  198. IsReNameTextShow = Visibility.Collapsed;
  199. }
  200. /// <summary>
  201. /// 显示重命名文本框
  202. /// </summary>
  203. private void rename()
  204. {
  205. IsReNameTextShow = Visibility.Visible;
  206. }
  207. private void showInFolder()
  208. {
  209. if (!string.IsNullOrEmpty(PDFViewer.Document.FilePath))
  210. {
  211. CommonHelper.ShowFileBrowser(PDFViewer.Document.FilePath);
  212. }
  213. }
  214. private void CloseTabItem(object item)
  215. {
  216. if (item == null)
  217. {
  218. App.mainWindowViewModel?.CloseTabItem(mainWindowViewModel.SelectedItem);
  219. }
  220. else
  221. {
  222. App.mainWindowViewModel?.CloseTabItem(item);
  223. App.OpenedFileList.Remove(FilePath);
  224. }
  225. }
  226. /// <summary>
  227. /// 打开指定路径的PDF文件
  228. /// </summary>
  229. /// <param name="filePath"></param>
  230. public void OpenFile(string filePath, PasswordInfo passwordInfo = null)
  231. {
  232. var result = LoadFileFormPath(filePath);
  233. if (!result)
  234. {
  235. return;
  236. }
  237. FilePath = filePath;
  238. NavigateToViewContent();
  239. //检查是否是新文档
  240. OpenFileInfo isnew = SettingHelper.GetFileInfo(filePath);
  241. if (isnew == null)
  242. {
  243. isNewDocument = true;
  244. if (App.OpenedFileList.Contains(filePath) == false)
  245. {
  246. App.OpenedFileList.Add(filePath);
  247. }
  248. }
  249. //打开文件后,不管是新文件还是旧文件都需要更新排序
  250. SettingHelper.SortRecentOpenFiles(filePath);
  251. }
  252. /// <summary>
  253. /// 创建PDFviewer对象后导航到ViewContent
  254. /// </summary>
  255. private void NavigateToViewContent(PasswordInfo passwordInfo = null)
  256. {
  257. NavigationParameters parameters = new NavigationParameters {
  258. { ParameterNames.MainViewModel, this },
  259. { ParameterNames.PDFViewer,PDFViewer},
  260. { ParameterNames.PasswordInfo, passwordInfo}
  261. };
  262. toolregion.RequestNavigate(MainContentRegionName, "ViewContent", parameters);
  263. IsReNameEnable = true;
  264. if (!string.IsNullOrEmpty(PDFViewer.Document.FilePath))
  265. {
  266. IsShowInFolderEnable = true;
  267. }
  268. }
  269. /// <summary>
  270. /// 从文件路径创建PDFViewer对象,已包含文档解密逻辑
  271. /// </summary>
  272. /// <param name="path"></param>
  273. /// <returns></returns>
  274. private bool LoadFileFormPath(string path)
  275. {
  276. PDFViewer = new CPDFViewer();
  277. PDFViewer.InitDocument(path);
  278. PDFViewer.UndoManager.PropertyChanged += UndoManager_PropertyChanged;
  279. if (PDFViewer.Document == null)
  280. {
  281. //MessageBoxEx.Show(App.MainPageLoader.GetString("Main_OpenFileFailedWarning"));
  282. return false;
  283. }
  284. else
  285. {
  286. //解密逻辑调整到显示阅读页后,测试确认没问题后,删除下面的注释部分代码
  287. //VerifyPasswordResult result = SecurityHelper.VerifyPasswordByPasswordKind(PDFViewer.Document, EnumPasswordKind.StatusOpenPassword, dialogs);
  288. //if (result.IsDiscryptied)
  289. //{
  290. // if (result.Password != null)
  291. // {
  292. // string filePath = PDFViewer.Document.FilePath;
  293. // PDFViewer.Document.UnlockWithPassword(result.Password);
  294. // PDFViewer.Tag = result.Password;
  295. // }
  296. // ///TODO:
  297. // ///此处填入需要执行的代码
  298. //}
  299. //if (result.IsDiscryptied == false)
  300. //{
  301. // //未成功解密文档时,释放Document对象,返回
  302. // PDFViewer.Document.Release();
  303. // return false;
  304. //}
  305. }
  306. //PDFViewer.Load();
  307. //PDFViewer.SetFormFieldHighlight(Settings.Default.AppProperties.InitialVIew.HighlightLink);
  308. //PDFViewer.SetBackgroundBrush(new System.Windows.Media.SolidColorBrush(Settings.Default.AppProperties.InitialVIew.BackGround));
  309. if (App.mainWindowViewModel != null)
  310. {
  311. App.mainWindowViewModel.CurrentPDFViewer = PDFViewer;
  312. }
  313. return true;
  314. }
  315. /// <summary>
  316. /// 创建文件,路径为空时表示创建空白文档
  317. /// 否则表示从图片路径创建PDf
  318. /// </summary>
  319. /// <param name="imagePath"></param>
  320. /// <returns></returns>
  321. public bool CreateFile(string imagePath = null)
  322. {
  323. PDFViewer = new CPDFViewer();
  324. PDFViewer.CreateDocument();
  325. PDFViewer.UndoManager.PropertyChanged += UndoManager_PropertyChanged;
  326. if (PDFViewer.Document == null)
  327. {
  328. AlertsMessage alertsMessage = new AlertsMessage();
  329. alertsMessage.ShowDialog("", "创建文件失败.", "OK");
  330. return false;
  331. }
  332. if (string.IsNullOrEmpty(imagePath))
  333. {
  334. FileName = "Blank Page.pdf";
  335. //默认插入595*842 大小的页面
  336. PDFViewer.Document.InsertPage(0, 595, 842, null);
  337. }
  338. else
  339. {
  340. FileName = imagePath.Substring(imagePath.LastIndexOf("\\") + 1, imagePath.LastIndexOf(".") - imagePath.LastIndexOf("\\") - 1) + ".pdf";
  341. Bitmap pic = new Bitmap(imagePath);
  342. int width = pic.Size.Width;
  343. int height = pic.Size.Height;
  344. string ex = System.IO.Path.GetExtension(imagePath);
  345. //其他格式或者名称中含空格的图片 在本地先转存一下
  346. if ((ex != ".jpg" && ex != ".jpeg") || !Uri.IsWellFormedUriString(imagePath, UriKind.Absolute))
  347. {
  348. //将其他格式图片转换成jpg
  349. string folderPath = Path.GetTempPath();
  350. if (File.Exists(folderPath))
  351. {
  352. File.Delete(folderPath);
  353. }
  354. DirectoryInfo tempfolder = new DirectoryInfo(folderPath);
  355. if (!tempfolder.Exists)
  356. {
  357. tempfolder.Create();
  358. }
  359. string targetPath = System.IO.Path.Combine(folderPath, Guid.NewGuid().ToString());
  360. imagePath = targetPath;
  361. pic.Save(targetPath, ImageFormat.Jpeg);
  362. }
  363. pic.Dispose();
  364. var result = PDFViewer.Document.InsertPage(0, width, height, imagePath);
  365. if (!result)
  366. {
  367. AlertsMessage alertsMessage = new AlertsMessage();
  368. alertsMessage.ShowDialog("", "创建文件失败.", "OK");
  369. return false;
  370. }
  371. }
  372. PDFViewer.UndoManager.CanSave = true;
  373. FileChanged = Visibility.Visible;
  374. NavigateToViewContent();
  375. return true;
  376. }
  377. /// <summary>
  378. /// 从office文件转换成PDF
  379. /// </summary>
  380. /// <param name="sourcepath"></param>
  381. /// <returns></returns>
  382. public async Task<bool> CreateFileFromOffice(string sourcepath, Microsoft.Office.Interop.Word.WdPaperSize paperSize = Microsoft.Office.Interop.Word.WdPaperSize.wdPaperA4, double margin = 0)
  383. {
  384. try
  385. {
  386. //生成存放临时pdf的临时文件夹
  387. string folderPath = Path.GetTempPath();
  388. if (File.Exists(folderPath))
  389. {
  390. File.Delete(folderPath);
  391. }
  392. DirectoryInfo tempfolder = new DirectoryInfo(folderPath);
  393. if (!tempfolder.Exists)
  394. {
  395. tempfolder.Create();
  396. }
  397. string targetPath = System.IO.Path.Combine(folderPath, Guid.NewGuid().ToString() + ".pdf");
  398. string ex = System.IO.Path.GetExtension(sourcepath).ToLower();
  399. await Task.Delay(10);
  400. switch (ex)
  401. {
  402. case ".doc":
  403. case ".docx":
  404. case "docm":
  405. case ".dot":
  406. case ".dotx":
  407. case ".dotm":
  408. case ".txt":
  409. case ".html":
  410. await Task.Run(() =>
  411. {
  412. Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
  413. Microsoft.Office.Interop.Word.Document document = null;
  414. word.Visible = false;
  415. word.ShowWindowsInTaskbar = true;
  416. document = word.Documents.Open(sourcepath);
  417. var page = document.PageSetup;
  418. page.PaperSize = paperSize;
  419. if (margin > 0)
  420. {
  421. page.LeftMargin = page.TopMargin = page.RightMargin = page.BottomMargin = (float)margin;
  422. }
  423. document?.ExportAsFixedFormat(targetPath, Microsoft.Office.Interop.Word.WdExportFormat.wdExportFormatPDF);
  424. document?.Close(false);
  425. if (word != null)
  426. {
  427. word.NormalTemplate.Saved = true;
  428. word.Quit();
  429. }
  430. });
  431. break;
  432. case ".xls":
  433. case ".xlsx":
  434. case ".xlsm":
  435. case ".xlsb":
  436. case ".xlam":
  437. case ".xltx":
  438. case ".xlt":
  439. await Task.Run(() =>
  440. {
  441. Microsoft.Office.Interop.Excel.Application excele = new Microsoft.Office.Interop.Excel.Application();
  442. Microsoft.Office.Interop.Excel.Workbook workbook = null;
  443. excele.Visible = false;
  444. try
  445. {
  446. workbook = excele.Workbooks.Open(sourcepath);
  447. }
  448. catch (Exception e)
  449. {
  450. workbook = excele.Workbooks.Open(sourcepath, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "t", false, false, 0, true, 1, Microsoft.Office.Interop.Excel.XlCorruptLoad.xlRepairFile);
  451. }
  452. workbook?.ExportAsFixedFormat(Microsoft.Office.Interop.Excel.XlFixedFormatType.xlTypePDF, targetPath);
  453. workbook?.Close();
  454. excele?.Quit();
  455. });
  456. break;
  457. case ".ppt":
  458. case ".pptx":
  459. case ".pptm":
  460. case ".pptsx":
  461. case ".pps":
  462. case ".pptsm":
  463. case ".pot":
  464. case ".potm":
  465. await Task.Run(() =>
  466. {
  467. Microsoft.Office.Interop.PowerPoint.Application ppt = new Microsoft.Office.Interop.PowerPoint.Application();
  468. Microsoft.Office.Interop.PowerPoint.Presentation presentation = null;
  469. ppt.Visible = Microsoft.Office.Core.MsoTriState.msoCTrue;
  470. presentation = ppt.Presentations.Open(sourcepath);
  471. presentation.ExportAsFixedFormat(targetPath, Microsoft.Office.Interop.PowerPoint.PpFixedFormatType.ppFixedFormatTypePDF);
  472. presentation?.Close();
  473. ppt?.Quit();
  474. });
  475. break;
  476. }
  477. PDFViewer = new CPDFViewer();
  478. PDFViewer.CreateDocument();
  479. if (PDFViewer.Document == null)
  480. {
  481. AlertsMessage alertsMessage = new AlertsMessage();
  482. alertsMessage.ShowDialog("", "创建PDF失败", "OK");
  483. return false;
  484. }
  485. FileName = sourcepath.Substring(sourcepath.LastIndexOf("\\") + 1, sourcepath.LastIndexOf(".") - sourcepath.LastIndexOf("\\") - 1) + ".pdf";
  486. var tempdoc = CPDFDocument.InitWithFilePath(targetPath);
  487. if (tempdoc == null)
  488. {
  489. AlertsMessage alertsMessage = new AlertsMessage();
  490. alertsMessage.ShowDialog("", "创建PDF失败", "OK");
  491. return false;
  492. }
  493. PDFViewer.Document.ImportPages(tempdoc, "");
  494. PDFViewer.UndoManager.CanSave = true;
  495. FileChanged = Visibility.Visible;
  496. await System.Windows.Application.Current.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Send, new Action(() =>
  497. {
  498. NavigateToViewContent();
  499. }));
  500. return true;
  501. }
  502. catch (Exception ex)
  503. {
  504. string str = "没有安装";
  505. //判断是否有安装office软件
  506. var officeType = Type.GetTypeFromProgID("Word.Application");
  507. if (officeType == null)
  508. {
  509. str += "Word;";
  510. }
  511. officeType = Type.GetTypeFromProgID("Excel.Application");
  512. if (officeType == null)
  513. {
  514. str += "Excel;";
  515. }
  516. officeType = Type.GetTypeFromProgID("Powerpoint.Application");
  517. if (officeType == null)
  518. {
  519. str += "Excel;";
  520. }
  521. AlertsMessage alertsMessage = new AlertsMessage();
  522. if (str != "没有安装")
  523. {
  524. alertsMessage.ShowDialog("", "没有安装Office", "OK");
  525. }
  526. else
  527. {
  528. alertsMessage.ShowDialog("", "创建PDF失败", "OK");
  529. }
  530. return false;
  531. }
  532. }
  533. private void UndoManager_PropertyChanged(object sender, PropertyChangedEventArgs e)
  534. {
  535. if (e.PropertyName == "CanSave")
  536. {
  537. if (PDFViewer.UndoManager.CanSave)
  538. {
  539. FileChanged = Visibility.Visible;
  540. }
  541. else
  542. {
  543. FileChanged = Visibility.Collapsed;
  544. }
  545. if (!string.IsNullOrEmpty(PDFViewer.Document.FileName))
  546. {
  547. FileName = PDFViewer.Document.FileName;
  548. }
  549. }
  550. }
  551. #region Navigation
  552. public async void OnNavigatedTo(NavigationContext navigationContext)
  553. {
  554. mainWindowViewModel = App.mainWindowViewModel;
  555. //因为是异步打开多个文件,需要先显示Home界面
  556. NavigationParameters parameters = new NavigationParameters();
  557. parameters.Add(ParameterNames.MainViewModel, this);
  558. if (toolregion.Regions.ContainsRegionWithName(MainContentRegionName))
  559. {
  560. toolregion.RequestNavigate(MainContentRegionName, "HomeContent", parameters);
  561. }
  562. //常规加载首页的情况
  563. if (navigationContext.Parameters.Count <= 0)
  564. {
  565. return;
  566. }
  567. //一次打开多个文件的情况
  568. var filepath = navigationContext.Parameters[ParameterNames.FilePath].ToString();
  569. if (filepath != null)
  570. {
  571. bool result = true;
  572. if (System.IO.Path.GetExtension(filepath.ToString()).ToLower() == ".pdf")
  573. {
  574. OpenFile(filepath.ToString());
  575. }
  576. else if (Properties.Resources.imageex.Contains(System.IO.Path.GetExtension(filepath).ToLower()))
  577. {
  578. //图片转PDF
  579. result = CreateFile(filepath);
  580. }
  581. else
  582. {
  583. result = await CreateFileFromOffice(filepath);
  584. }
  585. if (!result)
  586. {
  587. mainWindowViewModel.CloseTabItem(mainWindowViewModel.SelectedItem);
  588. return;
  589. }
  590. if (!App.OpenedFileList.Contains(filepath))
  591. {
  592. //更新已打开的文件记录
  593. App.OpenedFileList.Add(filepath);
  594. }
  595. }
  596. }
  597. public bool IsNavigationTarget(NavigationContext navigationContext)
  598. {
  599. return false;
  600. }
  601. public void OnNavigatedFrom(NavigationContext navigationContext)
  602. {
  603. }
  604. #endregion Navigation
  605. }
  606. }