MainContentViewModel.cs 20 KB

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