using PDF_Office.Model; using Prism.Commands; using System.Data; using Prism.Mvvm; using Prism.Services.Dialogs; using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; using System.IO; using System.Diagnostics; using PDF_Office.CustomControl; using System.Windows; using PDF_Office.Helper; using PDF_Office.Model.Dialog.HomePageToolsDialogs; using ComPDFKit.PDFDocument; using System.Drawing; using DialogResult = Prism.Services.Dialogs.DialogResult; namespace PDF_Office.ViewModels.Dialog.HomePageToolsDialogs { public class HomePagePictureToPDFDialogViewModel : BindableBase, IDialogAware { #region 参数和属性 private List fileNames; private int fileNamesIndex = 0; private int FileNameNumber = 0; public IDialogService dialogs; public List fileNamesView = new List(); public HomePagePictureToPDFDialogModel pictureToPDFModel=new HomePagePictureToPDFDialogModel(); private string pictureToPDFGridIsEnabled = "True"; public string PictureToPDFGridIsEnabled { get { return pictureToPDFGridIsEnabled; } set { SetProperty(ref pictureToPDFGridIsEnabled, value); } } private string setPictureToPDFGridIsEnabled = "True"; public string SetPictureToPDFGridIsEnabled { get { return setPictureToPDFGridIsEnabled; } set { SetProperty(ref setPictureToPDFGridIsEnabled, value); } } private DataTable imagesDataTable = new DataTable(); public DataTable ImagesDataTable { get { return imagesDataTable; } set { SetProperty(ref imagesDataTable, value); } } private DataTable imagesCurrentDataTable = new DataTable(); public DataTable ImagesCurrentDataTable { get { return imagesCurrentDataTable; } set { SetProperty(ref imagesCurrentDataTable, 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 Visibility addFileVisibility = Visibility.Hidden; public Visibility AddFileVisibility { get { return addFileVisibility; } set { SetProperty(ref addFileVisibility, value); RaisePropertyChanged(); } } #endregion #region 委托声明 public DelegateCommand ToPDFCommand { get; set; } public DelegateCommand ADDPictureCommand { get; set; } public DelegateCommand ADDPictureFilesCommand { get; set; } public DelegateCommand RemovePictureFileCommand { get; set; } public DelegateCommand SelectFileCommand { get; set; } #endregion public HomePagePictureToPDFDialogViewModel(IDialogService dialogs) { this.dialogs = dialogs; ToPDFCommand = new DelegateCommand(topdf); ADDPictureCommand = new DelegateCommand(addpicture); ADDPictureFilesCommand = new DelegateCommand(addpicturefiles); RemovePictureFileCommand = new DelegateCommand(removepicturefile); SelectFileCommand = new DelegateCommand(selectFile); ImagesDataTable.Columns.Add("FileName"); ImagesDataTable.Columns.Add("FileSize"); ImagesDataTable.Columns.Add("FileState"); ImagesCurrentDataTable.Columns.Add("FileState"); } #region 逻辑函数 private void topdf() { PictureToPDFGridIsEnabled = "False"; if (pictureToPDFModel.Mode == HomePagePictureToPDFDialogModel.ToPDFFileMode.NewFiles) { fileNamesIndex = 0; foreach (var filename in fileNames) { ImagesDataTable.Rows[fileNamesIndex]["FileState"] = "准备转换"; ImagesCurrentDataTable.Rows[fileNamesIndex]["FileState"] = "准备转换"; Image img = Image.FromFile(filename); if (img == null) { ImagesDataTable.Rows[fileNamesIndex]["FileState"] = "文件出错"; ImagesCurrentDataTable.Rows[fileNamesIndex]["FileState"] = "文件出错"; continue; } CPDFDocument topdfdoc = CPDFDocument.CreateDocument(); FileInfo fileinfo = new FileInfo(filename); JpegInsertPage(ref topdfdoc, filename, fileinfo,img.Width,img.Height); Trace.WriteLine("Path.GetTempPath():" + Path.GetTempPath()); topdfdoc.WriteToFilePath(savefilename(filename)); topdfdoc.Release(); string file_size = (((float)fileinfo.Length) / 1024).ToString() + " K"; ImagesDataTable.Rows[fileNamesIndex]["FileState"] = "完成"; ImagesCurrentDataTable.Rows[fileNamesIndex]["FileState"] = "完成"; fileNamesIndex++; } System.Diagnostics.Process.Start("Explorer", "/select," + savefilename(fileNames[0])); } if (pictureToPDFModel.Mode == HomePagePictureToPDFDialogModel.ToPDFFileMode.OneNewFile) { CPDFDocument topdfdoc = CPDFDocument.CreateDocument(); int pageindex = 0; foreach (var filename in fileNames) { ImagesDataTable.Rows[fileNamesIndex]["FileState"] = "准备转换"; ImagesCurrentDataTable.Rows[fileNamesIndex]["FileState"] = "准备转换"; Image img = Image.FromFile(filename); if (img == null) { ImagesDataTable.Rows[fileNamesIndex]["FileState"] = "文件出错"; ImagesCurrentDataTable.Rows[fileNamesIndex]["FileState"] = "文件出错"; continue; } FileInfo fileinfo = new FileInfo(filename); JpegInsertPage(ref topdfdoc, filename, fileinfo,img.Width, img.Height, pageindex); pageindex++; string file_size = (((float)fileinfo.Length) / 1024).ToString() + " K"; ImagesDataTable.Rows[fileNamesIndex]["FileState"] = "完成"; ImagesCurrentDataTable.Rows[fileNamesIndex]["FileState"] = "完成"; fileNamesIndex++; } System.Diagnostics.Process.Start("Explorer", "/select," + savefilename(fileNames[0])); topdfdoc.WriteToFilePath(savefilename(fileNames[0])); topdfdoc.Release(); } if (pictureToPDFModel.Mode == HomePagePictureToPDFDialogModel.ToPDFFileMode.SelectFileName) { CPDFDocument topdfdoc =CPDFDocument.InitWithFilePath(pictureToPDFModel.FilePath); if (topdfdoc == null) { Trace.WriteLine("Document==null"); //TODO MessageBoxEx.Show("文档为空"); PictureToPDFGridIsEnabled = "True"; return; } if (topdfdoc.IsLocked) { DialogParameters value = new DialogParameters(); value.Add(ParameterNames.PDFDocument, topdfdoc); dialogs.ShowDialog(DialogNames.VerifyPassWordDialog, value, e => { if (e.Result == ButtonResult.OK) { if (e.Parameters.ContainsKey(ParameterNames.PassWord) && e.Parameters.GetValue(ParameterNames.PassWord) != null) { topdfdoc.UnlockWithPassword(e.Parameters.GetValue(ParameterNames.PassWord).ToString()); } } }); if (topdfdoc.IsLocked) { //未成功解密文档时,释放Document对象,返回 ImagesDataTable.Rows[fileNamesIndex]["FileState"] = "文件出错"; ImagesCurrentDataTable.Rows[fileNamesIndex]["FileState"] = "文件出错"; fileNamesIndex++; PictureToPDFGridIsEnabled = "True"; return; } } int pageindex = topdfdoc.PageCount; foreach (var filename in fileNames) { ImagesDataTable.Rows[fileNamesIndex]["FileState"] = "准备转换"; ImagesCurrentDataTable.Rows[fileNamesIndex]["FileState"] = "准备转换"; Image img = Image.FromFile(filename); if (img == null) { ImagesDataTable.Rows[fileNamesIndex]["FileState"] = "文件出错"; ImagesCurrentDataTable.Rows[fileNamesIndex]["FileState"] = "文件出错"; continue; } FileInfo fileinfo = new FileInfo(filename); JpegInsertPage(ref topdfdoc, filename, fileinfo, img.Width, img.Height, pageindex); pageindex++; string file_size = (((float)fileinfo.Length) / 1024).ToString() + " K"; ImagesDataTable.Rows[fileNamesIndex]["FileState"] = "完成"; ImagesCurrentDataTable.Rows[fileNamesIndex]["FileState"] = "完成"; fileNamesIndex++; } topdfdoc.WriteToLoadedPath(); System.Diagnostics.Process.Start("Explorer", "/select," + topdfdoc.FilePath); topdfdoc.Release(); } PictureToPDFGridIsEnabled = "True"; fileNamesIndex=0; } /// /// 设置保存后的文件名 /// public string savefilename(string filename) { FileInfo file = new FileInfo(filename); return CommonHelper.CreateFilePath(filename.Replace(file.Name, "") + pictureToPDFModel.FrontFileNameLabel + file.Name + pictureToPDFModel.RearFileNameLabel + ".pdf"); } #endregion #region 批量处理逻辑函数 /// /// 选择PDF文件 /// private void selectFile() { System.Windows.Forms.OpenFileDialog dlg = new System.Windows.Forms.OpenFileDialog(); dlg.Multiselect = false; dlg.Filter = "PDF|*.pdf;*.PDF;"; if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK) { SelectFileName=dlg.FileName; pictureToPDFModel.FilePath = dlg.FileName; } } /// /// 添加图片文件 /// private void addpicture() { FileNameNumber = fileNames.Count; System.Windows.Forms.OpenFileDialog dlg = new System.Windows.Forms.OpenFileDialog(); dlg.Multiselect = true; dlg.Filter = "Picture|*.png;*.PNG;*.jpg;*.JPG;*.bmp;*.gif;*tiff;"; if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK) { fileNames.AddRange(dlg.FileNames.ToList()); RemoveExcess(ref fileNames); SetPictureToPDFGridIsEnabled = "True"; AddFileVisibility = Visibility.Collapsed; updateListview("待确定"); } } public void addPicture(string filename) { FileNameNumber = fileNames.Count; fileNames.Add(filename); RemoveExcess(ref fileNames); SetPictureToPDFGridIsEnabled = "True"; AddFileVisibility = Visibility.Collapsed; updateListview("待确定"); } /// /// 添加图片文件夹 /// 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 == ".png" || fi.Extension == ".jpg" || fi.Extension == ".jpeg" || fi.Extension ==".bmp"|| fi.Extension == ".gif"|| fi.Extension == ".tiff") { fileNames.Add(app); } } RemoveExcess(ref fileNames); updateListview("待确定"); SetPictureToPDFGridIsEnabled = "True"; AddFileVisibility = Visibility.Collapsed; } } /// /// 删除图片文件 /// public void removepicturefile() { FileNameNumber = fileNames.Count; Reverseorder(ref fileNamesView); foreach (int filenamesview in fileNamesView) { //Trace.WriteLine(filenamesview); fileNames.Remove(fileNames[filenamesview]); } if (fileNames.Count < 1) { SetPictureToPDFGridIsEnabled = "False"; AddFileVisibility = Visibility.Visible; } updateListview("待确定"); } public void removepdffile(int index) { ImagesCurrentDataTable.Rows.RemoveAt(index); fileNames.Remove(fileNames[index]); if (fileNames.Count < 1) { SetPictureToPDFGridIsEnabled = "False"; AddFileVisibility = Visibility.Visible; } updateListview("待确定"); } /// /// 打开文件图片 /// public void openfiledialog(){ foreach (int filenamesview in fileNamesView) { System.Diagnostics.Process.Start(fileNames[filenamesview]); } } /// /// 删除重复的文件 /// 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; } /// /// 逆序int类型集合 /// public void Reverseorder(ref List Numbers) { Numbers=Numbers.OrderBy(a=>a).ToList(); Numbers.Reverse(); } /// /// 更新listview显示 /// state 状态显示字符串 /// public void updateListview(string state) { updateCurrentListview(); DataTable imagesdatatable = new DataTable(); imagesdatatable.Columns.Add("FileName"); imagesdatatable.Columns.Add("FileSize"); imagesdatatable.Columns.Add("FileState"); int datatableindex = 0; foreach (var fileName in fileNames) { string file_all = fileName; FileInfo f = new FileInfo(file_all); string file_size = (((float)f.Length)/1024).ToString()+" K"; imagesdatatable.Rows.Add(f.Name, file_size, ImagesCurrentDataTable.Rows[datatableindex]["FileState"]); datatableindex++; } ImagesDataTable = imagesdatatable; } /// /// 更新Currentlistview显示 /// pagerangetext 自定义页面范围字符串 pagerangeselectindex combobox下拉索引(0全部页面 1奇数页 2偶数页 3自定义页面)isevenpageisenabled 偶数页状态 state 状态显示字符串 /// public void updateCurrentListview( string state = "待完成") { if (fileNames.Count >= FileNameNumber) { for (int i = 0; fileNames.Count - FileNameNumber > i; i++) { ImagesCurrentDataTable.Rows.Add(state); } } else { Reverseorder(ref fileNamesView); foreach (int filenamesview in fileNamesView) { ImagesCurrentDataTable.Rows.RemoveAt(filenamesview); } } } #endregion #region 图片转换 /// /// 图片转PNG /// picturefile 图片文件名 /// filePath 保存路径 /// public bool SavePng(string picturefile, string filePath) { Image img = Image.FromFile(picturefile); try { using (var bmp = new Bitmap(img.Width, img.Height)) { bmp.SetResolution(img.HorizontalResolution, img.VerticalResolution); using (var g = Graphics.FromImage(bmp)) { g.Clear(Color.White); g.DrawImageUnscaled(img, 0, 0); } bmp.Save(filePath, System.Drawing.Imaging.ImageFormat.Png); } return true; } catch { return false; } } /// /// 图片转JPeG /// picturefile 图片文件名 /// filePath 保存路径 /// public bool SaveJpeg(string picturefile, string filePath) { Image img = Image.FromFile(picturefile); try { using (var bmp = new Bitmap(img.Width, img.Height)) { bmp.SetResolution(img.HorizontalResolution, img.VerticalResolution); using (var g = Graphics.FromImage(bmp)) { g.Clear(Color.White); g.DrawImageUnscaled(img, 0, 0); } //存储各种格式 //bmp.Save(filePath, System.Drawing.Imaging.ImageFormat.Gif); //bmp.Save(filePath, System.Drawing.Imaging.ImageFormat.Png); bmp.Save(filePath, System.Drawing.Imaging.ImageFormat.Jpeg); } return true; } catch { return false; } } /// /// 插入JPeG图片 /// topdfdoc 所要插入的文档 /// filename 图片文件名 /// fileinfo 文件信息 /// width page宽 /// height page高 /// index 插入位置 /// private void JpegInsertPage(ref CPDFDocument topdfdoc,string filename, FileInfo fileinfo,int width,int height,int index=0) { string tempFileName = ""; if (fileinfo.Extension == ".jpg"|| fileinfo.Extension == ".jpeg") { topdfdoc.InsertPage(index, width, height, filename); } else { tempFileName = Path.GetTempPath() + "pngtemp.jpg"; if (!PictureConverter.SaveJpeg(filename, tempFileName)) { MessageBoxEx.Show("图片格式有问题"); } topdfdoc.InsertPage(index, width, height, tempFileName); } } #endregion #region 构架行为 public string Title => "图片转PDF"; public event Action RequestClose; public bool CanCloseDialog() { return true; } public void OnDialogClosed() { } public void OnDialogOpened(IDialogParameters parameters) { string[] filepath=null; parameters.TryGetValue(ParameterNames.FilePath, out filepath); if (filepath!=null) { fileNames=filepath.ToList(); updateListview("待确定"); } } #endregion } }