MainContentViewModel.cs 22 KB

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