MainContentViewModel.cs 22 KB

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