using PDF_Master.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_Master.CustomControl; using System.Windows; using PDF_Master.Helper; using PDF_Master.Model.Dialog.HomePageToolsDialogs; using ComPDFKit.PDFDocument; using System.Drawing; using DialogResult = Prism.Services.Dialogs.DialogResult; namespace PDF_Master.ViewModels.Dialog.HomePageToolsDialogs { public class HomePagePictureToPDFDialogViewModel : BindableBase, IDialogAware { #region 文案 private string T_title; public string T_Title { get { return T_title; } set { SetProperty(ref T_title, value); } } private string T_addFolder; public string T_AddFolder { get { return T_addFolder; } set { SetProperty(ref T_addFolder, value); } } private string T_addFile; public string T_AddFile { get { return T_addFile; } set { SetProperty(ref T_addFile, value); } } private string T_emptyContext; public string T_EmptyContext { get { return T_emptyContext; } set { SetProperty(ref T_emptyContext, value); } } private string T_settings; public string T_Settings { get { return T_settings; } set { SetProperty(ref T_settings, value); } } private string T_exportTitle; public string T_ExportTitle { get { return T_exportTitle; } set { SetProperty(ref T_exportTitle, value); } } private string T_create; public string T_Create { get { return T_create; } set { SetProperty(ref T_create, value); } } private string T_merge; public string T_Merge { get { return T_merge; } set { SetProperty(ref T_merge, value); } } private string T_emptySelectFiles; public string T_EmptySelectFiles { get { return T_emptySelectFiles; } set { SetProperty(ref T_emptySelectFiles, value); } } private string T_export; public string T_Export { get { return T_export; } set { SetProperty(ref T_export, value); } } private string T_saveAsPDF; public string T_SaveAsPDF { get { return T_saveAsPDF; } set { SetProperty(ref T_saveAsPDF, value); } } private void InitString() { T_Title = App.MainPageLoader.GetString("ImageToPDF_Title"); T_AddFolder = App.MainPageLoader.GetString("ImageToPDF_AddFolder"); T_AddFile = App.MainPageLoader.GetString("ImageToPDF_AddFile"); T_EmptySelectFiles = App.MainPageLoader.GetString("ImageToPDF_SelectFiles"); T_EmptyContext = App.MainPageLoader.GetString("ImageToPDF_EmptyContext"); T_Settings = App.MainPageLoader.GetString("ImageToPDF_Settings"); T_ExportTitle = App.MainPageLoader.GetString("ImageToPDF_ExportTitle"); T_Create = App.MainPageLoader.GetString("ImageToPDF_Create"); T_Merge = App.MainPageLoader.GetString("ImageToPDF_Merge"); T_SaveAsPDF= App.MainPageLoader.GetString("ImageToPDF_SaveAsPDF"); } #endregion #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 = "True"; public string RemoveIsEnable { get { return removeIsEnable; } set { SetProperty(ref removeIsEnable, value); } } private string imageToPDFBtnIsEnable = "True"; public string ImageToPDFBtnIsEnable { get { return imageToPDFBtnIsEnable; } set { SetProperty(ref imageToPDFBtnIsEnable, value); } } private string selectFileName = "File"; 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) { InitString(); this.dialogs = dialogs; ToPDFCommand = new DelegateCommand(topdf); ADDPictureCommand = new DelegateCommand(addpicture); ADDPictureFilesCommand = new DelegateCommand(addpicturefiles); RemovePictureFileCommand = new DelegateCommand(removepicturefiles); SelectFileCommand = new DelegateCommand(selectFile); ImagesDataTable.Columns.Add("FileName"); ImagesDataTable.Columns.Add("FileSize"); ImagesDataTable.Columns.Add("FileState"); ImagesCurrentDataTable.Columns.Add("FileState"); this.dialogs = dialogs; } #region 逻辑函数 private void topdf() { PictureToPDFGridIsEnabled = "False"; if (pictureToPDFModel.Mode == HomePagePictureToPDFDialogModel.ToPDFFileMode.NewFiles) { FolderBrowserDialog dlg = new FolderBrowserDialog(); string saveSelectedPath = ""; string SaveSelectedPath = ""; if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK) { SaveSelectedPath = dlg.SelectedPath.Trim(); saveSelectedPath = SaveSelectedPath + "\\"; } else { PictureToPDFGridIsEnabled = "True"; return; } fileNamesIndex = 0; string fileName = ""; foreach (var filename in fileNames) { ImagesDataTable.Rows[fileNamesIndex]["FileState"] = "wait"; ImagesCurrentDataTable.Rows[fileNamesIndex]["FileState"] = "wait"; try { Image img = Image.FromFile(filename); if (img == null) { ImagesDataTable.Rows[fileNamesIndex]["FileState"] = "error"; ImagesCurrentDataTable.Rows[fileNamesIndex]["FileState"] = "error"; fileNamesIndex++; 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()); fileName = savefilename(filename, saveSelectedPath); topdfdoc.WriteToFilePath(fileName); topdfdoc.Release(); string file_size = (((float)fileinfo.Length) / 1024).ToString() + " K"; ImagesDataTable.Rows[fileNamesIndex]["FileState"] = "complete"; ImagesCurrentDataTable.Rows[fileNamesIndex]["FileState"] = "complete"; fileNamesIndex++; } catch { ImagesDataTable.Rows[fileNamesIndex]["FileState"] = "error"; ImagesCurrentDataTable.Rows[fileNamesIndex]["FileState"] = "error"; fileNamesIndex++; continue; } //System.Diagnostics.Process.Start("Explorer", "/select," + fileName); } System.Diagnostics.Process.Start("Explorer", "/select," + fileName); } if (pictureToPDFModel.Mode == HomePagePictureToPDFDialogModel.ToPDFFileMode.OneNewFile) { CPDFDocument topdfdoc = CPDFDocument.CreateDocument(); int pageindex = 0; FolderBrowserDialog folderDialog = new FolderBrowserDialog(); System.Windows.Forms.SaveFileDialog sfd = new System.Windows.Forms.SaveFileDialog(); sfd.FileName = "Untitle"; sfd.Filter = "PDF|*.pdf;"; string NewFileName = ""; if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK) { NewFileName = sfd.FileName; } else { PictureToPDFGridIsEnabled = "True"; return; } foreach (var filename in fileNames) { ImagesDataTable.Rows[fileNamesIndex]["FileState"] = "wait"; ImagesCurrentDataTable.Rows[fileNamesIndex]["FileState"] = "wait"; Image img = Image.FromFile(filename); if (img == null) { ImagesDataTable.Rows[fileNamesIndex]["FileState"] = "error"; ImagesCurrentDataTable.Rows[fileNamesIndex]["FileState"] = "error"; 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"] = "complete"; ImagesCurrentDataTable.Rows[fileNamesIndex]["FileState"] = "complete"; fileNamesIndex++; } System.Diagnostics.Process.Start("Explorer", "/select," + NewFileName); topdfdoc.WriteToFilePath(NewFileName); topdfdoc.Release(); } if (pictureToPDFModel.Mode == HomePagePictureToPDFDialogModel.ToPDFFileMode.SelectFileName) { FolderBrowserDialog dlg = new FolderBrowserDialog(); string saveSelectedPath = ""; if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK) { saveSelectedPath = dlg.SelectedPath.Trim(); saveSelectedPath = saveSelectedPath + "\\"; } else { PictureToPDFGridIsEnabled = "True"; return; } 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"] = "error"; ImagesCurrentDataTable.Rows[fileNamesIndex]["FileState"] = "error"; fileNamesIndex++; PictureToPDFGridIsEnabled = "True"; return; } } int pageindex = topdfdoc.PageCount; foreach (var filename in fileNames) { ImagesDataTable.Rows[fileNamesIndex]["FileState"] = "wait"; ImagesCurrentDataTable.Rows[fileNamesIndex]["FileState"] = "wait"; Image img = Image.FromFile(filename); if (img == null) { ImagesDataTable.Rows[fileNamesIndex]["FileState"] = "error"; ImagesCurrentDataTable.Rows[fileNamesIndex]["FileState"] = "error"; 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"] = "complete"; ImagesCurrentDataTable.Rows[fileNamesIndex]["FileState"] = "complete"; fileNamesIndex++; } string saveselectedpath = CommonHelper.CreateFilePath(saveSelectedPath + topdfdoc.FileName + ".pdf"); topdfdoc.WriteToFilePath(saveselectedpath); System.Diagnostics.Process.Start("Explorer", "/select," + saveselectedpath); topdfdoc.Release(); } PictureToPDFGridIsEnabled = "True"; fileNamesIndex = 0; } /// /// 设置保存后的文件名 /// public string savefilename(string filename, string filepath) { FileInfo file = new FileInfo(filename); return CommonHelper.CreateFilePath(filepath + pictureToPDFModel.FrontFileNameLabel + file.Name.Replace(file.Extension, ".pdf") + pictureToPDFModel.RearFileNameLabel); } #endregion #region 批量处理逻辑函数 /// /// 选择PDF文件 /// private void selectFile() { System.Windows.Forms.OpenFileDialog dlg = new System.Windows.Forms.OpenFileDialog(); dlg.Multiselect = false; dlg.Filter = "PDF|*.pdf;"; if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK) { SelectFileName = dlg.FileName; pictureToPDFModel.FilePath = dlg.FileName; ImageToPDFBtnIsEnable = "True"; } } /// /// 添加图片文件 /// private void addpicture() { FileNameNumber = fileNames.Count; System.Windows.Forms.OpenFileDialog dlg = new System.Windows.Forms.OpenFileDialog(); dlg.Multiselect = true; dlg.Filter = "Picture|*.png;*.jpg;*.bmp;*.gif;*tiff;*jpeg;"; if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK) { fileNames.AddRange(dlg.FileNames.ToList()); RemoveExcess(ref fileNames); SetPictureToPDFGridIsEnabled = "True"; AddFileVisibility = Visibility.Hidden; RemoveIsEnable = "True"; updateListview("wait"); } } public void addPicture(string filename) { FileNameNumber = fileNames.Count; fileNames.Add(filename); RemoveExcess(ref fileNames); SetPictureToPDFGridIsEnabled = "True"; AddFileVisibility = Visibility.Hidden; RemoveIsEnable = "True"; updateListview("wait"); } /// /// 添加图片文件夹 /// 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("wait"); SetPictureToPDFGridIsEnabled = "True"; AddFileVisibility = Visibility.Hidden; RemoveIsEnable = "True"; } } /// /// 删除图片文件 /// /// public void removepicturefiles() {if (fileNamesView.Count > 0) { removepicturefile(); } else { FileNameNumber = fileNames.Count; //Trace.WriteLine(filenamesview); fileNames.Clear(); if (fileNames.Count < 1) { SetPictureToPDFGridIsEnabled = "False"; AddFileVisibility = Visibility.Visible; RemoveIsEnable = "False"; } updateListview("wait"); } } 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; RemoveIsEnable = "False"; } updateListview("wait"); } public void removepdffile(int index) { ImagesCurrentDataTable.Rows.RemoveAt(index); fileNames.Remove(fileNames[index]); if (fileNames.Count < 1) { SetPictureToPDFGridIsEnabled = "False"; AddFileVisibility = Visibility.Visible; RemoveIsEnable = "False"; } updateListview("wait"); } /// /// 打开文件图片 /// public void openfiledialog() { foreach (int filenamesview in fileNamesView) { System.Diagnostics.Process.Start("Explorer", "/select," + 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); if (!f.Exists) { continue; } 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 = "wait") { 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); } } public void CloseDialoge() { RequestClose?.Invoke(new DialogResult(ButtonResult.OK)); } #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("wait"); } } #endregion } }