MainContentViewModel.cs 22 KB

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