MainContentViewModel.cs 24 KB

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