using Prism.Commands; using Prism.Mvvm; using System; using System.Collections.Generic; using System.Linq; using System.Data; using System.Windows; using PDF_Master.Helper; using Prism.Regions; using ComPDFKit.PDFDocument; using PDF_Master.CustomControl; using PDF_Master.Model.Dialog.HomePageToolsDialogs.HomePageBatchProcessing; using PDF_Master.Model; using System.Diagnostics; using System.IO; using System.Windows.Forms; using Prism.Events; using ComPDFKitViewer.PdfViewer; using PDF_Master.EventAggregators; using PDFSettings; using PDF_Master.Model.EditTools.Bates; using PDF_Master.Model.EditTools.Background; using static System.Windows.Forms.VisualStyles.VisualStyleElement.TrayNotify; using Prism.Services.Dialogs; namespace PDF_Master.ViewModels.Dialog.HomePageToolsDialogs.HomePageBatchProcessing.HomePageBackground { public class HomePageBackgroundDialogViewModel : BindableBase, INavigationAware { #region 参数和属性 private List fileNames; public BackgroundInfo BackgroundInfo; private CPDFDocument tempDocument; public string PageNumber = ""; private CPDFBackground background; public IRegionManager backgroundRegion; public IEventAggregator eventAggregator; public IDialogService dialogs; private CPDFViewer PDFViewer; private ViewContentViewModel viewContentViewModel; public string TemplateListBaseName = "HomePageBackgroundTemplateListBaseContent"; public string CreateBaseName = "HomePageBackgroundCreateBaseContent"; public string CreateModColorName = "HomePageBackgroundCreateColorContent"; public string CreateModFileName = "HomePageBackgroundCreateFileContent"; public string TemplateListModColorName = "HomePageBackgroundTemplateListColorContent"; public string TemplateListModFileName = "HomePageBackgroundTemplateListFileContent"; private string _backgroundSettingsRegionName; /// /// 属性设置Region /// public string BackgroundSettingsRegionName { get { return _backgroundSettingsRegionName; } set { _backgroundSettingsRegionName = value; } } private Visibility _backgroundSettingsVisible = Visibility.Collapsed; /// /// 属性设置Region可见 /// public Visibility BackgroundSettingsVisible { get { return _backgroundSettingsVisible; } set { _backgroundSettingsVisible = value; } } private EnumColorOrFile _currentCreateMod; public EnumColorOrFile CurrentCreateMod { get { return _currentCreateMod; } set { _currentCreateMod = value; } } private EnumColorOrFile _currentTemplateListMod; public EnumColorOrFile CurrentTemplateListMod { get { return _currentTemplateListMod; } set { _currentTemplateListMod = value; } } public List fileNamesView = new List(); private int fileNamesIndex = 0; private int FileNameNumber = 0; private string backgroundGridIsEnabled = "True"; public string BackgroundGridIsEnabled { get { return backgroundGridIsEnabled; } set { SetProperty(ref backgroundGridIsEnabled, value); } } private string setBackgroundGridIsEnabled = "True"; public string SetBackgroundGridIsEnabled { get { return setBackgroundGridIsEnabled; } set { SetProperty(ref setBackgroundGridIsEnabled, value); } } private DataTable pdfDataTable = new DataTable(); public DataTable PDFDataTable { get { return pdfDataTable; } set { SetProperty(ref pdfDataTable, value); } } private DataTable pdfCurrentDataTable = new DataTable(); public DataTable PDFCurrentDataTable { get { return pdfCurrentDataTable; } set { SetProperty(ref pdfCurrentDataTable, value); } } private string removeIsEnable = "False"; public string RemoveIsEnable { get { return removeIsEnable; } set { SetProperty(ref removeIsEnable, value); } } private string selectFileName = "False"; public string SelectFileName { get { return selectFileName; } set { SetProperty(ref selectFileName, value); } } private string backgroundRegionName; public string BackgroundRegionName { get { return backgroundRegionName; } set { SetProperty(ref backgroundRegionName, value); } } private Visibility backgroundVisible = Visibility.Collapsed; public Visibility BackgroundVisible { get { return backgroundVisible; } set { SetProperty(ref backgroundVisible, value); } } private Visibility addFileVisibility = Visibility.Hidden; public Visibility AddFileVisibility { get { return addFileVisibility; } set { SetProperty(ref addFileVisibility, value); RaisePropertyChanged(); } } private string createGridSpan = "1"; public string CreateGridSpan { get { return createGridSpan; } set { SetProperty(ref createGridSpan, value); RaisePropertyChanged(); } } private Visibility createGridSpanVisibility = Visibility.Visible; public Visibility CreateGridSpanVisibility { get { return createGridSpanVisibility; } set { SetProperty(ref createGridSpanVisibility, value); RaisePropertyChanged(); } } private bool _createBtnIsEnabled = false; public bool CreateBtnIsEnabled { get { return _createBtnIsEnabled; } set { SetProperty(ref _createBtnIsEnabled, value); } } #endregion #region 委托声明 public DelegateCommand ADDPDFCommand { get; set; } public DelegateCommand ADDOpenedPDFCommand { get; set; } public DelegateCommand RemovePDFFileCommand { get; set; } public DelegateCommand CreateCommand { get; set; } public DelegateCommand ADDPDFFilesCommand { get; set; } #endregion public string Unicode = null; public HomePageBackgroundDialogViewModel(IRegionManager backgroundRegion, IEventAggregator eventAggregator, IDialogService dialogs) { this.eventAggregator = eventAggregator; this.backgroundRegion = backgroundRegion; this.dialogs = dialogs; PDFCurrentDataTable.Columns.Add("FilePageRangeText"); PDFCurrentDataTable.Columns.Add("FilePageRangeSelectIndex"); PDFCurrentDataTable.Columns.Add("IsEvenPageIsEnabled"); PDFCurrentDataTable.Columns.Add("FileState"); PDFDataTable.Columns.Add("FileName"); PDFDataTable.Columns.Add("FilePageRangeText"); PDFDataTable.Columns.Add("FilePageRangeSelectIndex"); PDFDataTable.Columns.Add("IsEvenPageIsEnabled"); PDFDataTable.Columns.Add("MaxPageRange"); PDFDataTable.Columns.Add("FileSize"); PDFDataTable.Columns.Add("FileState"); Unicode = Guid.NewGuid().ToString(); BackgroundSettingsVisible = Visibility.Visible; ADDPDFCommand = new DelegateCommand(addpicture); ADDOpenedPDFCommand = new DelegateCommand(addOpenedPDFFiles); ADDPDFFilesCommand = new DelegateCommand(addpicturefiles); RemovePDFFileCommand = new DelegateCommand(removepdffile); CreateCommand = new DelegateCommand(create); BackgroundSettingsRegionName = Guid.NewGuid().ToString(); eventAggregator.GetEvent().Subscribe(EnterTemplateListOrCreate, e => e.Unicode == Unicode); eventAggregator.GetEvent().Subscribe(SetCurrentCreateMod, e => e.Unicode == Unicode); eventAggregator.GetEvent().Subscribe(SetCurrentTemplateListMod, e => e.Unicode == Unicode); eventAggregator.GetEvent().Subscribe(EditBackgroundTemplateItem, e => e.Unicode == Unicode); } #region 逻辑函数 public void EnterTemplateListOrCreate(EnumTemplateListOrCreateUnicode enumTemplateListOrCreateunicode) { EnumTemplateListOrCreate enumTemplateListOrCreate = enumTemplateListOrCreateunicode.Status; if (enumTemplateListOrCreate == EnumTemplateListOrCreate.StatusTemplate) { CreateGridSpan = "1"; CreateGridSpanVisibility = Visibility.Visible; EnterSelectedContent(TemplateListBaseName); } else { CreateGridSpan = "2"; CreateGridSpanVisibility = Visibility.Collapsed; EnterSelectedContent(CreateBaseName); } } public void EnterSelectedContent(string SelectedContentName) { NavigationParameters param = new NavigationParameters(); param.Add(ParameterNames.PDFViewer, PDFViewer); param.Add("Unicode", Unicode); param.Add("ViewModel", this); if (SelectedContentName == TemplateListBaseName) { param.Add("CurrentCreateModName", CurrentCreateMod); } else if (SelectedContentName == CreateBaseName) { param.Add("CurrentTemplateListModName", CurrentTemplateListMod); } backgroundRegion.RequestNavigate(BackgroundSettingsRegionName, SelectedContentName, param); BackgroundSettingsVisible = Visibility.Visible; } public void SetCurrentCreateMod(stringUnicode currentCreateModNameunicode) { string currentCreateModName = currentCreateModNameunicode.Status; if (currentCreateModName == CreateModColorName) { CurrentCreateMod = EnumColorOrFile.StatusColor; } else if (currentCreateModName == CreateModFileName) { CurrentCreateMod = EnumColorOrFile.StatusFile; } } public void SetCurrentTemplateListMod(stringUnicode currentTemplateListModNameunicode) { string currentTemplateListModName = currentTemplateListModNameunicode.Status; if (currentTemplateListModName == TemplateListModColorName) { CurrentTemplateListMod = EnumColorOrFile.StatusColor; } else if (currentTemplateListModName == TemplateListModFileName) { CurrentTemplateListMod = EnumColorOrFile.StatusFile; } } public void EditBackgroundTemplateItem(BackgroundItemUnicode backgroundItemunicode) { BackgroundItem backgroundItem = backgroundItemunicode.Status; NavigationParameters param = new NavigationParameters(); param.Add(ParameterNames.PDFViewer, PDFViewer); param.Add("CurrentTemplateListModName", CurrentTemplateListMod); param.Add("Unicode", Unicode); param.Add("BackgroundItem", backgroundItem); backgroundRegion.RequestNavigate(BackgroundSettingsRegionName, CreateBaseName, param); BackgroundSettingsVisible = Visibility.Visible; CreateGridSpan = "2"; CreateGridSpanVisibility = Visibility.Collapsed; } private void create() { FolderBrowserDialog dlg = new FolderBrowserDialog(); string saveSelectedPath = ""; if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK) { saveSelectedPath = dlg.SelectedPath.Trim(); saveSelectedPath = saveSelectedPath + "\\"; } else { return; } HomePageBatchProcessingDialogModel.closeDialog = true; updateListview("wait"); fileNamesIndex = 0; BackgroundGridIsEnabled = "False"; foreach (var filename in fileNames) { FileInfo fileinfo = new FileInfo(filename); string OutputPath = fileinfo.DirectoryName; char[] enumerationSeparator = new char[] { ',' }; char[] rangeSeparator = new char[] { '-' }; List PageIndexLists = new List(); CPDFDocument document = CPDFDocument.InitWithFilePath(filename); if (document == null) { PDFDataTable.Rows[fileNamesIndex]["FileState"] = "error"; PDFCurrentDataTable.Rows[fileNamesIndex]["FileState"] = "error"; fileNamesIndex++; continue; } if (document.IsLocked) { DialogParameters value = new DialogParameters(); value.Add(ParameterNames.PDFDocument, document); dialogs.ShowDialog(DialogNames.VerifyPassWordDialog, value, e => { if (e.Result == ButtonResult.OK) { if (e.Parameters.ContainsKey(ParameterNames.PassWord) && e.Parameters.GetValue(ParameterNames.PassWord) != null) { document.UnlockWithPassword(e.Parameters.GetValue(ParameterNames.PassWord).ToString()); } } }); if (document.IsLocked) { //未成功解密文档时,释放Document对象,返回 PDFDataTable.Rows[fileNamesIndex]["FileState"] = "error"; PDFCurrentDataTable.Rows[fileNamesIndex]["FileState"] = "error"; fileNamesIndex++; continue; } } CreateBackground(document); document.WriteToFilePath(CommonHelper.CreateFilePath(saveSelectedPath + document.FileName + "_Background.pdf")); // if (!CommonHelper.GetPagesInRange(ref PageIndexLists, "1-" + document.PageCount.ToString(), document.PageCount, enumerationSeparator, rangeSeparator)) // { //TODO // Trace.WriteLine("输入不对"); // MessageBoxEx.Show("输入不对"); // return; // } document.Release(); PDFDataTable.Rows[fileNamesIndex]["FileState"] = "complete"; PDFCurrentDataTable.Rows[fileNamesIndex]["FileState"] = "complete"; fileNamesIndex++; } BackgroundGridIsEnabled = "True"; HomePageBatchProcessingDialogModel.closeDialog = false; } public void CreateBackground(CPDFDocument document) { if (BackgroundInfo != null) { background = document.GetBackground(); if (BackgroundInfo.BackgroundType == C_Background_Type.BG_TYPE_COLOR) { background.SetBackgroundType(C_Background_Type.BG_TYPE_COLOR); background.SetColor(BackgroundInfo.Color); } else { background.SetBackgroundType(C_Background_Type.BG_TYPE_IMAGE); background.SetImage(BackgroundInfo.ImageArray, BackgroundInfo.ImageWidth, BackgroundInfo.ImageHeight, ComPDFKit.Import.C_Scale_Type.fitCenter); } if (!BackgroundInfo.IsRelativeScale) { background.SetScale(1); } else { background.SetScale((float)(BackgroundInfo.Scale / 100)); } background.SetRotation((float)((BackgroundInfo.Rotation / 180) * Math.PI)); background.SetOpacity((byte)(((float)BackgroundInfo.Opacity / 100) * 255)); background.SetVertalign(BackgroundInfo.Vertalign); background.SetHorizalign(BackgroundInfo.Horizalign); background.SetXOffset(BackgroundInfo.HorizOffset); background.SetYOffset(BackgroundInfo.VertOffset); background.SetAllowsPrint(true); background.SetAllowsView(true); background.SetPages(getFilePageRange(document, PDFCurrentDataTable.Rows[fileNamesIndex]["FilePageRangeText"].ToString(), PDFCurrentDataTable.Rows[fileNamesIndex]["FilePageRangeSelectIndex"].ToString())); background.Update(); } } #endregion #region 批量处理逻辑函数 /// /// 添加PDF文件 /// private void addpicture() { FileNameNumber = fileNames.Count; System.Windows.Forms.OpenFileDialog dlg = new System.Windows.Forms.OpenFileDialog(); dlg.Multiselect = true; dlg.Filter = "PDF|*.pdf;*.PDF;"; if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK) { fileNames.AddRange(dlg.FileNames.ToList()); RemoveExcess(ref fileNames); SetBackgroundGridIsEnabled = "True"; AddFileVisibility = Visibility.Collapsed; updateListview("wait"); } } public void addPDFFiles(string filename) { FileNameNumber = fileNames.Count; fileNames.Add(filename); RemoveExcess(ref fileNames); SetBackgroundGridIsEnabled = "True"; AddFileVisibility = Visibility.Collapsed; updateListview("wait"); } /// /// 添加已打开PDF文件 /// public void addOpenedPDFFiles() { FileNameNumber = fileNames.Count; foreach (var filename in App.OpenedFileList) { fileNames.Add(filename); } RemoveExcess(ref fileNames); SetBackgroundGridIsEnabled = "True"; AddFileVisibility = Visibility.Collapsed; updateListview("wait"); } /// /// 删除重复的文件 /// public void RemoveExcess(ref List Filenames) { List filenames = new List(); foreach (var fileName in Filenames) { if (!filenames.Contains(fileName)) { filenames.Add(fileName); } } Filenames.Clear(); Filenames = filenames; } /// /// 添加PDF文件夹 /// private void addpicturefiles() { FileNameNumber = fileNames.Count; FolderBrowserDialog dialog = new FolderBrowserDialog(); dialog.Description = "请选择文件路径"; if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK) { string foldPath = dialog.SelectedPath; var apps = System.IO.Directory.GetFiles(foldPath); foreach (string app in apps) { var fi = new FileInfo(app); if (fi.Extension == ".pdf" || fi.Extension == ".PDF") { fileNames.Add(app); } } RemoveExcess(ref fileNames); updateListview("wait"); SetBackgroundGridIsEnabled = "True"; AddFileVisibility = Visibility.Collapsed; } } /// /// 更新listview显示 /// state 状态显示字符串 /// public void updateListview(string state) { updateCurrentListview(); DataTable pdfdatatable = new DataTable(); pdfdatatable.Columns.Add("FileName"); pdfdatatable.Columns.Add("FilePageRangeText"); pdfdatatable.Columns.Add("FilePageRangeSelectIndex"); pdfdatatable.Columns.Add("IsEvenPageIsEnabled"); pdfdatatable.Columns.Add("MaxPageRange"); pdfdatatable.Columns.Add("FileSize"); pdfdatatable.Columns.Add("FileState"); int datatableindex = 0; List PageIndexLists = new List(); foreach (var fileName in fileNames) { string file_all = fileName; FileInfo f = new FileInfo(file_all); string file_size = (((float)f.Length) / 1024).ToString() + " K"; if (!isEvenPage(fileName) && PDFCurrentDataTable.Rows[datatableindex]["FilePageRangeSelectIndex"].ToString() == "2") { PDFCurrentDataTable.Rows[datatableindex]["FilePageRangeSelectIndex"] = "0"; } int pagecount = CPDFDocument.InitWithFilePath(fileName).PageCount; if (PDFCurrentDataTable.Rows[datatableindex]["FilePageRangeSelectIndex"].ToString() == "3" && !CommonHelper.GetPagesInRange(ref PageIndexLists, PDFCurrentDataTable.Rows[datatableindex]["FilePageRangeText"].ToString(), pagecount, new char[] { ',' }, new char[] { '-' }, true)) { PDFCurrentDataTable.Rows[datatableindex]["FilePageRangeSelectIndex"] = "0"; } pdfdatatable.Rows.Add(f.Name, PDFCurrentDataTable.Rows[datatableindex]["FilePageRangeText"], PDFCurrentDataTable.Rows[datatableindex]["FilePageRangeSelectIndex"], isEvenPage(fileName), pagecount, file_size, PDFCurrentDataTable.Rows[datatableindex]["FileState"]); datatableindex++; } PDFDataTable = pdfdatatable; HomePageBatchProcessingDialogModel.FilePaths = fileNames; } /// /// 更新Currentlistview显示 /// pagerangetext 自定义页面范围字符串 pagerangeselectindex combobox下拉索引(0全部页面 1奇数页 2偶数页 3自定义页面)isevenpageisenabled 偶数页状态 state 状态显示字符串 /// public void updateCurrentListview(string pagerangetext = "1", string pagerangeselectindex = "0", bool isevenpageisenabled = true, string state = "wait") { if (fileNames.Count >= FileNameNumber) { for (int i = 0; fileNames.Count - FileNameNumber > i; i++) { PDFCurrentDataTable.Rows.Add(pagerangetext, pagerangeselectindex, isevenpageisenabled, state); } } else { Reverseorder(ref fileNamesView); foreach (int filenamesview in fileNamesView) { PDFCurrentDataTable.Rows.RemoveAt(filenamesview); } } } /// /// 更新Currentlistview显示 /// pagerangetext 自定义页面范围字符串 pagerangeselectindex combobox下拉索引(0全部页面 1奇数页 2偶数页 3自定义页面) /// public void updateFilesPageRange(string pagerangetext = "1", string pagerangeselectindex = "0") { for (int i = 0; fileNames.Count > i; i++) { PDFDataTable.Rows[i]["FilePageRangeText"] = pagerangetext; PDFDataTable.Rows[i]["FilePageRangeSelectIndex"] = pagerangeselectindex; PDFCurrentDataTable.Rows[i]["FilePageRangeText"] = pagerangetext; PDFCurrentDataTable.Rows[i]["FilePageRangeSelectIndex"] = pagerangeselectindex; } } /// /// 获取文件列表单个文件对应的页码范围 /// document 文档对象 pagerangetext 自定义页面范围字符串 pagerangeselectindex combobox下拉索引(0全部页面 1奇数页 2偶数页 3自定义页面) /// public string getFilePageRange(CPDFDocument document, string pagerangetext = "1", string pagerangeselectindex = "0") { string filePageRange = "1"; EditToolsHelper.GetPageRange(int.Parse(pagerangeselectindex), document, ref filePageRange, pagerangetext); return filePageRange; } /// /// 判断是否关闭偶数页 /// document 文档对象 ) /// public bool isEvenPage(string filename) { CPDFDocument document = CPDFDocument.InitWithFilePath(filename); bool isevenpage = false; if (document.PageCount > 1) { isevenpage = true; } document.Release(); return isevenpage; } /// /// 逆序int类型集合 /// public void Reverseorder(ref List Numbers) { Numbers = Numbers.OrderBy(a => a).ToList(); Numbers.Reverse(); } /// /// 打开文件PDF /// public void openfiledialog() { foreach (int filenamesview in fileNamesView) { System.Diagnostics.Process.Start("Explorer", "/select," + fileNames[filenamesview]); } } /// /// 删除文件PDF /// public void removepdffile() { FileNameNumber = fileNames.Count; Reverseorder(ref fileNamesView); foreach (int filenamesview in fileNamesView) { //Trace.WriteLine(filenamesview); fileNames.Remove(fileNames[filenamesview]); } if (fileNames.Count < 1) { SetBackgroundGridIsEnabled = "False"; AddFileVisibility = Visibility.Visible; } updateListview("wait"); } public void removepdffile(int index) { PDFCurrentDataTable.Rows.RemoveAt(index); fileNames.Remove(fileNames[index]); if (fileNames.Count < 1) { SetBackgroundGridIsEnabled = "False"; AddFileVisibility = Visibility.Visible; } updateListview("wait"); } public void PDFFileCount() { if (fileNames.Count == 0) { SetBackgroundGridIsEnabled = "False"; AddFileVisibility = Visibility.Visible; } else { SetBackgroundGridIsEnabled = "True"; AddFileVisibility = Visibility.Collapsed; } } #endregion #region 构架行为 public void OnNavigatedTo(NavigationContext navigationContext) { List filepath = new List(); navigationContext.Parameters.TryGetValue(ParameterNames.ViewContentViewModel, out viewContentViewModel); navigationContext.Parameters.TryGetValue(ParameterNames.PDFViewer, out PDFViewer); navigationContext.Parameters.TryGetValue>(ParameterNames.FilePath, out filepath); if (filepath != null) { fileNames = filepath; PDFFileCount(); updateListview("wait"); CreateGridSpan = "1"; CreateGridSpanVisibility = Visibility.Visible; EnterSelectedContent(TemplateListBaseName); } } public bool IsNavigationTarget(NavigationContext navigationContext) { return true; } public void OnNavigatedFrom(NavigationContext navigationContext) { } #endregion } }