MainContentViewModel.cs 17 KB

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