MainContentViewModel.cs 17 KB

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