MainContentViewModel.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670
  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. if (App.OpenedFileList.Contains(filePath) == false)
  273. {
  274. App.OpenedFileList.Add(filePath);
  275. }
  276. //打开文件后,不管是新文件还是旧文件都需要更新排序
  277. SettingHelper.SortRecentOpenFiles(filePath);
  278. }
  279. /// <summary>
  280. /// 创建PDFviewer对象后导航到ViewContent
  281. /// </summary>
  282. private void NavigateToViewContent(PasswordInfo passwordInfo = null)
  283. {
  284. NavigationParameters parameters = new NavigationParameters {
  285. { ParameterNames.MainViewModel, this },
  286. { ParameterNames.PDFViewer,PDFViewer},
  287. { ParameterNames.PasswordInfo, passwordInfo}
  288. };
  289. toolregion.RequestNavigate(MainContentRegionName, "ViewContent", parameters);
  290. IsReNameEnable = true;
  291. if (!string.IsNullOrEmpty(PDFViewer.Document.FilePath) && !NewFile)
  292. {
  293. IsShowInFolderEnable = true;
  294. }
  295. }
  296. /// <summary>
  297. /// 从文件路径创建PDFViewer对象,已包含文档解密逻辑
  298. /// </summary>
  299. /// <param name="path"></param>
  300. /// <returns></returns>
  301. private bool LoadFileFormPath(string path)
  302. {
  303. PDFViewer = new CPDFViewer();
  304. PDFViewer.InitDocument(path);
  305. PDFViewer.UndoManager.PropertyChanged += UndoManager_PropertyChanged;
  306. if (PDFViewer.Document == null)
  307. {
  308. //MessageBoxEx.Show(App.MainPageLoader.GetString("Main_OpenFileFailedWarning"));
  309. return false;
  310. }
  311. else
  312. {
  313. //解密逻辑调整到显示阅读页后,测试确认没问题后,删除下面的注释部分代码
  314. //VerifyPasswordResult result = SecurityHelper.VerifyPasswordByPasswordKind(PDFViewer.Document, EnumPasswordKind.StatusOpenPassword, dialogs);
  315. //if (result.IsDiscryptied)
  316. //{
  317. // if (result.Password != null)
  318. // {
  319. // string filePath = PDFViewer.Document.FilePath;
  320. // PDFViewer.Document.UnlockWithPassword(result.Password);
  321. // PDFViewer.Tag = result.Password;
  322. // }
  323. // ///TODO:
  324. // ///此处填入需要执行的代码
  325. //}
  326. //if (result.IsDiscryptied == false)
  327. //{
  328. // //未成功解密文档时,释放Document对象,返回
  329. // PDFViewer.Document.Release();
  330. // return false;
  331. //}
  332. }
  333. //PDFViewer.Load();
  334. //PDFViewer.SetFormFieldHighlight(Settings.Default.AppProperties.InitialVIew.HighlightLink);
  335. //PDFViewer.SetBackgroundBrush(new System.Windows.Media.SolidColorBrush(Settings.Default.AppProperties.InitialVIew.BackGround));
  336. if (App.mainWindowViewModel != null)
  337. {
  338. App.mainWindowViewModel.CurrentPDFViewer = PDFViewer;
  339. }
  340. return true;
  341. }
  342. /// <summary>
  343. /// 创建文件,路径为空时表示创建空白文档
  344. /// 否则表示从图片路径创建PDf
  345. /// </summary>
  346. /// <param name="imagePath"></param>
  347. /// <returns></returns>
  348. public bool CreateFile(string imagePath = null)
  349. {
  350. PDFViewer = new CPDFViewer();
  351. PDFViewer.CreateDocument();
  352. PDFViewer.UndoManager.PropertyChanged += UndoManager_PropertyChanged;
  353. if (PDFViewer.Document == null)
  354. {
  355. AlertsMessage alertsMessage = new AlertsMessage();
  356. alertsMessage.ShowDialog("", App.MainPageLoader.GetString("Create PDF failed"), App.ServiceLoader.GetString("Text_ok"));
  357. return false;
  358. }
  359. if (string.IsNullOrEmpty(imagePath))
  360. {
  361. FileName = "Blank Page.pdf";
  362. //默认插入595*842 大小的页面
  363. PDFViewer.Document.InsertPage(0, 595, 842, null);
  364. }
  365. else
  366. {
  367. FileName = imagePath.Substring(imagePath.LastIndexOf("\\") + 1, imagePath.LastIndexOf(".") - imagePath.LastIndexOf("\\") - 1) + ".pdf";
  368. Bitmap pic = new Bitmap(imagePath);
  369. int width = pic.Size.Width;
  370. int height = pic.Size.Height;
  371. string ex = System.IO.Path.GetExtension(imagePath);
  372. //其他格式或者名称中含空格的图片 在本地先转存一下
  373. if ((ex != ".jpg" && ex != ".jpeg") || !Uri.IsWellFormedUriString(imagePath, UriKind.Absolute))
  374. {
  375. //将其他格式图片转换成jpg
  376. string folderPath = Path.GetTempPath();
  377. if (File.Exists(folderPath))
  378. {
  379. File.Delete(folderPath);
  380. }
  381. DirectoryInfo tempfolder = new DirectoryInfo(folderPath);
  382. if (!tempfolder.Exists)
  383. {
  384. tempfolder.Create();
  385. }
  386. string targetPath = System.IO.Path.Combine(folderPath, Guid.NewGuid().ToString());
  387. imagePath = targetPath;
  388. pic.Save(targetPath, ImageFormat.Jpeg);
  389. }
  390. pic.Dispose();
  391. var result = PDFViewer.Document.InsertPage(0, width, height, imagePath);
  392. if (!result)
  393. {
  394. AlertsMessage alertsMessage = new AlertsMessage();
  395. alertsMessage.ShowDialog("", App.MainPageLoader.GetString("Create PDF failed"), App.ServiceLoader.GetString("Text_ok"));
  396. return false;
  397. }
  398. }
  399. SaveToTempFile();
  400. PDFViewer.UndoManager.CanSave = true;
  401. FileChanged = Visibility.Visible;
  402. NavigateToViewContent();
  403. return true;
  404. }
  405. /// <summary>
  406. /// 从office文件转换成PDF
  407. /// </summary>
  408. /// <param name="sourcepath"></param>
  409. /// <returns></returns>
  410. public bool CreateFileFromOffice(string sourcepath, Microsoft.Office.Interop.Word.WdPaperSize paperSize = Microsoft.Office.Interop.Word.WdPaperSize.wdPaperA4, double margin = 0)
  411. {
  412. try
  413. {
  414. string targetPath = "";
  415. targetPath = ConverterHelper.ConvertOfficeToPDF(sourcepath, paperSize, margin);
  416. PDFViewer = new CPDFViewer();
  417. PDFViewer.CreateDocument();
  418. if (PDFViewer.Document == null)
  419. {
  420. AlertsMessage alertsMessage = new AlertsMessage();
  421. alertsMessage.ShowDialog("", App.MainPageLoader.GetString("Create PDF failed"), App.ServiceLoader.GetString("Text_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("", App.MainPageLoader.GetString("Create PDF failed"), App.ServiceLoader.GetString("Text_ok"));
  430. return false;
  431. }
  432. PDFViewer.Document.ImportPages(tempdoc, "");
  433. SaveToTempFile();
  434. PDFViewer.UndoManager.CanSave = true;
  435. FileChanged = Visibility.Visible;
  436. //await System.Windows.Application.Current.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Send, new Action(() =>
  437. //{
  438. NavigateToViewContent();
  439. //}));
  440. return true;
  441. }
  442. catch (Exception)
  443. {
  444. string str = "没有安装";
  445. //判断是否有安装office软件
  446. var officeType = Type.GetTypeFromProgID("Word.Application");
  447. if (officeType == null)
  448. {
  449. str += "Word;";
  450. }
  451. officeType = Type.GetTypeFromProgID("Excel.Application");
  452. if (officeType == null)
  453. {
  454. str += "Excel;";
  455. }
  456. officeType = Type.GetTypeFromProgID("Powerpoint.Application");
  457. if (officeType == null)
  458. {
  459. str += "Excel;";
  460. }
  461. AlertsMessage alertsMessage = new AlertsMessage();
  462. if (str != "没有安装")
  463. {
  464. alertsMessage.ShowDialog("",App.MainPageLoader.GetString("NoOffice_Warning"), App.ServiceLoader.GetString("Text_ok"));
  465. }
  466. else
  467. {
  468. alertsMessage.ShowDialog("", App.MainPageLoader.GetString("CreateFileFailedWarning"), App.ServiceLoader.GetString("Text_ok"));
  469. }
  470. return false;
  471. }
  472. }
  473. /// <summary>
  474. /// 新建的文档 保存至临时文件 解决新建文档没有路径的问题
  475. /// </summary>
  476. private void SaveToTempFile()
  477. {
  478. if (PDFViewer != null)
  479. {
  480. string tempfile = CacheFilePath.Instance.CreatedFilePath;
  481. string file = CommonHelper.CreateFilePath(Path.Combine(tempfile,App.UntitledFileNmae));
  482. PDFViewer.Document.WriteToFilePath(file);
  483. PDFViewer.CloseDocument();
  484. PDFViewer.InitDocument(file);
  485. FilePath = file;
  486. //在viewcontent里打开是 会重新load 因此这里不需要load 避免重复
  487. NewFile = true;
  488. }
  489. }
  490. private void UndoManager_PropertyChanged(object sender, PropertyChangedEventArgs e)
  491. {
  492. if (e.PropertyName == "CanSave")
  493. {
  494. if (PDFViewer.UndoManager.CanSave)
  495. {
  496. FileChanged = Visibility.Visible;
  497. }
  498. else
  499. {
  500. FileChanged = Visibility.Collapsed;
  501. }
  502. //保存完后,需要更新产品名字
  503. if (!PDFViewer.UndoManager.CanSave&&!string.IsNullOrEmpty(PDFViewer.Document.FileName))
  504. {
  505. FileName =System.IO.Path.GetFileName(PDFViewer.Document.FilePath);
  506. }
  507. }
  508. }
  509. #region Navigation
  510. public async void OnNavigatedTo(NavigationContext navigationContext)
  511. {
  512. mainWindowViewModel = App.mainWindowViewModel;
  513. //因为是异步打开多个文件,需要先显示Home界面
  514. NavigationParameters parameters = new NavigationParameters();
  515. parameters.Add(ParameterNames.MainViewModel, this);
  516. if (toolregion.Regions.ContainsRegionWithName(MainContentRegionName))
  517. {
  518. toolregion.RequestNavigate(MainContentRegionName, "HomeContent", parameters);
  519. }
  520. //常规加载首页的情况
  521. if (navigationContext.Parameters.Count <= 0)
  522. {
  523. return;
  524. }
  525. //一次打开多个文件的情况
  526. var filepath = navigationContext.Parameters[ParameterNames.FilePath].ToString();
  527. if (filepath != null)
  528. {
  529. homeContentViewModel.IsLoading = Visibility.Visible;
  530. await Task.Delay(3);
  531. bool result = true;
  532. if (System.IO.Path.GetExtension(filepath.ToString()).ToLower() == ".pdf")
  533. {
  534. OpenFile(filepath.ToString());
  535. }
  536. else if (Properties.Resources.imageex.Contains(System.IO.Path.GetExtension(filepath).ToLower()))
  537. {
  538. //图片转PDF
  539. result = CreateFile(filepath);
  540. }
  541. else
  542. {
  543. result =CreateFileFromOffice(filepath);
  544. }
  545. homeContentViewModel.IsLoading = Visibility.Collapsed;
  546. if (!result)
  547. {
  548. mainWindowViewModel.CloseTabItem(mainWindowViewModel.SelectedItem);
  549. return;
  550. }
  551. if (!App.OpenedFileList.Contains(filepath))
  552. {
  553. //更新已打开的文件记录
  554. App.OpenedFileList.Add(filepath);
  555. }
  556. }
  557. }
  558. public bool IsNavigationTarget(NavigationContext navigationContext)
  559. {
  560. return false;
  561. }
  562. public void OnNavigatedFrom(NavigationContext navigationContext)
  563. {
  564. }
  565. #endregion Navigation
  566. }
  567. }