MainContentViewModel.cs 22 KB

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