using ComPDFKit.PDFDocument; using ComPDFKit_Conversion.Converter; using Microsoft.Office.Interop.Excel; using Microsoft.Office.Interop.Word; using PDF_Office.CustomControl; using PDF_Office.Helper; using PDF_Office.Model; using PDF_Office.Model.Dialog.ConverterDialogs; using PDF_Office.Model.Dialog.HomePageToolsDialogs.HomePageBatchProcessing; using PDF_Office.Model.Dialog.HomePageToolsDialogs.HomePageBatchProcessing.HomePageConverter; using Prism.Commands; using Prism.Mvvm; using Prism.Regions; using Prism.Services.Dialogs; using System; using System.Collections.Generic; using System.Data; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Windows; using System.Windows.Forms; using DataTable = System.Data.DataTable; namespace PDF_Office.ViewModels.Dialog.HomePageToolsDialogs.HomePageBatchProcessing.HomePageConverter { public class HomePageConverterDialogViewModel : BindableBase, INavigationAware { #region 参数和属性 private List fileNames; public HomePageConverterCSVModel ConverterCSVModel = new HomePageConverterCSVModel(); public HomePageConverterExcelModel ConverterExcelModel = new HomePageConverterExcelModel(); public HomePageConverterHTMLModel ConverterHTMLModel = new HomePageConverterHTMLModel(); public HomePageConverterImgModel ConverterImgModel = new HomePageConverterImgModel(); public HomePageConverterPPTModel ConverterPPTModel = new HomePageConverterPPTModel(); public HomePageConverterRTFModel ConverterRTFModel = new HomePageConverterRTFModel(); public HomePageConverterTextModel ConverterTextModel = new HomePageConverterTextModel(); public HomePageConverterWordModel ConverterWordModel = new HomePageConverterWordModel(); private CPDFDocument tempDocument; public string PageNumber = ""; public IRegionManager ConverterRegion; public IDialogService dialogs; public List fileNamesView = new List(); private int fileNamesIndex = 0; private int FileNameNumber = 0; public List ConverterTypeFamily { set; get; } = new List(); private void SetImageTypeOrigin() { this.ConverterTypeFamily.Add("Word"); this.ConverterTypeFamily.Add("Excel"); this.ConverterTypeFamily.Add("PPT"); this.ConverterTypeFamily.Add("RTF"); this.ConverterTypeFamily.Add("HTML"); this.ConverterTypeFamily.Add("Text"); this.ConverterTypeFamily.Add("CSV"); this.ConverterTypeFamily.Add("Img"); } private string converterGridIsEnabled = "True"; public string ConverterGridIsEnabled { get { return converterGridIsEnabled; } set { SetProperty(ref converterGridIsEnabled, value); } } private string setConverterGridIsEnabled = "True"; public string SetConverterGridIsEnabled { get { return setConverterGridIsEnabled; } set { SetProperty(ref setConverterGridIsEnabled, 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 int converterTypeIndex = 0; public int ConverterTypeIndex { get { return converterTypeIndex; } set { SetProperty(ref converterTypeIndex, value); } } private string converterRegionName; public string ConverterRegionName { get { return converterRegionName; } set { SetProperty(ref converterRegionName, value); } } private Visibility converterVisible = Visibility.Collapsed; public Visibility ConverterVisible { get { return converterVisible; } set { SetProperty(ref converterVisible, value); } } private Visibility addFileVisibility = Visibility.Hidden; public Visibility AddFileVisibility { get { return addFileVisibility; } set { SetProperty(ref addFileVisibility, value); RaisePropertyChanged(); } } #endregion #region 委托声明 public DelegateCommand ADDPDFCommand { get; set; } public DelegateCommand RemovePDFFileCommand { get; set; } public DelegateCommand ConvertCommand { get; set; } public DelegateCommand ADDPDFFilesCommand { get; set; } #endregion public HomePageConverterDialogViewModel(IRegionManager converterRegion, IDialogService dialogs) { SetImageTypeOrigin(); 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("FileSize"); PDFDataTable.Columns.Add("FileState"); ADDPDFCommand = new DelegateCommand(addpicture); ADDPDFFilesCommand = new DelegateCommand(addpicturefiles); RemovePDFFileCommand = new DelegateCommand(removepdffile); ConvertCommand = new DelegateCommand(convert); ConverterRegion = converterRegion; this.dialogs = dialogs; ConverterRegionName=Guid.NewGuid().ToString(); } #region 逻辑函数 private void SetProgress(int pageIndex) { PDFDataTable.Rows[fileNamesIndex]["FileState"] = "已经转换" + pageIndex.ToString() + "页"; pageIndex.ToString(); } private async void convert() { updateListview("待确定"); bool result = false; OnProgress GetProgress = null; GetProgress += SetProgress; fileNamesIndex = 0; ConverterGridIsEnabled = "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"] = "文件出错"; PDFCurrentDataTable.Rows[fileNamesIndex]["FileState"] = "文件出错"; fileNamesIndex++; continue; } string DocPassword = ""; 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) { DocPassword = e.Parameters.GetValue(ParameterNames.PassWord).ToString(); document.UnlockWithPassword(DocPassword); } } }); if (document.IsLocked) { //未成功解密文档时,释放Document对象,返回 PDFDataTable.Rows[fileNamesIndex]["FileState"] = "文件出错"; PDFCurrentDataTable.Rows[fileNamesIndex]["FileState"] = "文件出错"; fileNamesIndex++; continue; } } if (!CommonHelper.GetPagesInRange(ref PageIndexLists, "1-" + document.PageCount.ToString(),document.PageCount, enumerationSeparator, rangeSeparator)) { //TODO Trace.WriteLine("输入不对"); MessageBoxEx.Show("输入不对"); return; } switch (ConverterTypeIndex) { case 0: if (ConverterWordModel != null) { PageNumber = ConverterWordModel.PageIndexLists.Count().ToString(); result = await ConverterHelper.WordConvert(filename, OutputPath, GetProgress, PageIndexLists, DocPassword); } break; case 1: if (ConverterExcelModel != null) { PageNumber = ConverterExcelModel.PageIndexLists.Count().ToString(); result = await ConverterHelper.ExcelConvert(filename, OutputPath, GetProgress, PageIndexLists, DocPassword, ConverterExcelModel.excelOption); } break; case 2: if (ConverterPPTModel != null) { PageNumber = ConverterPPTModel.PageIndexLists.Count().ToString(); result = await ConverterHelper.PPTConvert(filename, OutputPath, GetProgress, PageIndexLists, DocPassword); } break; case 3: if (ConverterRTFModel != null) { PageNumber = ConverterRTFModel.PageIndexLists.Count().ToString(); result = await ConverterHelper.RTFConvert(filename, OutputPath, GetProgress, PageIndexLists, DocPassword); } break; case 4: if (ConverterHTMLModel != null) { PageNumber = ConverterHTMLModel.PageIndexLists.Count().ToString(); result = await ConverterHelper.HTMLConvert(filename, OutputPath, GetProgress, PageIndexLists, DocPassword, ConverterHTMLModel.HTMLOptions()); } break; case 5: if (ConverterTextModel != null) { PageNumber = ConverterTextModel.PageIndexLists.Count().ToString(); result = await ConverterHelper.TxtConvert(filename, OutputPath, GetProgress, PageIndexLists, DocPassword); } break; case 6: if (ConverterCSVModel != null) { PageNumber = ConverterCSVModel.PageIndexLists.Count().ToString(); result = await ConverterHelper.CSVConvert(filename, OutputPath, GetProgress, PageIndexLists, DocPassword); } break; case 7: if (ConverterImgModel != null) { PageNumber = ConverterImgModel.PageIndexLists.Count().ToString(); result = await ConverterHelper.ImgConvert(filename, OutputPath, GetProgress, PageIndexLists, DocPassword, ConverterImgModel.Type, ConverterImgModel.imageType); } break; default: break; } document.Release(); PDFDataTable.Rows[fileNamesIndex]["FileState"] = "完成"; PDFCurrentDataTable.Rows[fileNamesIndex]["FileState"] = "完成"; fileNamesIndex++; } ConverterGridIsEnabled = "True"; } #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); SetConverterGridIsEnabled = "True"; AddFileVisibility = Visibility.Collapsed; updateListview("待确定"); } } public void addPDFFiles(string filename) { FileNameNumber = fileNames.Count; fileNames.Add(filename); RemoveExcess(ref fileNames); SetConverterGridIsEnabled = "True"; AddFileVisibility = Visibility.Collapsed; updateListview("待确定"); } /// /// 删除重复的文件 /// 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("待确定"); SetConverterGridIsEnabled = "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("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"; } if (PDFCurrentDataTable.Rows[datatableindex]["FilePageRangeSelectIndex"].ToString() == "3" && !CommonHelper.GetPagesInRange(ref PageIndexLists, PDFCurrentDataTable.Rows[datatableindex]["FilePageRangeText"].ToString(), CPDFDocument.InitWithFilePath(fileName).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), 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 = "待完成") { 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(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) { SetConverterGridIsEnabled = "False"; AddFileVisibility = Visibility.Visible; } updateListview("待确定"); } public void removepdffile(int index) { PDFCurrentDataTable.Rows.RemoveAt(index); fileNames.Remove(fileNames[index]); if (fileNames.Count < 1) { SetConverterGridIsEnabled = "False"; AddFileVisibility = Visibility.Visible; } updateListview("待确定"); } public void PDFFileCount() { if (fileNames.Count == 0) { SetConverterGridIsEnabled = "False"; AddFileVisibility = Visibility.Visible; } else { SetConverterGridIsEnabled = "True"; AddFileVisibility = Visibility.Collapsed; } } public void ChangeConverter(int index) { ConverterTypeIndex=index; NavigationParameters param = new NavigationParameters(); param.Add(ParameterNames.ViewContentViewModel, this); if (index == 0 || index == 1 || index == 6 || index == 7) { ConverterVisible = Visibility.Collapsed; ConverterRegion.RequestNavigate(ConverterRegionName, HomePageConverterDialogModel.GetConverter[index], param); ConverterVisible = Visibility.Visible; } else { ConverterVisible = Visibility.Collapsed; } } #endregion #region 构架行为 public void OnNavigatedTo(NavigationContext navigationContext) { List filepath = new List(); int convertertypeindex=0; navigationContext.Parameters.TryGetValue>(ParameterNames.FilePath, out filepath); navigationContext.Parameters.TryGetValue("ConverterTypeIndex", out convertertypeindex); if (filepath != null) { fileNames = filepath; PDFFileCount(); updateListview("待确定"); ChangeConverter(ConverterTypeIndex); } } public bool IsNavigationTarget(NavigationContext navigationContext) { return true; } public void OnNavigatedFrom(NavigationContext navigationContext) { ConverterHelper.Clear(); } #endregion } }