MainContentViewModel.cs 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  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, Microsoft.Office.Interop.Word.WdPaperSize paperSize = Microsoft.Office.Interop.Word.WdPaperSize.wdPaperA4, double margin = 0)
  255. {
  256. try
  257. {
  258. //生成存放临时pdf的临时文件夹
  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).ToLower();
  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. case ".html":
  281. await Task.Run(() =>
  282. {
  283. Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
  284. Microsoft.Office.Interop.Word.Document document = null;
  285. word.Visible = false;
  286. word.ShowWindowsInTaskbar = true;
  287. document = word.Documents.Open(sourcepath);
  288. var page = document.PageSetup;
  289. page.PaperSize = paperSize;
  290. if(margin>0)
  291. {
  292. page.LeftMargin = page.TopMargin = page.RightMargin = page.BottomMargin = (float)margin;
  293. }
  294. document?.ExportAsFixedFormat(targetPath, Microsoft.Office.Interop.Word.WdExportFormat.wdExportFormatPDF);
  295. document?.Close();
  296. word?.Quit();
  297. });
  298. break;
  299. case ".xls":
  300. case ".xlsx":
  301. case ".xlsm":
  302. case ".xlsb":
  303. case ".xlam":
  304. case ".xltx":
  305. case ".xlt":
  306. await Task.Run(() =>
  307. {
  308. Microsoft.Office.Interop.Excel.Application excele = new Microsoft.Office.Interop.Excel.Application();
  309. Microsoft.Office.Interop.Excel.Workbook workbook = null;
  310. excele.Visible = false;
  311. try
  312. {
  313. workbook = excele.Workbooks.Open(sourcepath);
  314. }
  315. catch (Exception e)
  316. {
  317. 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);
  318. }
  319. workbook?.ExportAsFixedFormat(Microsoft.Office.Interop.Excel.XlFixedFormatType.xlTypePDF, targetPath);
  320. workbook?.Close();
  321. excele?.Quit();
  322. });
  323. break;
  324. case ".ppt":
  325. case ".pptx":
  326. case ".pptm":
  327. case ".pptsx":
  328. case ".pps":
  329. case ".pptsm":
  330. case ".pot":
  331. case ".potm":
  332. await Task.Run(() =>
  333. {
  334. Microsoft.Office.Interop.PowerPoint.Application ppt = new Microsoft.Office.Interop.PowerPoint.Application();
  335. Microsoft.Office.Interop.PowerPoint.Presentation presentation = null;
  336. ppt.Visible = Microsoft.Office.Core.MsoTriState.msoCTrue;
  337. presentation = ppt.Presentations.Open(sourcepath);
  338. presentation.ExportAsFixedFormat(targetPath, Microsoft.Office.Interop.PowerPoint.PpFixedFormatType.ppFixedFormatTypePDF);
  339. presentation?.Close();
  340. ppt?.Quit();
  341. });
  342. break;
  343. }
  344. PDFViewer = new CPDFViewer();
  345. PDFViewer.CreateDocument();
  346. if (PDFViewer.Document == null)
  347. {
  348. AlertsMessage alertsMessage = new AlertsMessage();
  349. alertsMessage.ShowDialog("","创建PDF失败","OK");
  350. return false;
  351. }
  352. FileName = sourcepath.Substring(sourcepath.LastIndexOf("\\") + 1, sourcepath.LastIndexOf(".") - sourcepath.LastIndexOf("\\") - 1) + ".pdf";
  353. var tempdoc = CPDFDocument.InitWithFilePath(targetPath);
  354. if (tempdoc == null)
  355. {
  356. AlertsMessage alertsMessage = new AlertsMessage();
  357. alertsMessage.ShowDialog("", "创建PDF失败", "OK");
  358. return false;
  359. }
  360. PDFViewer.Document.ImportPages(tempdoc, "");
  361. //PDFViewer.SetBackgroundBrush(new SolidColorBrush((Color)System.Windows.Media.ColorConverter.ConvertFromString(Settings.Default.AppProperties.InitialVIew.Background)));
  362. PDFViewer.Load();
  363. PDFViewer.UndoManager.CanSave = true;
  364. FileChanged = Visibility.Visible;
  365. PDFViewer.SetFormFieldHighlight(true);
  366. NavigateToViewContent();
  367. return true;
  368. }
  369. catch (Exception ex)
  370. {
  371. AlertsMessage alertsMessage = new AlertsMessage();
  372. alertsMessage.ShowDialog("", "没有安装Office", "OK");
  373. return false;
  374. }
  375. }
  376. private void UndoManager_PropertyChanged(object sender, PropertyChangedEventArgs e)
  377. {
  378. if (e.PropertyName == "CanSave")
  379. {
  380. if (PDFViewer.UndoManager.CanSave)
  381. {
  382. FileChanged = Visibility.Visible;
  383. }
  384. else
  385. {
  386. FileChanged = Visibility.Collapsed;
  387. }
  388. if (!string.IsNullOrEmpty(PDFViewer.Document.FileName))
  389. {
  390. FileName = PDFViewer.Document.FileName;
  391. }
  392. }
  393. }
  394. #region Navigation
  395. public async void OnNavigatedTo(NavigationContext navigationContext)
  396. {
  397. if (navigationContext.Parameters.Count <= 0)
  398. return;
  399. var filepath = navigationContext.Parameters[ParameterNames.FilePath].ToString();
  400. if (filepath!= null)
  401. {
  402. if(System.IO.Path.GetExtension(filepath.ToString()).ToLower()==".pdf")
  403. {
  404. OpenFile(filepath.ToString());
  405. }
  406. else if(Properties.Resources.imageex.Contains(System.IO.Path.GetExtension(filepath).ToLower()))
  407. {
  408. //图片转PDF
  409. CreateFile(filepath);
  410. }
  411. else
  412. {
  413. await CreateFileFromOffice(filepath);
  414. }
  415. }
  416. }
  417. public bool IsNavigationTarget(NavigationContext navigationContext)
  418. {
  419. return false;
  420. }
  421. public void OnNavigatedFrom(NavigationContext navigationContext)
  422. {
  423. }
  424. #endregion
  425. }
  426. }