123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574 |
- 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<string> fileNames;
- private int fileNamesIndex = 0;
- private int FileNameNumber = 0;
- public IDialogService dialogs;
- public List<int> fileNamesView = new List<int>();
- 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<string>(ParameterNames.PassWord) != null)
- {
- topdfdoc.UnlockWithPassword(e.Parameters.GetValue<string>(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;
- }
- /// <summary>
- /// 设置保存后的文件名
- /// </summary>
- 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 批量处理逻辑函数
- /// <summary>
- /// 选择PDF文件
- /// </summary>
- 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;
- }
- }
- /// <summary>
- /// 添加图片文件
- /// </summary>
- 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("待确定");
- }
- /// <summary>
- /// 添加图片文件夹
- /// </summary>
- 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;
- }
- }
- /// <summary>
- /// 删除图片文件
- /// </summary>
- 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("待确定");
- }
- /// <summary>
- /// 打开文件图片
- /// </summary>
- public void openfiledialog(){
- foreach (int filenamesview in fileNamesView)
- {
- System.Diagnostics.Process.Start(fileNames[filenamesview]);
- }
- }
- /// <summary>
- /// 删除重复的文件
- /// </summary>
- public void RemoveExcess(ref List<string> Filenames) {
- List<string> filenames = new List<string>();
- foreach (var fileName in Filenames)
- {
- if (!filenames.Contains(fileName))
- {
- filenames.Add(fileName);
- }
- }
- Filenames.Clear();
- Filenames = filenames;
- }
- /// <summary>
- /// 逆序int类型集合
- /// </summary>
- public void Reverseorder(ref List<int> Numbers)
- {
- Numbers=Numbers.OrderBy(a=>a).ToList();
- Numbers.Reverse();
- }
- /// <summary>
- /// 更新listview显示
- /// state 状态显示字符串
- /// </summary>
- 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;
- }
- /// <summary>
- /// 更新Currentlistview显示
- /// pagerangetext 自定义页面范围字符串 pagerangeselectindex combobox下拉索引(0全部页面 1奇数页 2偶数页 3自定义页面)isevenpageisenabled 偶数页状态 state 状态显示字符串
- /// </summary>
- 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 图片转换
- /// <summary>
- /// 图片转PNG
- /// picturefile 图片文件名
- /// filePath 保存路径
- /// </summary>
- 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;
- }
- }
- /// <summary>
- /// 图片转JPeG
- /// picturefile 图片文件名
- /// filePath 保存路径
- /// </summary>
- 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;
- }
- }
- /// <summary>
- /// 插入JPeG图片
- /// topdfdoc 所要插入的文档
- /// filename 图片文件名
- /// fileinfo 文件信息
- /// width page宽
- /// height page高
- /// index 插入位置
- /// </summary>
- 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<IDialogResult> RequestClose;
- public bool CanCloseDialog()
- {
- return true;
- }
- public void OnDialogClosed()
- {
- }
- public void OnDialogOpened(IDialogParameters parameters)
- {
- string[] filepath=null;
- parameters.TryGetValue<string[]>(ParameterNames.FilePath, out filepath);
- if (filepath!=null)
- {
- fileNames=filepath.ToList();
-
- updateListview("待确定");
- }
- }
- #endregion
- }
- }
|