MainContentViewModel.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674
  1. using ComPDFKitViewer.PdfViewer;
  2. using Microsoft.Win32;
  3. using PDF_Master.CustomControl;
  4. using PDF_Master.EventAggregators;
  5. using PDF_Master.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_Master.Model;
  20. using System.ComponentModel;
  21. using PDF_Master.Helper;
  22. using PDFSettings;
  23. using System.Drawing;
  24. using System.IO;
  25. using System.Drawing.Imaging;
  26. using ComPDFKit.PDFDocument;
  27. using static PDF_Master.Model.Dialog.ToolsDialogs.SaftyDialogs.DeleteSafetySettintgsModel;
  28. using PDF_Master.Model.Dialog.ToolsDialogs.SaftyDialogs;
  29. using PDF_Master.Properties;
  30. using WIA;
  31. namespace PDF_Master.ViewModels
  32. {
  33. public class MainContentViewModel : BindableBase, INavigationAware
  34. {
  35. #region 文案
  36. private string T_rename;
  37. public string T_Rename
  38. {
  39. get { return T_rename; }
  40. set
  41. {
  42. SetProperty(ref T_rename, value);
  43. }
  44. }
  45. private string T_floder;
  46. public string T_Floder
  47. {
  48. get { return T_floder; }
  49. set
  50. {
  51. SetProperty(ref T_floder, value);
  52. }
  53. }
  54. private string T_close;
  55. public string T_Close
  56. {
  57. get { return T_close; }
  58. set
  59. {
  60. SetProperty(ref T_close, value);
  61. }
  62. }
  63. private string T_closeAll;
  64. public string T_CloseAll
  65. {
  66. get { return T_closeAll; }
  67. set
  68. {
  69. SetProperty(ref T_closeAll, value);
  70. }
  71. }
  72. private void InitString()
  73. {
  74. FileName = App.MainPageLoader.GetString("MultipleTabs_Default");
  75. T_Rename = App.MainPageLoader.GetString("MultipleTabs_Rename");
  76. T_Floder = App.MainPageLoader.GetString("MultipleTabs_ Folder");
  77. T_Close = App.MainPageLoader.GetString("MultipleTabs_ Close");
  78. T_CloseAll = App.MainPageLoader.GetString("MultipleTabs_ CloseAll");
  79. }
  80. #endregion
  81. /// <summary>
  82. /// 是否使用了高级功能
  83. /// </summary>
  84. public bool IsUsedVIP = false;
  85. /// <summary>
  86. /// 是否处于阅读模式
  87. /// </summary>
  88. public bool IsBookMode = false;
  89. private string fileName = "Home";
  90. public string FileName
  91. {
  92. get { return fileName; }
  93. set
  94. {
  95. SetProperty(ref fileName, value);
  96. if (IsReNameTextShow == Visibility.Visible)
  97. {
  98. dorenameFile();
  99. }
  100. }
  101. }
  102. private string filePath;
  103. public string FilePath
  104. {
  105. get { return filePath; }
  106. set
  107. {
  108. SetProperty(ref filePath, value);
  109. if (!string.IsNullOrEmpty(filePath))
  110. {
  111. FileName = System.IO.Path.GetFileName(filePath);
  112. }
  113. }
  114. }
  115. private Visibility fileChanged = Visibility.Collapsed;
  116. public Visibility FileChanged
  117. {
  118. get { return fileChanged; }
  119. set { SetProperty(ref fileChanged, value); }
  120. }
  121. public CPDFViewer PDFViewer { get; set; }
  122. public DelegateCommand<object> CloseTab { get; set; }
  123. public DelegateCommand UnLoaded { get; set; }
  124. public DelegateCommand ShowInFolderCommand { get; set; }
  125. public DelegateCommand RenameCommand { get; set; }
  126. public ViewContentViewModel viewContentViewModel { get; set; }
  127. public MainWindowViewModel mainWindowViewModel { get; set; }
  128. public HomeContentViewModel homeContentViewModel { get; set; }
  129. private string regionName;
  130. public string MainContentRegionName
  131. {
  132. get { return regionName; }
  133. set { SetProperty(ref regionName, value); }
  134. }
  135. private bool isReNameEnable = false;
  136. /// <summary>
  137. /// 是否能够重命名
  138. /// </summary>
  139. public bool IsReNameEnable
  140. {
  141. get { return isReNameEnable; }
  142. set
  143. {
  144. SetProperty(ref isReNameEnable, value);
  145. }
  146. }
  147. private bool isShowInFolderEnable = false;
  148. /// <summary>
  149. /// 是否能够显示文件浏览器
  150. /// </summary>
  151. public bool IsShowInFolderEnable
  152. {
  153. get { return isShowInFolderEnable; }
  154. set
  155. {
  156. SetProperty(ref isShowInFolderEnable, value);
  157. }
  158. }
  159. private Visibility isRenameTextShow = Visibility.Collapsed;
  160. public Visibility IsReNameTextShow
  161. {
  162. get { return isRenameTextShow; }
  163. set
  164. {
  165. SetProperty(ref isRenameTextShow, value);
  166. }
  167. }
  168. private bool newFile = false;
  169. /// <summary>
  170. /// 是否是新建的文档
  171. /// </summary>
  172. public bool NewFile
  173. {
  174. get { return newFile; }
  175. set
  176. {
  177. SetProperty(ref newFile, value);
  178. if (!value)
  179. {
  180. IsShowInFolderEnable = true;
  181. }
  182. }
  183. }
  184. public IRegionManager toolregion;
  185. public IEventAggregator eventer;
  186. public IContainerProvider container;
  187. public IDialogService dialogs;
  188. public MainContentViewModel(IRegionManager regionManager, IEventAggregator eventAggregator, IContainerProvider containerProvider, IDialogService dialogService)
  189. {
  190. toolregion = regionManager;
  191. eventer = eventAggregator;
  192. container = containerProvider;
  193. dialogs = dialogService;
  194. CloseTab = new DelegateCommand<object>(CloseTabItem);
  195. ShowInFolderCommand = new DelegateCommand(showInFolder);
  196. RenameCommand = new DelegateCommand(rename);
  197. UnLoaded = new DelegateCommand(unload);
  198. MainContentRegionName = Guid.NewGuid().ToString();
  199. InitString();
  200. }
  201. //关闭页签
  202. //清除文件记录,释放Document对象
  203. private void unload()
  204. {
  205. if (PDFViewer != null)
  206. {
  207. App.OpenedFileList.Remove(PDFViewer.Document?.FilePath);
  208. PDFViewer.CloseDocument();
  209. }
  210. }
  211. /// <summary>
  212. /// 执行重命名操作
  213. /// </summary>
  214. private void dorenameFile()
  215. {
  216. var folder = PDFViewer.Document.FilePath.Substring(0, PDFViewer.Document.FilePath.LastIndexOf("\\"));
  217. ////File.Replace(PDFViewer.Document.FilePath,Path.Combine(folder,FileName),Path.Combine(folder,"back.bak"),true);
  218. ///TODO:会被占用 无法操作
  219. IsReNameTextShow = Visibility.Collapsed;
  220. }
  221. /// <summary>
  222. /// 显示重命名文本框
  223. /// </summary>
  224. private void rename()
  225. {
  226. IsReNameTextShow = Visibility.Visible;
  227. }
  228. private void showInFolder()
  229. {
  230. if (!string.IsNullOrEmpty(PDFViewer.Document.FilePath))
  231. {
  232. CommonHelper.ShowFileBrowser(PDFViewer.Document.FilePath);
  233. }
  234. }
  235. private void CloseTabItem(object item)
  236. {
  237. if (item == null)
  238. {
  239. App.mainWindowViewModel?.CloseTabItem(mainWindowViewModel.SelectedItem);
  240. }
  241. else
  242. {
  243. App.mainWindowViewModel?.CloseTabItem(item);
  244. App.OpenedFileList.Remove(FilePath);
  245. if (NewFile)
  246. {
  247. //新文档 关闭文档后 及时清空临时缓存
  248. DirectoryInfo directory = new DirectoryInfo(CacheFilePath.Instance.CreatedFilePath);
  249. FileInfo fileInfo = new FileInfo(FilePath);
  250. if (directory.GetFiles().ToList().Contains(fileInfo))
  251. {
  252. File.Delete(FilePath);
  253. }
  254. }
  255. }
  256. }
  257. /// <summary>
  258. /// 打开指定路径的PDF文件
  259. /// </summary>
  260. /// <param name="filePath"></param>
  261. public void OpenFile(string filePath, PasswordInfo passwordInfo = null)
  262. {
  263. var result = LoadFileFormPath(filePath);
  264. if (!result)
  265. {
  266. AlertsMessage alertsMessage = new AlertsMessage();
  267. alertsMessage.ShowDialog("",App.MainPageLoader.GetString("Main_OpenFileFailedWarning"), App.ServiceLoader.GetString("Text_ok"));
  268. return;
  269. }
  270. FilePath = filePath;
  271. NavigateToViewContent();
  272. //检查是否是新文档
  273. OpenFileInfo isnew = SettingHelper.GetFileInfo(filePath);
  274. if (isnew == null)
  275. {
  276. if (App.OpenedFileList.Contains(filePath) == false)
  277. {
  278. App.OpenedFileList.Add(filePath);
  279. }
  280. }
  281. //打开文件后,不管是新文件还是旧文件都需要更新排序
  282. SettingHelper.SortRecentOpenFiles(filePath);
  283. }
  284. /// <summary>
  285. /// 创建PDFviewer对象后导航到ViewContent
  286. /// </summary>
  287. private void NavigateToViewContent(PasswordInfo passwordInfo = null)
  288. {
  289. NavigationParameters parameters = new NavigationParameters {
  290. { ParameterNames.MainViewModel, this },
  291. { ParameterNames.PDFViewer,PDFViewer},
  292. { ParameterNames.PasswordInfo, passwordInfo}
  293. };
  294. toolregion.RequestNavigate(MainContentRegionName, "ViewContent", parameters);
  295. IsReNameEnable = true;
  296. if (!string.IsNullOrEmpty(PDFViewer.Document.FilePath) && !NewFile)
  297. {
  298. IsShowInFolderEnable = true;
  299. }
  300. }
  301. /// <summary>
  302. /// 从文件路径创建PDFViewer对象,已包含文档解密逻辑
  303. /// </summary>
  304. /// <param name="path"></param>
  305. /// <returns></returns>
  306. private bool LoadFileFormPath(string path)
  307. {
  308. PDFViewer = new CPDFViewer();
  309. PDFViewer.InitDocument(path);
  310. PDFViewer.UndoManager.PropertyChanged += UndoManager_PropertyChanged;
  311. if (PDFViewer.Document == null)
  312. {
  313. //MessageBoxEx.Show(App.MainPageLoader.GetString("Main_OpenFileFailedWarning"));
  314. return false;
  315. }
  316. else
  317. {
  318. //解密逻辑调整到显示阅读页后,测试确认没问题后,删除下面的注释部分代码
  319. //VerifyPasswordResult result = SecurityHelper.VerifyPasswordByPasswordKind(PDFViewer.Document, EnumPasswordKind.StatusOpenPassword, dialogs);
  320. //if (result.IsDiscryptied)
  321. //{
  322. // if (result.Password != null)
  323. // {
  324. // string filePath = PDFViewer.Document.FilePath;
  325. // PDFViewer.Document.UnlockWithPassword(result.Password);
  326. // PDFViewer.Tag = result.Password;
  327. // }
  328. // ///TODO:
  329. // ///此处填入需要执行的代码
  330. //}
  331. //if (result.IsDiscryptied == false)
  332. //{
  333. // //未成功解密文档时,释放Document对象,返回
  334. // PDFViewer.Document.Release();
  335. // return false;
  336. //}
  337. }
  338. //PDFViewer.Load();
  339. //PDFViewer.SetFormFieldHighlight(Settings.Default.AppProperties.InitialVIew.HighlightLink);
  340. //PDFViewer.SetBackgroundBrush(new System.Windows.Media.SolidColorBrush(Settings.Default.AppProperties.InitialVIew.BackGround));
  341. if (App.mainWindowViewModel != null)
  342. {
  343. App.mainWindowViewModel.CurrentPDFViewer = PDFViewer;
  344. }
  345. return true;
  346. }
  347. /// <summary>
  348. /// 创建文件,路径为空时表示创建空白文档
  349. /// 否则表示从图片路径创建PDf
  350. /// </summary>
  351. /// <param name="imagePath"></param>
  352. /// <returns></returns>
  353. public bool CreateFile(string imagePath = null)
  354. {
  355. PDFViewer = new CPDFViewer();
  356. PDFViewer.CreateDocument();
  357. PDFViewer.UndoManager.PropertyChanged += UndoManager_PropertyChanged;
  358. if (PDFViewer.Document == null)
  359. {
  360. AlertsMessage alertsMessage = new AlertsMessage();
  361. alertsMessage.ShowDialog("", App.MainPageLoader.GetString("Create PDF failed"), App.ServiceLoader.GetString("Text_ok"));
  362. return false;
  363. }
  364. if (string.IsNullOrEmpty(imagePath))
  365. {
  366. FileName = "Blank Page.pdf";
  367. //默认插入595*842 大小的页面
  368. PDFViewer.Document.InsertPage(0, 595, 842, null);
  369. }
  370. else
  371. {
  372. FileName = imagePath.Substring(imagePath.LastIndexOf("\\") + 1, imagePath.LastIndexOf(".") - imagePath.LastIndexOf("\\") - 1) + ".pdf";
  373. Bitmap pic = new Bitmap(imagePath);
  374. int width = pic.Size.Width;
  375. int height = pic.Size.Height;
  376. string ex = System.IO.Path.GetExtension(imagePath);
  377. //其他格式或者名称中含空格的图片 在本地先转存一下
  378. if ((ex != ".jpg" && ex != ".jpeg") || !Uri.IsWellFormedUriString(imagePath, UriKind.Absolute))
  379. {
  380. //将其他格式图片转换成jpg
  381. string folderPath = Path.GetTempPath();
  382. if (File.Exists(folderPath))
  383. {
  384. File.Delete(folderPath);
  385. }
  386. DirectoryInfo tempfolder = new DirectoryInfo(folderPath);
  387. if (!tempfolder.Exists)
  388. {
  389. tempfolder.Create();
  390. }
  391. string targetPath = System.IO.Path.Combine(folderPath, Guid.NewGuid().ToString());
  392. imagePath = targetPath;
  393. pic.Save(targetPath, ImageFormat.Jpeg);
  394. }
  395. pic.Dispose();
  396. var result = PDFViewer.Document.InsertPage(0, width, height, imagePath);
  397. if (!result)
  398. {
  399. AlertsMessage alertsMessage = new AlertsMessage();
  400. alertsMessage.ShowDialog("", App.MainPageLoader.GetString("Create PDF failed"), App.ServiceLoader.GetString("Text_ok"));
  401. return false;
  402. }
  403. }
  404. SaveToTempFile();
  405. PDFViewer.UndoManager.CanSave = true;
  406. FileChanged = Visibility.Visible;
  407. NavigateToViewContent();
  408. return true;
  409. }
  410. /// <summary>
  411. /// 从office文件转换成PDF
  412. /// </summary>
  413. /// <param name="sourcepath"></param>
  414. /// <returns></returns>
  415. public bool CreateFileFromOffice(string sourcepath, Microsoft.Office.Interop.Word.WdPaperSize paperSize = Microsoft.Office.Interop.Word.WdPaperSize.wdPaperA4, double margin = 0)
  416. {
  417. try
  418. {
  419. string targetPath = "";
  420. targetPath = ConverterHelper.ConvertOfficeToPDF(sourcepath, paperSize, margin);
  421. PDFViewer = new CPDFViewer();
  422. PDFViewer.CreateDocument();
  423. if (PDFViewer.Document == null)
  424. {
  425. AlertsMessage alertsMessage = new AlertsMessage();
  426. alertsMessage.ShowDialog("", App.MainPageLoader.GetString("Create PDF failed"), App.ServiceLoader.GetString("Text_ok"));
  427. return false;
  428. }
  429. FileName = sourcepath.Substring(sourcepath.LastIndexOf("\\") + 1, sourcepath.LastIndexOf(".") - sourcepath.LastIndexOf("\\") - 1) + ".pdf";
  430. var tempdoc = CPDFDocument.InitWithFilePath(targetPath);
  431. if (tempdoc == null)
  432. {
  433. AlertsMessage alertsMessage = new AlertsMessage();
  434. alertsMessage.ShowDialog("", App.MainPageLoader.GetString("Create PDF failed"), App.ServiceLoader.GetString("Text_ok"));
  435. return false;
  436. }
  437. PDFViewer.Document.ImportPages(tempdoc, "");
  438. SaveToTempFile();
  439. PDFViewer.UndoManager.CanSave = true;
  440. FileChanged = Visibility.Visible;
  441. //await System.Windows.Application.Current.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Send, new Action(() =>
  442. //{
  443. NavigateToViewContent();
  444. //}));
  445. return true;
  446. }
  447. catch (Exception)
  448. {
  449. string str = "没有安装";
  450. //判断是否有安装office软件
  451. var officeType = Type.GetTypeFromProgID("Word.Application");
  452. if (officeType == null)
  453. {
  454. str += "Word;";
  455. }
  456. officeType = Type.GetTypeFromProgID("Excel.Application");
  457. if (officeType == null)
  458. {
  459. str += "Excel;";
  460. }
  461. officeType = Type.GetTypeFromProgID("Powerpoint.Application");
  462. if (officeType == null)
  463. {
  464. str += "Excel;";
  465. }
  466. AlertsMessage alertsMessage = new AlertsMessage();
  467. if (str != "没有安装")
  468. {
  469. alertsMessage.ShowDialog("",App.MainPageLoader.GetString("NoOffice_Warning"), App.ServiceLoader.GetString("Text_ok"));
  470. }
  471. else
  472. {
  473. alertsMessage.ShowDialog("", App.MainPageLoader.GetString("CreateFileFailedWarning"), App.ServiceLoader.GetString("Text_ok"));
  474. }
  475. return false;
  476. }
  477. }
  478. /// <summary>
  479. /// 新建的文档 保存至临时文件 解决新建文档没有路径的问题
  480. /// </summary>
  481. private void SaveToTempFile()
  482. {
  483. if (PDFViewer != null)
  484. {
  485. string tempfile = CacheFilePath.Instance.CreatedFilePath;
  486. string file = CommonHelper.CreateFilePath(Path.Combine(tempfile,App.UntitledFileNmae));
  487. PDFViewer.Document.WriteToFilePath(file);
  488. PDFViewer.CloseDocument();
  489. PDFViewer.InitDocument(file);
  490. FilePath = file;
  491. //在viewcontent里打开是 会重新load 因此这里不需要load 避免重复
  492. NewFile = true;
  493. }
  494. }
  495. private void UndoManager_PropertyChanged(object sender, PropertyChangedEventArgs e)
  496. {
  497. if (e.PropertyName == "CanSave")
  498. {
  499. if (PDFViewer.UndoManager.CanSave)
  500. {
  501. FileChanged = Visibility.Visible;
  502. }
  503. else
  504. {
  505. FileChanged = Visibility.Collapsed;
  506. }
  507. //保存完后,需要更新产品名字
  508. if (!PDFViewer.UndoManager.CanSave&&!string.IsNullOrEmpty(PDFViewer.Document.FileName))
  509. {
  510. FileName =System.IO.Path.GetFileName(PDFViewer.Document.FilePath);
  511. }
  512. }
  513. }
  514. #region Navigation
  515. public async void OnNavigatedTo(NavigationContext navigationContext)
  516. {
  517. mainWindowViewModel = App.mainWindowViewModel;
  518. //因为是异步打开多个文件,需要先显示Home界面
  519. NavigationParameters parameters = new NavigationParameters();
  520. parameters.Add(ParameterNames.MainViewModel, this);
  521. if (toolregion.Regions.ContainsRegionWithName(MainContentRegionName))
  522. {
  523. toolregion.RequestNavigate(MainContentRegionName, "HomeContent", parameters);
  524. }
  525. //常规加载首页的情况
  526. if (navigationContext.Parameters.Count <= 0)
  527. {
  528. return;
  529. }
  530. //一次打开多个文件的情况
  531. var filepath = navigationContext.Parameters[ParameterNames.FilePath].ToString();
  532. if (filepath != null)
  533. {
  534. homeContentViewModel.IsLoading = Visibility.Visible;
  535. await Task.Delay(3);
  536. bool result = true;
  537. if (System.IO.Path.GetExtension(filepath.ToString()).ToLower() == ".pdf")
  538. {
  539. OpenFile(filepath.ToString());
  540. }
  541. else if (Properties.Resources.imageex.Contains(System.IO.Path.GetExtension(filepath).ToLower()))
  542. {
  543. //图片转PDF
  544. result = CreateFile(filepath);
  545. }
  546. else
  547. {
  548. result =CreateFileFromOffice(filepath);
  549. }
  550. homeContentViewModel.IsLoading = Visibility.Collapsed;
  551. if (!result)
  552. {
  553. mainWindowViewModel.CloseTabItem(mainWindowViewModel.SelectedItem);
  554. return;
  555. }
  556. if (!App.OpenedFileList.Contains(filepath))
  557. {
  558. //更新已打开的文件记录
  559. App.OpenedFileList.Add(filepath);
  560. }
  561. }
  562. }
  563. public bool IsNavigationTarget(NavigationContext navigationContext)
  564. {
  565. return false;
  566. }
  567. public void OnNavigatedFrom(NavigationContext navigationContext)
  568. {
  569. }
  570. #endregion Navigation
  571. }
  572. }