MainContentViewModel.cs 22 KB

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