HomePagePictureToPDFDialogViewModel.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490
  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. #endregion
  204. #region 批量处理逻辑函数
  205. /// <summary>
  206. /// 选择PDF文件
  207. /// </summary>
  208. private void selectFile()
  209. {
  210. System.Windows.Forms.OpenFileDialog dlg = new System.Windows.Forms.OpenFileDialog();
  211. dlg.Multiselect = false;
  212. dlg.Filter = "PDF|*.pdf;*.PDF;";
  213. if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
  214. {
  215. SelectFileName=dlg.FileName;
  216. pictureToPDFModel.FilePath = dlg.FileName;
  217. }
  218. }
  219. /// <summary>
  220. /// 添加图片文件
  221. /// </summary>
  222. private void addpicture()
  223. {
  224. System.Windows.Forms.OpenFileDialog dlg = new System.Windows.Forms.OpenFileDialog();
  225. dlg.Multiselect = true;
  226. dlg.Filter = "Picture|*.png;*.PNG;*.jpg;*.JPG;*.bmp;*.gif;*tiff;";
  227. if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
  228. {
  229. fileNames.AddRange(dlg.FileNames.ToList());
  230. RemoveExcess(ref fileNames);
  231. SetPictureToPDFGridIsEnabled = "True";
  232. AddFileVisibility = Visibility.Collapsed;
  233. updateListview("待确定");
  234. }
  235. }
  236. /// <summary>
  237. /// 添加图片文件夹
  238. /// </summary>
  239. private void addpicturefiles()
  240. {
  241. FolderBrowserDialog dialog = new FolderBrowserDialog();
  242. dialog.Description = "请选择文件路径";
  243. if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
  244. {
  245. string foldPath = dialog.SelectedPath;
  246. var apps = System.IO.Directory.GetFiles(foldPath);
  247. foreach (string app in apps)
  248. {
  249. var fi = new FileInfo(app);
  250. if (fi.Extension == ".png" || fi.Extension == ".jpg" || fi.Extension == ".jpeg" || fi.Extension ==".bmp"|| fi.Extension == ".gif"|| fi.Extension == ".tiff")
  251. {
  252. fileNames.Add(app);
  253. }
  254. }
  255. RemoveExcess(ref fileNames);
  256. updateListview("待确定");
  257. SetPictureToPDFGridIsEnabled = "True";
  258. AddFileVisibility = Visibility.Collapsed;
  259. }
  260. }
  261. /// <summary>
  262. /// 删除图片文件
  263. /// </summary>
  264. public void removepicturefile() {
  265. Reverseorder(ref fileNamesView);
  266. foreach (int filenamesview in fileNamesView)
  267. {
  268. //Trace.WriteLine(filenamesview);
  269. fileNames.Remove(fileNames[filenamesview]);
  270. }
  271. if (fileNames.Count < 1)
  272. {
  273. SetPictureToPDFGridIsEnabled = "False";
  274. AddFileVisibility = Visibility.Visible;
  275. }
  276. updateListview("待确定");
  277. }
  278. public void removepdffile(int index)
  279. {
  280. fileNames.Remove(fileNames[index]);
  281. if (fileNames.Count < 1)
  282. {
  283. SetPictureToPDFGridIsEnabled = "False";
  284. AddFileVisibility = Visibility.Visible;
  285. }
  286. updateListview("待确定");
  287. }
  288. /// <summary>
  289. /// 打开文件图片
  290. /// </summary>
  291. public void openfiledialog(){
  292. foreach (int filenamesview in fileNamesView)
  293. {
  294. System.Diagnostics.Process.Start(fileNames[filenamesview]);
  295. }
  296. }
  297. /// <summary>
  298. /// 删除重复的文件
  299. /// </summary>
  300. public void RemoveExcess(ref List<string> Filenames) {
  301. List<string> filenames = new List<string>();
  302. foreach (var fileName in Filenames)
  303. {
  304. if (!filenames.Contains(fileName))
  305. {
  306. filenames.Add(fileName);
  307. }
  308. }
  309. Filenames.Clear();
  310. Filenames = filenames;
  311. }
  312. /// <summary>
  313. /// 逆序int类型集合
  314. /// </summary>
  315. public void Reverseorder(ref List<int> Numbers)
  316. {
  317. Numbers=Numbers.OrderBy(a=>a).ToList();
  318. Numbers.Reverse();
  319. }
  320. /// <summary>
  321. /// 更新listview显示
  322. /// state 状态显示字符串
  323. /// </summary>
  324. public void updateListview( string state) {
  325. DataTable imagesdatatable = new DataTable();
  326. imagesdatatable.Columns.Add("FileName");
  327. imagesdatatable.Columns.Add("FileSize");
  328. imagesdatatable.Columns.Add("FileState");
  329. foreach (var fileName in fileNames)
  330. {
  331. string file_all = fileName;
  332. FileInfo f = new FileInfo(file_all);
  333. string file_size = (((float)f.Length)/1024).ToString()+" K";
  334. imagesdatatable.Rows.Add(f.Name, file_size, state);
  335. }
  336. ImagesDataTable = imagesdatatable;
  337. }
  338. #endregion
  339. #region 图片转换
  340. /// <summary>
  341. /// 图片转PNG
  342. /// picturefile 图片文件名
  343. /// filePath 保存路径
  344. /// </summary>
  345. public bool SavePng(string picturefile, string filePath)
  346. {
  347. Image img = Image.FromFile(picturefile);
  348. try
  349. {
  350. using (var bmp = new Bitmap(img.Width, img.Height))
  351. {
  352. bmp.SetResolution(img.HorizontalResolution, img.VerticalResolution);
  353. using (var g = Graphics.FromImage(bmp))
  354. {
  355. g.Clear(Color.White);
  356. g.DrawImageUnscaled(img, 0, 0);
  357. }
  358. bmp.Save(filePath, System.Drawing.Imaging.ImageFormat.Png);
  359. }
  360. return true;
  361. }
  362. catch
  363. {
  364. return false;
  365. }
  366. }
  367. /// <summary>
  368. /// 图片转JPeG
  369. /// picturefile 图片文件名
  370. /// filePath 保存路径
  371. /// </summary>
  372. public bool SaveJpeg(string picturefile, string filePath)
  373. {
  374. Image img = Image.FromFile(picturefile);
  375. try
  376. {
  377. using (var bmp = new Bitmap(img.Width, img.Height))
  378. {
  379. bmp.SetResolution(img.HorizontalResolution, img.VerticalResolution);
  380. using (var g = Graphics.FromImage(bmp))
  381. {
  382. g.Clear(Color.White);
  383. g.DrawImageUnscaled(img, 0, 0);
  384. }
  385. //存储各种格式
  386. //bmp.Save(filePath, System.Drawing.Imaging.ImageFormat.Gif);
  387. //bmp.Save(filePath, System.Drawing.Imaging.ImageFormat.Png);
  388. bmp.Save(filePath, System.Drawing.Imaging.ImageFormat.Jpeg);
  389. }
  390. return true;
  391. }
  392. catch
  393. {
  394. return false;
  395. }
  396. }
  397. /// <summary>
  398. /// 插入JPeG图片
  399. /// topdfdoc 所要插入的文档
  400. /// filename 图片文件名
  401. /// fileinfo 文件信息
  402. /// width page宽
  403. /// height page高
  404. /// index 插入位置
  405. /// </summary>
  406. private void JpegInsertPage(ref CPDFDocument topdfdoc,string filename, FileInfo fileinfo,int width,int height,int index=0) {
  407. string tempFileName = "";
  408. if (fileinfo.Extension == ".jpg"|| fileinfo.Extension == ".jpeg")
  409. {
  410. topdfdoc.InsertPage(index, width, height, filename);
  411. }
  412. else
  413. {
  414. tempFileName = Path.GetTempPath() + "pngtemp.jpg";
  415. if (!PictureConverter.SaveJpeg(filename, tempFileName))
  416. {
  417. MessageBoxEx.Show("图片格式有问题");
  418. }
  419. topdfdoc.InsertPage(index, width, height, tempFileName);
  420. }
  421. }
  422. #endregion
  423. #region 构架行为
  424. public string Title => "图片转PDF";
  425. public event Action<IDialogResult> RequestClose;
  426. public bool CanCloseDialog()
  427. {
  428. return true;
  429. }
  430. public void OnDialogClosed()
  431. {
  432. }
  433. public void OnDialogOpened(IDialogParameters parameters)
  434. {
  435. string[] filepath=null;
  436. parameters.TryGetValue<string[]>(ParameterNames.FilePath, out filepath);
  437. if (filepath!=null)
  438. {
  439. fileNames=filepath.ToList();
  440. ImagesDataTable.Columns.Add("FileName");
  441. ImagesDataTable.Columns.Add("FileSize");
  442. ImagesDataTable.Columns.Add("FileState");
  443. updateListview("待确定");
  444. }
  445. }
  446. #endregion
  447. }
  448. }