MainContentViewModel.cs 20 KB

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