MainContentViewModel.cs 22 KB

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