MainContentViewModel.cs 22 KB

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