MainContentViewModel.cs 22 KB

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