HomePagePictureToPDFDialogViewModel.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  1. using PDF_Office.Model;
  2. using Prism.Commands;
  3. using System.Data;
  4. using Prism.Mvvm;
  5. using Prism.Services.Dialogs;
  6. using System;
  7. using System.Collections.Generic;
  8. using System.Linq;
  9. using System.Windows.Forms;
  10. using System.IO;
  11. using System.Diagnostics;
  12. using PDF_Office.CustomControl;
  13. using System.Windows;
  14. using PDF_Office.Helper;
  15. using PDF_Office.Model.Dialog.HomePageToolsDialogs;
  16. using ComPDFKit.PDFDocument;
  17. using System.Drawing;
  18. using DialogResult = Prism.Services.Dialogs.DialogResult;
  19. namespace PDF_Office.ViewModels.Dialog.HomePageToolsDialogs
  20. {
  21. public class HomePagePictureToPDFDialogViewModel : BindableBase, IDialogAware
  22. {
  23. #region 参数和属性
  24. private List<string> fileNames;
  25. private int fileNamesIndex = 0;
  26. public List<int> fileNamesView = new List<int>();
  27. public HomePagePictureToPDFDialogModel pictureToPDFModel=new HomePagePictureToPDFDialogModel();
  28. private string pictureToPDFGridIsEnabled = "True";
  29. public string PictureToPDFGridIsEnabled
  30. {
  31. get
  32. {
  33. return pictureToPDFGridIsEnabled;
  34. }
  35. set
  36. {
  37. SetProperty(ref pictureToPDFGridIsEnabled, value);
  38. }
  39. }
  40. private string setPictureToPDFGridIsEnabled = "True";
  41. public string SetPictureToPDFGridIsEnabled
  42. {
  43. get
  44. {
  45. return setPictureToPDFGridIsEnabled;
  46. }
  47. set
  48. {
  49. SetProperty(ref setPictureToPDFGridIsEnabled, value);
  50. }
  51. }
  52. private DataTable imagesDataTable = new DataTable();
  53. public DataTable ImagesDataTable
  54. {
  55. get { return imagesDataTable; }
  56. set
  57. {
  58. SetProperty(ref imagesDataTable, value);
  59. }
  60. }
  61. private string removeIsEnable = "False";
  62. public string RemoveIsEnable
  63. {
  64. get { return removeIsEnable; }
  65. set
  66. {
  67. SetProperty(ref removeIsEnable, value);
  68. }
  69. }
  70. private string selectFileName = "False";
  71. public string SelectFileName
  72. {
  73. get { return selectFileName; }
  74. set
  75. {
  76. SetProperty(ref selectFileName, value);
  77. }
  78. }
  79. private Visibility addFileVisibility = Visibility.Hidden;
  80. public Visibility AddFileVisibility
  81. {
  82. get { return addFileVisibility; }
  83. set
  84. {
  85. SetProperty(ref addFileVisibility, value);
  86. RaisePropertyChanged();
  87. }
  88. }
  89. #endregion
  90. #region 委托声明
  91. public DelegateCommand ToPDFCommand { get; set; }
  92. public DelegateCommand ADDPictureCommand { get; set; }
  93. public DelegateCommand ADDPictureFilesCommand { get; set; }
  94. public DelegateCommand RemovePictureFileCommand { get; set; }
  95. public DelegateCommand SelectFileCommand { get; set; }
  96. #endregion
  97. public HomePagePictureToPDFDialogViewModel()
  98. {
  99. ToPDFCommand = new DelegateCommand(topdf);
  100. ADDPictureCommand = new DelegateCommand(addpicture);
  101. ADDPictureFilesCommand = new DelegateCommand(addpicturefiles);
  102. RemovePictureFileCommand = new DelegateCommand(removepicturefile);
  103. SelectFileCommand = new DelegateCommand(selectFile);
  104. }
  105. #region 逻辑函数
  106. private void topdf() {
  107. PictureToPDFGridIsEnabled = "False";
  108. if (pictureToPDFModel.Mode == HomePagePictureToPDFDialogModel.ToPDFFileMode.NewFiles)
  109. {
  110. fileNamesIndex = 0;
  111. foreach (var filename in fileNames)
  112. {
  113. ImagesDataTable.Rows[fileNamesIndex]["FileState"] = "准备转换";
  114. Image img = Image.FromFile(filename);
  115. if (img == null)
  116. {
  117. ImagesDataTable.Rows[fileNamesIndex]["FileState"] = "文件出错";
  118. continue;
  119. }
  120. CPDFDocument topdfdoc = CPDFDocument.CreateDocument();
  121. FileInfo fileinfo = new FileInfo(filename);
  122. JpegInsertPage(ref topdfdoc, filename, fileinfo,img.Width,img.Height);
  123. Trace.WriteLine("Path.GetTempPath():" + Path.GetTempPath());
  124. topdfdoc.WriteToFilePath(savefilename(filename));
  125. topdfdoc.Release();
  126. string file_size = (((float)fileinfo.Length) / 1024).ToString() + " K";
  127. ImagesDataTable.Rows[fileNamesIndex]["FileState"] = "完成";
  128. fileNamesIndex++;
  129. }
  130. System.Diagnostics.Process.Start("Explorer", "/select," + savefilename(fileNames[0]));
  131. }
  132. if (pictureToPDFModel.Mode == HomePagePictureToPDFDialogModel.ToPDFFileMode.OneNewFile)
  133. {
  134. CPDFDocument topdfdoc = CPDFDocument.CreateDocument();
  135. int pageindex = 0;
  136. foreach (var filename in fileNames) {
  137. ImagesDataTable.Rows[fileNamesIndex]["FileState"] = "准备转换";
  138. Image img = Image.FromFile(filename);
  139. if (img == null)
  140. {
  141. ImagesDataTable.Rows[fileNamesIndex]["FileState"] = "文件出错";
  142. continue;
  143. }
  144. FileInfo fileinfo = new FileInfo(filename);
  145. JpegInsertPage(ref topdfdoc, filename, fileinfo,img.Width, img.Height);
  146. pageindex++;
  147. string file_size = (((float)fileinfo.Length) / 1024).ToString() + " K";
  148. ImagesDataTable.Rows[fileNamesIndex]["FileState"] = "完成";
  149. fileNamesIndex++;
  150. }
  151. System.Diagnostics.Process.Start("Explorer", "/select," + savefilename(fileNames[0]));
  152. topdfdoc.WriteToFilePath(savefilename(fileNames[0]));
  153. topdfdoc.Release();
  154. }
  155. if (pictureToPDFModel.Mode == HomePagePictureToPDFDialogModel.ToPDFFileMode.SelectFileName)
  156. {
  157. CPDFDocument topdfdoc =CPDFDocument.InitWithFilePath(pictureToPDFModel.FilePath);
  158. if (topdfdoc == null)
  159. {
  160. Trace.WriteLine("Document==null");
  161. //TODO
  162. MessageBoxEx.Show("文档为空");
  163. return;
  164. }
  165. if (topdfdoc.IsEncrypted)
  166. {
  167. Trace.WriteLine("youmima");
  168. MessageBoxEx.Show("文档加密");
  169. //TODO
  170. return;
  171. }
  172. int pageindex = topdfdoc.PageCount;
  173. foreach (var filename in fileNames)
  174. {
  175. ImagesDataTable.Rows[fileNamesIndex]["FileState"] = "准备转换";
  176. Image img = Image.FromFile(filename);
  177. if (img == null)
  178. {
  179. ImagesDataTable.Rows[fileNamesIndex]["FileState"] = "文件出错";
  180. continue;
  181. }
  182. FileInfo fileinfo = new FileInfo(filename);
  183. JpegInsertPage(ref topdfdoc, filename, fileinfo, img.Width, img.Height, pageindex);
  184. pageindex++;
  185. string file_size = (((float)fileinfo.Length) / 1024).ToString() + " K";
  186. ImagesDataTable.Rows[fileNamesIndex]["FileState"] = "完成";
  187. fileNamesIndex++;
  188. }
  189. topdfdoc.WriteToLoadedPath();
  190. System.Diagnostics.Process.Start("Explorer", "/select," + topdfdoc.FilePath);
  191. topdfdoc.Release();
  192. }
  193. RequestClose.Invoke(new DialogResult(ButtonResult.OK));
  194. }
  195. /// <summary>
  196. /// 设置保存后的文件名
  197. /// </summary>
  198. public string savefilename(string filename)
  199. {
  200. FileInfo file = new FileInfo(filename);
  201. return filename.Replace(file.Name, "") +pictureToPDFModel.FrontFileNameLabel+file.Name+pictureToPDFModel.RearFileNameLabel+".pdf";
  202. }
  203. /// <summary>
  204. /// 选择PDF文件
  205. /// </summary>
  206. private void selectFile()
  207. {
  208. System.Windows.Forms.OpenFileDialog dlg = new System.Windows.Forms.OpenFileDialog();
  209. dlg.Multiselect = false;
  210. dlg.Filter = "PDF|*.pdf;*.PDF;";
  211. if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
  212. {
  213. SelectFileName=dlg.FileName;
  214. pictureToPDFModel.FilePath = dlg.FileName;
  215. }
  216. }
  217. /// <summary>
  218. /// 添加图片文件
  219. /// </summary>
  220. private void addpicture()
  221. {
  222. System.Windows.Forms.OpenFileDialog dlg = new System.Windows.Forms.OpenFileDialog();
  223. dlg.Multiselect = true;
  224. dlg.Filter = "Picture|*.png;*.PNG;*.jpg;*.JPG;*.bmp;*.gif;*tiff;";
  225. if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
  226. {
  227. fileNames.AddRange(dlg.FileNames.ToList());
  228. RemoveExcess(ref fileNames);
  229. SetPictureToPDFGridIsEnabled = "True";
  230. AddFileVisibility = Visibility.Collapsed;
  231. updateListview("待确定");
  232. }
  233. }
  234. /// <summary>
  235. /// 添加图片文件夹
  236. /// </summary>
  237. private void addpicturefiles()
  238. {
  239. FolderBrowserDialog dialog = new FolderBrowserDialog();
  240. dialog.Description = "请选择文件路径";
  241. if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
  242. {
  243. string foldPath = dialog.SelectedPath;
  244. var apps = System.IO.Directory.GetFiles(foldPath);
  245. foreach (string app in apps)
  246. {
  247. var fi = new FileInfo(app);
  248. if (fi.Extension == ".png" || fi.Extension == ".jpg" || fi.Extension == ".jpeg" || fi.Extension ==".bmp"|| fi.Extension == ".gif"|| fi.Extension == ".tiff")
  249. {
  250. fileNames.Add(app);
  251. }
  252. }
  253. RemoveExcess(ref fileNames);
  254. updateListview("待确定");
  255. SetPictureToPDFGridIsEnabled = "True";
  256. AddFileVisibility = Visibility.Collapsed;
  257. }
  258. }
  259. /// <summary>
  260. /// 删除图片文件
  261. /// </summary>
  262. public void removepicturefile() {
  263. Reverseorder(ref fileNamesView);
  264. foreach (int filenamesview in fileNamesView)
  265. {
  266. //Trace.WriteLine(filenamesview);
  267. fileNames.Remove(fileNames[filenamesview]);
  268. }
  269. if (fileNames.Count < 1)
  270. {
  271. SetPictureToPDFGridIsEnabled = "False";
  272. AddFileVisibility = Visibility.Visible;
  273. }
  274. updateListview("待确定");
  275. }
  276. /// <summary>
  277. /// 打开文件图片
  278. /// </summary>
  279. public void openfiledialog(){
  280. foreach (int filenamesview in fileNamesView)
  281. {
  282. System.Diagnostics.Process.Start(fileNames[filenamesview]);
  283. }
  284. }
  285. /// <summary>
  286. /// 删除重复的文件
  287. /// </summary>
  288. public void RemoveExcess(ref List<string> Filenames) {
  289. List<string> filenames = new List<string>();
  290. foreach (var fileName in Filenames)
  291. {
  292. if (!filenames.Contains(fileName))
  293. {
  294. filenames.Add(fileName);
  295. }
  296. }
  297. Filenames.Clear();
  298. Filenames = filenames;
  299. }
  300. /// <summary>
  301. /// 逆序int类型集合
  302. /// </summary>
  303. public void Reverseorder(ref List<int> Numbers)
  304. {
  305. Numbers=Numbers.OrderBy(a=>a).ToList();
  306. Numbers.Reverse();
  307. }
  308. /// <summary>
  309. /// 更新listview显示
  310. /// state 状态显示字符串
  311. /// </summary>
  312. public void updateListview( string state) {
  313. DataTable imagesdatatable = new DataTable();
  314. imagesdatatable.Columns.Add("FileName");
  315. imagesdatatable.Columns.Add("FileSize");
  316. imagesdatatable.Columns.Add("FileState");
  317. foreach (var fileName in fileNames)
  318. {
  319. string file_all = fileName;
  320. FileInfo f = new FileInfo(file_all);
  321. string file_size = (((float)f.Length)/1024).ToString()+" K";
  322. imagesdatatable.Rows.Add(f.Name, file_size, state);
  323. }
  324. ImagesDataTable = imagesdatatable;
  325. }
  326. /// <summary>
  327. /// 图片转PNG
  328. /// picturefile 图片文件名
  329. /// filePath 保存路径
  330. /// </summary>
  331. public bool SavePng(string picturefile, string filePath)
  332. {
  333. Image img = Image.FromFile(picturefile);
  334. try
  335. {
  336. using (var bmp = new Bitmap(img.Width, img.Height))
  337. {
  338. bmp.SetResolution(img.HorizontalResolution, img.VerticalResolution);
  339. using (var g = Graphics.FromImage(bmp))
  340. {
  341. g.Clear(Color.White);
  342. g.DrawImageUnscaled(img, 0, 0);
  343. }
  344. bmp.Save(filePath, System.Drawing.Imaging.ImageFormat.Png);
  345. }
  346. return true;
  347. }
  348. catch
  349. {
  350. return false;
  351. }
  352. }
  353. /// <summary>
  354. /// 图片转JPeG
  355. /// picturefile 图片文件名
  356. /// filePath 保存路径
  357. /// </summary>
  358. public bool SaveJpeg(string picturefile, string filePath)
  359. {
  360. Image img = Image.FromFile(picturefile);
  361. try
  362. {
  363. using (var bmp = new Bitmap(img.Width, img.Height))
  364. {
  365. bmp.SetResolution(img.HorizontalResolution, img.VerticalResolution);
  366. using (var g = Graphics.FromImage(bmp))
  367. {
  368. g.Clear(Color.White);
  369. g.DrawImageUnscaled(img, 0, 0);
  370. }
  371. //存储各种格式
  372. //bmp.Save(filePath, System.Drawing.Imaging.ImageFormat.Gif);
  373. //bmp.Save(filePath, System.Drawing.Imaging.ImageFormat.Png);
  374. bmp.Save(filePath, System.Drawing.Imaging.ImageFormat.Jpeg);
  375. }
  376. return true;
  377. }
  378. catch
  379. {
  380. return false;
  381. }
  382. }
  383. /// <summary>
  384. /// 插入JPeG图片
  385. /// topdfdoc 所要插入的文档
  386. /// filename 图片文件名
  387. /// fileinfo 文件信息
  388. /// width page宽
  389. /// height page高
  390. /// index 插入位置
  391. /// </summary>
  392. private void JpegInsertPage(ref CPDFDocument topdfdoc,string filename, FileInfo fileinfo,int width,int height,int index=0) {
  393. string tempFileName = "";
  394. if (fileinfo.Extension == ".jpg"|| fileinfo.Extension == ".jpeg")
  395. {
  396. topdfdoc.InsertPage(index, width, height, filename);
  397. }
  398. else
  399. {
  400. tempFileName = Path.GetTempPath() + "pngtemp.jpg";
  401. if (!PictureConverter.SaveJpeg(filename, tempFileName))
  402. {
  403. MessageBoxEx.Show("图片格式有问题");
  404. }
  405. topdfdoc.InsertPage(index, width, height, tempFileName);
  406. }
  407. }
  408. #endregion
  409. #region 构架行为
  410. public string Title => "图片转PDF";
  411. public event Action<IDialogResult> RequestClose;
  412. public bool CanCloseDialog()
  413. {
  414. return true;
  415. }
  416. public void OnDialogClosed()
  417. {
  418. }
  419. public void OnDialogOpened(IDialogParameters parameters)
  420. {
  421. string[] filepath=null;
  422. parameters.TryGetValue<string[]>(ParameterNames.FilePath, out filepath);
  423. if (filepath!=null)
  424. {
  425. fileNames=filepath.ToList();
  426. ImagesDataTable.Columns.Add("FileName");
  427. ImagesDataTable.Columns.Add("FileSize");
  428. ImagesDataTable.Columns.Add("FileState");
  429. updateListview("待确定");
  430. }
  431. }
  432. #endregion
  433. }
  434. }