MainContentViewModel.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624
  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. PDFViewer.Tag = result.Password;
  222. }
  223. ///TODO:
  224. ///此处填入需要执行的代码
  225. }
  226. if (result.IsDiscryptied == false)
  227. {
  228. //未成功解密文档时,释放Document对象,返回
  229. PDFViewer.Document.Release();
  230. return false;
  231. }
  232. }
  233. PDFViewer.Load();
  234. if (App.mainWindowViewModel != null)
  235. {
  236. App.mainWindowViewModel.CurrentPDFViewer = PDFViewer;
  237. }
  238. App.OpenedFileList.Add(path);
  239. return true;
  240. }
  241. /// <summary>
  242. /// 创建文件,路径为空时表示创建空白文档
  243. /// 否则表示从图片路径创建PDf
  244. /// </summary>
  245. /// <param name="imagePath"></param>
  246. /// <returns></returns>
  247. public bool CreateFile(string imagePath = null)
  248. {
  249. PDFViewer = new CPDFViewer();
  250. PDFViewer.CreateDocument();
  251. PDFViewer.UndoManager.PropertyChanged += UndoManager_PropertyChanged;
  252. if (PDFViewer.Document == null)
  253. {
  254. AlertsMessage alertsMessage = new AlertsMessage();
  255. alertsMessage.ShowDialog("", "创建文件失败.", "OK");
  256. return false;
  257. }
  258. if (string.IsNullOrEmpty(imagePath))
  259. {
  260. FileName = "Blank Page.pdf";
  261. //默认插入595*842 大小的页面
  262. PDFViewer.Document.InsertPage(0, 595, 842, null);
  263. }
  264. else
  265. {
  266. FileName = imagePath.Substring(imagePath.LastIndexOf("\\") + 1, imagePath.LastIndexOf(".") - imagePath.LastIndexOf("\\") - 1) + ".pdf";
  267. Bitmap pic = new Bitmap(imagePath);
  268. int width = pic.Size.Width;
  269. int height = pic.Size.Height;
  270. string ex = System.IO.Path.GetExtension(imagePath);
  271. //其他格式或者名称中含空格的图片 在本地先转存一下
  272. if ((ex != ".jpg" && ex != ".jpeg") || !Uri.IsWellFormedUriString(imagePath, UriKind.Absolute))
  273. {
  274. //将其他格式图片转换成jpg
  275. string folderPath = Path.GetTempPath();
  276. if (File.Exists(folderPath))
  277. {
  278. File.Delete(folderPath);
  279. }
  280. DirectoryInfo tempfolder = new DirectoryInfo(folderPath);
  281. if (!tempfolder.Exists)
  282. {
  283. tempfolder.Create();
  284. }
  285. string targetPath = System.IO.Path.Combine(folderPath, Guid.NewGuid().ToString());
  286. imagePath = targetPath;
  287. pic.Save(targetPath, ImageFormat.Jpeg);
  288. }
  289. pic.Dispose();
  290. var result = PDFViewer.Document.InsertPage(0, width, height, imagePath);
  291. if (!result)
  292. {
  293. AlertsMessage alertsMessage = new AlertsMessage();
  294. alertsMessage.ShowDialog("", "创建文件失败.", "OK");
  295. return false;
  296. }
  297. }
  298. //设置背景色
  299. ////PDFViewer.SetBackgroundBrush(new SolidColorBrush((Color)System.Windows.Media.ColorConverter.ConvertFromString(Settings.Default.AppProperties.InitialVIew.Background)));
  300. PDFViewer.Load();
  301. PDFViewer.UndoManager.CanSave = true;
  302. FileChanged = Visibility.Visible;
  303. PDFViewer.SetFormFieldHighlight(true);
  304. NavigateToViewContent();
  305. return true;
  306. }
  307. /// <summary>
  308. /// 从office文件转换成PDF
  309. /// </summary>
  310. /// <param name="sourcepath"></param>
  311. /// <returns></returns>
  312. public async Task<bool> CreateFileFromOffice(string sourcepath, Microsoft.Office.Interop.Word.WdPaperSize paperSize = Microsoft.Office.Interop.Word.WdPaperSize.wdPaperA4, double margin = 0)
  313. {
  314. try
  315. {
  316. //生成存放临时pdf的临时文件夹
  317. string folderPath = Path.GetTempPath();
  318. if (File.Exists(folderPath))
  319. {
  320. File.Delete(folderPath);
  321. }
  322. DirectoryInfo tempfolder = new DirectoryInfo(folderPath);
  323. if (!tempfolder.Exists)
  324. {
  325. tempfolder.Create();
  326. }
  327. string targetPath = System.IO.Path.Combine(folderPath, Guid.NewGuid().ToString() + ".pdf");
  328. string ex = System.IO.Path.GetExtension(sourcepath).ToLower();
  329. await Task.Delay(10);
  330. switch (ex)
  331. {
  332. case ".doc":
  333. case ".docx":
  334. case "docm":
  335. case ".dot":
  336. case ".dotx":
  337. case ".dotm":
  338. case ".txt":
  339. case ".html":
  340. await Task.Run(() =>
  341. {
  342. Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
  343. Microsoft.Office.Interop.Word.Document document = null;
  344. word.Visible = false;
  345. word.ShowWindowsInTaskbar = true;
  346. document = word.Documents.Open(sourcepath);
  347. var page = document.PageSetup;
  348. page.PaperSize = paperSize;
  349. if (margin > 0)
  350. {
  351. page.LeftMargin = page.TopMargin = page.RightMargin = page.BottomMargin = (float)margin;
  352. }
  353. document?.ExportAsFixedFormat(targetPath, Microsoft.Office.Interop.Word.WdExportFormat.wdExportFormatPDF);
  354. document?.Close(false);
  355. if (word != null)
  356. {
  357. word.NormalTemplate.Saved = true;
  358. word.Quit();
  359. }
  360. });
  361. break;
  362. case ".xls":
  363. case ".xlsx":
  364. case ".xlsm":
  365. case ".xlsb":
  366. case ".xlam":
  367. case ".xltx":
  368. case ".xlt":
  369. await Task.Run(() =>
  370. {
  371. Microsoft.Office.Interop.Excel.Application excele = new Microsoft.Office.Interop.Excel.Application();
  372. Microsoft.Office.Interop.Excel.Workbook workbook = null;
  373. excele.Visible = false;
  374. try
  375. {
  376. workbook = excele.Workbooks.Open(sourcepath);
  377. }
  378. catch (Exception e)
  379. {
  380. 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);
  381. }
  382. workbook?.ExportAsFixedFormat(Microsoft.Office.Interop.Excel.XlFixedFormatType.xlTypePDF, targetPath);
  383. workbook?.Close();
  384. excele?.Quit();
  385. });
  386. break;
  387. case ".ppt":
  388. case ".pptx":
  389. case ".pptm":
  390. case ".pptsx":
  391. case ".pps":
  392. case ".pptsm":
  393. case ".pot":
  394. case ".potm":
  395. await Task.Run(() =>
  396. {
  397. Microsoft.Office.Interop.PowerPoint.Application ppt = new Microsoft.Office.Interop.PowerPoint.Application();
  398. Microsoft.Office.Interop.PowerPoint.Presentation presentation = null;
  399. ppt.Visible = Microsoft.Office.Core.MsoTriState.msoCTrue;
  400. presentation = ppt.Presentations.Open(sourcepath);
  401. presentation.ExportAsFixedFormat(targetPath, Microsoft.Office.Interop.PowerPoint.PpFixedFormatType.ppFixedFormatTypePDF);
  402. presentation?.Close();
  403. ppt?.Quit();
  404. });
  405. break;
  406. }
  407. PDFViewer = new CPDFViewer();
  408. PDFViewer.CreateDocument();
  409. if (PDFViewer.Document == null)
  410. {
  411. AlertsMessage alertsMessage = new AlertsMessage();
  412. alertsMessage.ShowDialog("", "创建PDF失败", "OK");
  413. return false;
  414. }
  415. FileName = sourcepath.Substring(sourcepath.LastIndexOf("\\") + 1, sourcepath.LastIndexOf(".") - sourcepath.LastIndexOf("\\") - 1) + ".pdf";
  416. var tempdoc = CPDFDocument.InitWithFilePath(targetPath);
  417. if (tempdoc == null)
  418. {
  419. AlertsMessage alertsMessage = new AlertsMessage();
  420. alertsMessage.ShowDialog("", "创建PDF失败", "OK");
  421. return false;
  422. }
  423. PDFViewer.Document.ImportPages(tempdoc, "");
  424. //PDFViewer.SetBackgroundBrush(new SolidColorBrush((Color)System.Windows.Media.ColorConverter.ConvertFromString(Settings.Default.AppProperties.InitialVIew.Background)));
  425. PDFViewer.Load();
  426. PDFViewer.UndoManager.CanSave = true;
  427. FileChanged = Visibility.Visible;
  428. PDFViewer.SetFormFieldHighlight(true);
  429. await System.Windows.Application.Current.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Send, new Action(() =>
  430. {
  431. NavigateToViewContent();
  432. }));
  433. return true;
  434. }
  435. catch (Exception ex)
  436. {
  437. string str = "没有安装";
  438. //判断是否有安装office软件
  439. var officeType = Type.GetTypeFromProgID("Word.Application");
  440. if (officeType == null)
  441. {
  442. str += "Word;";
  443. }
  444. officeType = Type.GetTypeFromProgID("Excel.Application");
  445. if (officeType == null)
  446. {
  447. str += "Excel;";
  448. }
  449. officeType = Type.GetTypeFromProgID("Powerpoint.Application");
  450. if (officeType == null)
  451. {
  452. str += "Excel;";
  453. }
  454. AlertsMessage alertsMessage = new AlertsMessage();
  455. if (str != "没有安装")
  456. {
  457. alertsMessage.ShowDialog("", "没有安装Office", "OK");
  458. }
  459. else
  460. {
  461. alertsMessage.ShowDialog("", "创建PDF失败", "OK");
  462. }
  463. return false;
  464. }
  465. }
  466. private void UndoManager_PropertyChanged(object sender, PropertyChangedEventArgs e)
  467. {
  468. if (e.PropertyName == "CanSave")
  469. {
  470. if (PDFViewer.UndoManager.CanSave)
  471. {
  472. FileChanged = Visibility.Visible;
  473. }
  474. else
  475. {
  476. FileChanged = Visibility.Collapsed;
  477. }
  478. if (!string.IsNullOrEmpty(PDFViewer.Document.FileName))
  479. {
  480. FileName = PDFViewer.Document.FileName;
  481. }
  482. }
  483. }
  484. #region Navigation
  485. public async void OnNavigatedTo(NavigationContext navigationContext)
  486. {
  487. mainWindowViewModel = App.mainWindowViewModel;
  488. //因为是异步打开多个文件,需要先显示Home界面
  489. NavigationParameters parameters = new NavigationParameters();
  490. parameters.Add(ParameterNames.MainViewModel, this);
  491. if (toolregion.Regions.ContainsRegionWithName(MainContentRegionName))
  492. {
  493. toolregion.RequestNavigate(MainContentRegionName, "HomeContent", parameters);
  494. }
  495. //常规加载首页的情况
  496. if (navigationContext.Parameters.Count <= 0)
  497. {
  498. return;
  499. }
  500. //一次打开多个文件的情况
  501. var filepath = navigationContext.Parameters[ParameterNames.FilePath].ToString();
  502. if (filepath != null)
  503. {
  504. bool result = true;
  505. if (System.IO.Path.GetExtension(filepath.ToString()).ToLower() == ".pdf")
  506. {
  507. OpenFile(filepath.ToString());
  508. }
  509. else if (Properties.Resources.imageex.Contains(System.IO.Path.GetExtension(filepath).ToLower()))
  510. {
  511. //图片转PDF
  512. result = CreateFile(filepath);
  513. }
  514. else
  515. {
  516. result = await CreateFileFromOffice(filepath);
  517. }
  518. if (!result)
  519. {
  520. mainWindowViewModel.CloseTabItem(mainWindowViewModel.SelectedItem);
  521. return;
  522. }
  523. //更新已打开的文件记录
  524. App.OpenedFileList.Add(filepath);
  525. }
  526. }
  527. public bool IsNavigationTarget(NavigationContext navigationContext)
  528. {
  529. return false;
  530. }
  531. public void OnNavigatedFrom(NavigationContext navigationContext)
  532. {
  533. }
  534. #endregion
  535. }
  536. }