123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667 |
- using ComPDFKitViewer.PdfViewer;
- using Microsoft.Win32;
- using PDF_Master.CustomControl;
- using PDF_Master.EventAggregators;
- using PDF_Master.Views;
- using Prism.Commands;
- using Prism.Events;
- using Prism.Ioc;
- using Prism.Mvvm;
- using Prism.Regions;
- using Prism.Services.Dialogs;
- using System;
- using System.Collections.Generic;
- using System.Diagnostics;
- using System.Linq;
- using System.Text;
- using System.Threading.Tasks;
- using System.Windows;
- using PDF_Master.Model;
- using System.ComponentModel;
- using PDF_Master.Helper;
- using PDFSettings;
- using System.Drawing;
- using System.IO;
- using System.Drawing.Imaging;
- using ComPDFKit.PDFDocument;
- using static PDF_Master.Model.Dialog.ToolsDialogs.SaftyDialogs.DeleteSafetySettintgsModel;
- using PDF_Master.Model.Dialog.ToolsDialogs.SaftyDialogs;
- using PDF_Master.Properties;
- using WIA;
- namespace PDF_Master.ViewModels
- {
- public class MainContentViewModel : BindableBase, INavigationAware
- {
- #region 文案
- private string T_rename;
- public string T_Rename
- {
- get { return T_rename; }
- set
- {
- SetProperty(ref T_rename, value);
- }
- }
- private string T_floder;
- public string T_Floder
- {
- get { return T_floder; }
- set
- {
- SetProperty(ref T_floder, value);
- }
- }
- private string T_close;
- public string T_Close
- {
- get { return T_close; }
- set
- {
- SetProperty(ref T_close, value);
- }
- }
- private string T_closeAll;
- public string T_CloseAll
- {
- get { return T_closeAll; }
- set
- {
- SetProperty(ref T_closeAll, value);
- }
- }
- private void InitString()
- {
- FileName = App.MainPageLoader.GetString("MultipleTabs_Default");
- T_Rename = App.MainPageLoader.GetString("MultipleTabs_Rename");
- T_Floder = App.MainPageLoader.GetString("MultipleTabs_ Folder");
- T_Close = App.MainPageLoader.GetString("MultipleTabs_ Close");
- T_CloseAll = App.MainPageLoader.GetString("MultipleTabs_ CloseAll");
- }
- #endregion 文案
- /// <summary>
- /// 是否是注释列表点击
- /// </summary>
- public bool AnnotMouseLeftButtonDown { get; set; } = false;
- /// <summary>
- /// 是否使用了高级功能
- /// </summary>
- public bool IsUsedVIP = false;
- /// <summary>
- /// 是否处于阅读模式
- /// </summary>
- public bool IsBookMode = false;
- private string fileName = "Home";
- public string FileName
- {
- get { return fileName; }
- set
- {
- SetProperty(ref fileName, value);
- if (IsReNameTextShow == Visibility.Visible)
- {
- dorenameFile();
- }
- }
- }
- private string filePath;
- public string FilePath
- {
- get { return filePath; }
- set
- {
- SetProperty(ref filePath, value);
- if (!string.IsNullOrEmpty(filePath))
- {
- FileName = System.IO.Path.GetFileName(filePath);
- }
- }
- }
- private Visibility fileChanged = Visibility.Collapsed;
- public Visibility FileChanged
- {
- get { return fileChanged; }
- set { SetProperty(ref fileChanged, value); }
- }
- public CPDFViewer PDFViewer { get; set; }
- public DelegateCommand<object> CloseTab { get; set; }
- public DelegateCommand UnLoaded { get; set; }
- public DelegateCommand ShowInFolderCommand { get; set; }
- public DelegateCommand RenameCommand { get; set; }
- public ViewContentViewModel viewContentViewModel { get; set; }
- public MainWindowViewModel mainWindowViewModel { get; set; }
- public HomeContentViewModel homeContentViewModel { get; set; }
- private string regionName;
- public string MainContentRegionName
- {
- get { return regionName; }
- set { SetProperty(ref regionName, value); }
- }
- private bool isReNameEnable = false;
- /// <summary>
- /// 是否能够重命名
- /// </summary>
- public bool IsReNameEnable
- {
- get { return isReNameEnable; }
- set
- {
- SetProperty(ref isReNameEnable, value);
- }
- }
- private bool isShowInFolderEnable = false;
- /// <summary>
- /// 是否能够显示文件浏览器
- /// </summary>
- public bool IsShowInFolderEnable
- {
- get { return isShowInFolderEnable; }
- set
- {
- SetProperty(ref isShowInFolderEnable, value);
- }
- }
- private Visibility isRenameTextShow = Visibility.Collapsed;
- public Visibility IsReNameTextShow
- {
- get { return isRenameTextShow; }
- set
- {
- SetProperty(ref isRenameTextShow, value);
- }
- }
- private bool newFile = false;
- /// <summary>
- /// 是否是新建的文档
- /// </summary>
- public bool NewFile
- {
- get { return newFile; }
- set
- {
- SetProperty(ref newFile, value);
- if (!value)
- {
- IsShowInFolderEnable = true;
- }
- }
- }
- public IRegionManager toolregion;
- public IEventAggregator eventer;
- public IContainerProvider container;
- public IDialogService dialogs;
- public MainContentViewModel(IRegionManager regionManager, IEventAggregator eventAggregator, IContainerProvider containerProvider, IDialogService dialogService)
- {
- toolregion = regionManager;
- eventer = eventAggregator;
- container = containerProvider;
- dialogs = dialogService;
- CloseTab = new DelegateCommand<object>(CloseTabItem);
- ShowInFolderCommand = new DelegateCommand(showInFolder);
- RenameCommand = new DelegateCommand(rename);
- UnLoaded = new DelegateCommand(unload);
- MainContentRegionName = Guid.NewGuid().ToString();
- InitString();
- }
- //关闭页签
- //清除文件记录,释放Document对象
- private void unload()
- {
- if (PDFViewer != null)
- {
- App.OpenedFileList.Remove(PDFViewer.Document?.FilePath);
- PDFViewer.CloseDocument();
- }
- }
- /// <summary>
- /// 执行重命名操作
- /// </summary>
- private void dorenameFile()
- {
- var folder = PDFViewer.Document.FilePath.Substring(0, PDFViewer.Document.FilePath.LastIndexOf("\\"));
- ////File.Replace(PDFViewer.Document.FilePath,Path.Combine(folder,FileName),Path.Combine(folder,"back.bak"),true);
- ///TODO:会被占用 无法操作
- IsReNameTextShow = Visibility.Collapsed;
- }
- /// <summary>
- /// 显示重命名文本框
- /// </summary>
- private void rename()
- {
- IsReNameTextShow = Visibility.Visible;
- }
- private void showInFolder()
- {
- if (!string.IsNullOrEmpty(PDFViewer.Document.FilePath))
- {
- CommonHelper.ShowFileBrowser(PDFViewer.Document.FilePath);
- }
- }
- private void CloseTabItem(object item)
- {
- if (item == null)
- {
- App.mainWindowViewModel?.CloseTabItem(mainWindowViewModel.SelectedItem);
- }
- else
- {
- App.mainWindowViewModel?.CloseTabItem(item);
- App.OpenedFileList.Remove(FilePath);
- if (NewFile)
- {
- //新文档 关闭文档后 及时清空临时缓存
- DirectoryInfo directory = new DirectoryInfo(CacheFilePath.Instance.CreatedFilePath);
- FileInfo fileInfo = new FileInfo(FilePath);
- if (directory.GetFiles().ToList().Contains(fileInfo))
- {
- File.Delete(FilePath);
- }
- }
- }
- }
- /// <summary>
- /// 打开指定路径的PDF文件
- /// </summary>
- /// <param name="filePath"></param>
- public void OpenFile(string filePath, PasswordInfo passwordInfo = null)
- {
- var result = LoadFileFormPath(filePath);
- if (!result)
- {
- AlertsMessage alertsMessage = new AlertsMessage();
- alertsMessage.ShowDialog("", App.MainPageLoader.GetString("Main_OpenFileFailedWarning"), App.ServiceLoader.GetString("Text_ok"));
- return;
- }
- FilePath = filePath;
- NavigateToViewContent();
- if (App.OpenedFileList.Contains(filePath) == false)
- {
- App.OpenedFileList.Add(filePath);
- }
- //打开文件后,不管是新文件还是旧文件都需要更新排序
- SettingHelper.SortRecentOpenFiles(filePath);
- }
- /// <summary>
- /// 创建PDFviewer对象后导航到ViewContent
- /// </summary>
- private void NavigateToViewContent(PasswordInfo passwordInfo = null)
- {
- NavigationParameters parameters = new NavigationParameters {
- { ParameterNames.MainViewModel, this },
- { ParameterNames.PDFViewer,PDFViewer},
- { ParameterNames.PasswordInfo, passwordInfo}
- };
- toolregion.RequestNavigate(MainContentRegionName, "ViewContent", parameters);
- IsReNameEnable = true;
- if (!string.IsNullOrEmpty(PDFViewer.Document.FilePath) && !NewFile)
- {
- IsShowInFolderEnable = true;
- }
- }
- /// <summary>
- /// 从文件路径创建PDFViewer对象,已包含文档解密逻辑
- /// </summary>
- /// <param name="path"></param>
- /// <returns></returns>
- private bool LoadFileFormPath(string path)
- {
- PDFViewer = new CPDFViewer();
- PDFViewer.InitDocument(path);
- PDFViewer.UndoManager.PropertyChanged += UndoManager_PropertyChanged;
- if (PDFViewer.Document == null)
- {
- //MessageBoxEx.Show(App.MainPageLoader.GetString("Main_OpenFileFailedWarning"));
- return false;
- }
- else
- {
- //解密逻辑调整到显示阅读页后,测试确认没问题后,删除下面的注释部分代码
- //VerifyPasswordResult result = SecurityHelper.VerifyPasswordByPasswordKind(PDFViewer.Document, EnumPasswordKind.StatusOpenPassword, dialogs);
- //if (result.IsDiscryptied)
- //{
- // if (result.Password != null)
- // {
- // string filePath = PDFViewer.Document.FilePath;
- // PDFViewer.Document.UnlockWithPassword(result.Password);
- // PDFViewer.Tag = result.Password;
- // }
- // ///TODO:
- // ///此处填入需要执行的代码
- //}
- //if (result.IsDiscryptied == false)
- //{
- // //未成功解密文档时,释放Document对象,返回
- // PDFViewer.Document.Release();
- // return false;
- //}
- }
- //PDFViewer.Load();
- //PDFViewer.SetFormFieldHighlight(Settings.Default.AppProperties.InitialVIew.HighlightLink);
- //PDFViewer.SetBackgroundBrush(new System.Windows.Media.SolidColorBrush(Settings.Default.AppProperties.InitialVIew.BackGround));
- if (App.mainWindowViewModel != null)
- {
- App.mainWindowViewModel.CurrentPDFViewer = PDFViewer;
- }
- return true;
- }
- /// <summary>
- /// 创建文件,路径为空时表示创建空白文档
- /// 否则表示从图片路径创建PDf
- /// </summary>
- /// <param name="imagePath"></param>
- /// <returns></returns>
- public bool CreateFile(string imagePath = null)
- {
- PDFViewer = new CPDFViewer();
- PDFViewer.CreateDocument();
- PDFViewer.UndoManager.PropertyChanged += UndoManager_PropertyChanged;
- if (PDFViewer.Document == null)
- {
- AlertsMessage alertsMessage = new AlertsMessage();
- alertsMessage.ShowDialog("", App.MainPageLoader.GetString("Create PDF failed"), App.ServiceLoader.GetString("Text_ok"));
- return false;
- }
- if (string.IsNullOrEmpty(imagePath))
- {
- FileName = "Blank Page.pdf";
- //默认插入595*842 大小的页面
- PDFViewer.Document.InsertPage(0, 595, 842, null);
- }
- else
- {
- FileName = imagePath.Substring(imagePath.LastIndexOf("\\") + 1, imagePath.LastIndexOf(".") - imagePath.LastIndexOf("\\") - 1) + ".pdf";
- Bitmap pic = new Bitmap(imagePath);
- int width = pic.Size.Width;
- int height = pic.Size.Height;
- string ex = System.IO.Path.GetExtension(imagePath);
- //其他格式或者名称中含空格的图片 在本地先转存一下
- if ((ex != ".jpg" && ex != ".jpeg") || !Uri.IsWellFormedUriString(imagePath, UriKind.Absolute))
- {
- //将其他格式图片转换成jpg
- string folderPath = Path.GetTempPath();
- if (File.Exists(folderPath))
- {
- File.Delete(folderPath);
- }
- DirectoryInfo tempfolder = new DirectoryInfo(folderPath);
- if (!tempfolder.Exists)
- {
- tempfolder.Create();
- }
- string targetPath = System.IO.Path.Combine(folderPath, Guid.NewGuid().ToString());
- imagePath = targetPath;
- pic.Save(targetPath, ImageFormat.Jpeg);
- }
- pic.Dispose();
- var result = PDFViewer.Document.InsertPage(0, width, height, imagePath);
- if (!result)
- {
- AlertsMessage alertsMessage = new AlertsMessage();
- alertsMessage.ShowDialog("", App.MainPageLoader.GetString("Create PDF failed"), App.ServiceLoader.GetString("Text_ok"));
- return false;
- }
- }
- SaveToTempFile();
- PDFViewer.UndoManager.CanSave = true;
- FileChanged = Visibility.Visible;
- NavigateToViewContent();
- return true;
- }
- /// <summary>
- /// 从office文件转换成PDF
- /// </summary>
- /// <param name="sourcepath"></param>
- /// <returns></returns>
- public bool CreateFileFromOffice(string sourcepath, Microsoft.Office.Interop.Word.WdPaperSize paperSize = Microsoft.Office.Interop.Word.WdPaperSize.wdPaperA4, double margin = 0)
- {
- try
- {
- string targetPath = "";
- targetPath = ConverterHelper.ConvertOfficeToPDF(sourcepath, paperSize, margin);
- PDFViewer = new CPDFViewer();
- PDFViewer.CreateDocument();
- if (PDFViewer.Document == null)
- {
- AlertsMessage alertsMessage = new AlertsMessage();
- alertsMessage.ShowDialog("", App.MainPageLoader.GetString("Create PDF failed"), App.ServiceLoader.GetString("Text_ok"));
- return false;
- }
- FileName = sourcepath.Substring(sourcepath.LastIndexOf("\\") + 1, sourcepath.LastIndexOf(".") - sourcepath.LastIndexOf("\\") - 1) + ".pdf";
- var tempdoc = CPDFDocument.InitWithFilePath(targetPath);
- if (tempdoc == null)
- {
- AlertsMessage alertsMessage = new AlertsMessage();
- alertsMessage.ShowDialog("", App.MainPageLoader.GetString("Create PDF failed"), App.ServiceLoader.GetString("Text_ok"));
- return false;
- }
- PDFViewer.Document.ImportPages(tempdoc, "");
- SaveToTempFile();
- PDFViewer.UndoManager.CanSave = true;
- FileChanged = Visibility.Visible;
- //await System.Windows.Application.Current.Dispatcher.BeginInvoke(System.Windows.Threading.DispatcherPriority.Send, new Action(() =>
- //{
- NavigateToViewContent();
- //}));
- return true;
- }
- catch (Exception)
- {
- string str = "没有安装";
- //判断是否有安装office软件
- var officeType = Type.GetTypeFromProgID("Word.Application");
- if (officeType == null)
- {
- str += "Word;";
- }
- officeType = Type.GetTypeFromProgID("Excel.Application");
- if (officeType == null)
- {
- str += "Excel;";
- }
- officeType = Type.GetTypeFromProgID("Powerpoint.Application");
- if (officeType == null)
- {
- str += "Excel;";
- }
- AlertsMessage alertsMessage = new AlertsMessage();
- if (str != "没有安装")
- {
- alertsMessage.ShowDialog("", App.MainPageLoader.GetString("NoOffice_Warning"), App.ServiceLoader.GetString("Text_ok"));
- }
- else
- {
- alertsMessage.ShowDialog("", App.MainPageLoader.GetString("CreateFileFailedWarning"), App.ServiceLoader.GetString("Text_ok"));
- }
- return false;
- }
- }
- /// <summary>
- /// 新建的文档 保存至临时文件 解决新建文档没有路径的问题
- /// </summary>
- private void SaveToTempFile()
- {
- if (PDFViewer != null)
- {
- string tempfile = CacheFilePath.Instance.CreatedFilePath;
- string file = CommonHelper.CreateFilePath(Path.Combine(tempfile, App.UntitledFileNmae));
- PDFViewer.Document.WriteToFilePath(file);
- PDFViewer.CloseDocument();
- PDFViewer.InitDocument(file);
- FilePath = file;
- //在viewcontent里打开是 会重新load 因此这里不需要load 避免重复
- NewFile = true;
- }
- }
- private void UndoManager_PropertyChanged(object sender, PropertyChangedEventArgs e)
- {
- if (e.PropertyName == "CanSave")
- {
- if (PDFViewer.UndoManager.CanSave)
- {
- FileChanged = Visibility.Visible;
- }
- else
- {
- FileChanged = Visibility.Collapsed;
- }
- //保存完后,需要更新产品名字
- if (!PDFViewer.UndoManager.CanSave && !string.IsNullOrEmpty(PDFViewer.Document.FileName))
- {
- FileName = System.IO.Path.GetFileName(PDFViewer.Document.FilePath);
- }
- }
- }
- #region Navigation
- public async void OnNavigatedTo(NavigationContext navigationContext)
- {
- mainWindowViewModel = App.mainWindowViewModel;
- //因为是异步打开多个文件,需要先显示Home界面
- NavigationParameters parameters = new NavigationParameters();
- parameters.Add(ParameterNames.MainViewModel, this);
- if (toolregion.Regions.ContainsRegionWithName(MainContentRegionName))
- {
- toolregion.RequestNavigate(MainContentRegionName, "HomeContent", parameters);
- }
- //常规加载首页的情况
- if (navigationContext.Parameters.Count <= 0)
- {
- return;
- }
- //一次打开多个文件的情况
- var filepath = navigationContext.Parameters[ParameterNames.FilePath].ToString();
- if (filepath != null)
- {
- homeContentViewModel.IsLoading = Visibility.Visible;
- await Task.Delay(3);
- bool result = true;
- if (System.IO.Path.GetExtension(filepath.ToString()).ToLower() == ".pdf")
- {
- OpenFile(filepath.ToString());
- }
- else if (Properties.Resources.imageex.Contains(System.IO.Path.GetExtension(filepath).ToLower()))
- {
- //图片转PDF
- result = CreateFile(filepath);
- }
- else
- {
- result = CreateFileFromOffice(filepath);
- }
- homeContentViewModel.IsLoading = Visibility.Collapsed;
- if (!result)
- {
- mainWindowViewModel.CloseTabItem(mainWindowViewModel.SelectedItem);
- return;
- }
- if (!App.OpenedFileList.Contains(filepath))
- {
- //更新已打开的文件记录
- App.OpenedFileList.Add(filepath);
- }
- }
- }
- public bool IsNavigationTarget(NavigationContext navigationContext)
- {
- return false;
- }
- public void OnNavigatedFrom(NavigationContext navigationContext)
- {
- }
- #endregion Navigation
- }
- }
|