HomePagePictureToPDFDialogViewModel.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574
  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. private int FileNameNumber = 0;
  27. public IDialogService dialogs;
  28. public List<int> fileNamesView = new List<int>();
  29. public HomePagePictureToPDFDialogModel pictureToPDFModel=new HomePagePictureToPDFDialogModel();
  30. private string pictureToPDFGridIsEnabled = "True";
  31. public string PictureToPDFGridIsEnabled
  32. {
  33. get
  34. {
  35. return pictureToPDFGridIsEnabled;
  36. }
  37. set
  38. {
  39. SetProperty(ref pictureToPDFGridIsEnabled, value);
  40. }
  41. }
  42. private string setPictureToPDFGridIsEnabled = "True";
  43. public string SetPictureToPDFGridIsEnabled
  44. {
  45. get
  46. {
  47. return setPictureToPDFGridIsEnabled;
  48. }
  49. set
  50. {
  51. SetProperty(ref setPictureToPDFGridIsEnabled, value);
  52. }
  53. }
  54. private DataTable imagesDataTable = new DataTable();
  55. public DataTable ImagesDataTable
  56. {
  57. get { return imagesDataTable; }
  58. set
  59. {
  60. SetProperty(ref imagesDataTable, value);
  61. }
  62. }
  63. private DataTable imagesCurrentDataTable = new DataTable();
  64. public DataTable ImagesCurrentDataTable
  65. {
  66. get { return imagesCurrentDataTable; }
  67. set
  68. {
  69. SetProperty(ref imagesCurrentDataTable, value);
  70. }
  71. }
  72. private string removeIsEnable = "False";
  73. public string RemoveIsEnable
  74. {
  75. get { return removeIsEnable; }
  76. set
  77. {
  78. SetProperty(ref removeIsEnable, value);
  79. }
  80. }
  81. private string selectFileName = "False";
  82. public string SelectFileName
  83. {
  84. get { return selectFileName; }
  85. set
  86. {
  87. SetProperty(ref selectFileName, value);
  88. }
  89. }
  90. private Visibility addFileVisibility = Visibility.Hidden;
  91. public Visibility AddFileVisibility
  92. {
  93. get { return addFileVisibility; }
  94. set
  95. {
  96. SetProperty(ref addFileVisibility, value);
  97. RaisePropertyChanged();
  98. }
  99. }
  100. #endregion
  101. #region 委托声明
  102. public DelegateCommand ToPDFCommand { get; set; }
  103. public DelegateCommand ADDPictureCommand { get; set; }
  104. public DelegateCommand ADDPictureFilesCommand { get; set; }
  105. public DelegateCommand RemovePictureFileCommand { get; set; }
  106. public DelegateCommand SelectFileCommand { get; set; }
  107. #endregion
  108. public HomePagePictureToPDFDialogViewModel(IDialogService dialogs)
  109. {
  110. this.dialogs = dialogs;
  111. ToPDFCommand = new DelegateCommand(topdf);
  112. ADDPictureCommand = new DelegateCommand(addpicture);
  113. ADDPictureFilesCommand = new DelegateCommand(addpicturefiles);
  114. RemovePictureFileCommand = new DelegateCommand(removepicturefile);
  115. SelectFileCommand = new DelegateCommand(selectFile);
  116. ImagesDataTable.Columns.Add("FileName");
  117. ImagesDataTable.Columns.Add("FileSize");
  118. ImagesDataTable.Columns.Add("FileState");
  119. ImagesCurrentDataTable.Columns.Add("FileState");
  120. }
  121. #region 逻辑函数
  122. private void topdf() {
  123. PictureToPDFGridIsEnabled = "False";
  124. if (pictureToPDFModel.Mode == HomePagePictureToPDFDialogModel.ToPDFFileMode.NewFiles)
  125. {
  126. fileNamesIndex = 0;
  127. foreach (var filename in fileNames)
  128. {
  129. ImagesDataTable.Rows[fileNamesIndex]["FileState"] = "准备转换";
  130. ImagesCurrentDataTable.Rows[fileNamesIndex]["FileState"] = "准备转换";
  131. Image img = Image.FromFile(filename);
  132. if (img == null)
  133. {
  134. ImagesDataTable.Rows[fileNamesIndex]["FileState"] = "文件出错";
  135. ImagesCurrentDataTable.Rows[fileNamesIndex]["FileState"] = "文件出错";
  136. continue;
  137. }
  138. CPDFDocument topdfdoc = CPDFDocument.CreateDocument();
  139. FileInfo fileinfo = new FileInfo(filename);
  140. JpegInsertPage(ref topdfdoc, filename, fileinfo,img.Width,img.Height);
  141. Trace.WriteLine("Path.GetTempPath():" + Path.GetTempPath());
  142. topdfdoc.WriteToFilePath(savefilename(filename));
  143. topdfdoc.Release();
  144. string file_size = (((float)fileinfo.Length) / 1024).ToString() + " K";
  145. ImagesDataTable.Rows[fileNamesIndex]["FileState"] = "完成";
  146. ImagesCurrentDataTable.Rows[fileNamesIndex]["FileState"] = "完成";
  147. fileNamesIndex++;
  148. }
  149. System.Diagnostics.Process.Start("Explorer", "/select," + savefilename(fileNames[0]));
  150. }
  151. if (pictureToPDFModel.Mode == HomePagePictureToPDFDialogModel.ToPDFFileMode.OneNewFile)
  152. {
  153. CPDFDocument topdfdoc = CPDFDocument.CreateDocument();
  154. int pageindex = 0;
  155. foreach (var filename in fileNames) {
  156. ImagesDataTable.Rows[fileNamesIndex]["FileState"] = "准备转换";
  157. ImagesCurrentDataTable.Rows[fileNamesIndex]["FileState"] = "准备转换";
  158. Image img = Image.FromFile(filename);
  159. if (img == null)
  160. {
  161. ImagesDataTable.Rows[fileNamesIndex]["FileState"] = "文件出错";
  162. ImagesCurrentDataTable.Rows[fileNamesIndex]["FileState"] = "文件出错";
  163. continue;
  164. }
  165. FileInfo fileinfo = new FileInfo(filename);
  166. JpegInsertPage(ref topdfdoc, filename, fileinfo,img.Width, img.Height, pageindex);
  167. pageindex++;
  168. string file_size = (((float)fileinfo.Length) / 1024).ToString() + " K";
  169. ImagesDataTable.Rows[fileNamesIndex]["FileState"] = "完成";
  170. ImagesCurrentDataTable.Rows[fileNamesIndex]["FileState"] = "完成";
  171. fileNamesIndex++;
  172. }
  173. System.Diagnostics.Process.Start("Explorer", "/select," + savefilename(fileNames[0]));
  174. topdfdoc.WriteToFilePath(savefilename(fileNames[0]));
  175. topdfdoc.Release();
  176. }
  177. if (pictureToPDFModel.Mode == HomePagePictureToPDFDialogModel.ToPDFFileMode.SelectFileName)
  178. {
  179. CPDFDocument topdfdoc =CPDFDocument.InitWithFilePath(pictureToPDFModel.FilePath);
  180. if (topdfdoc == null)
  181. {
  182. Trace.WriteLine("Document==null");
  183. //TODO
  184. MessageBoxEx.Show("文档为空");
  185. PictureToPDFGridIsEnabled = "True";
  186. return;
  187. }
  188. if (topdfdoc.IsLocked)
  189. {
  190. DialogParameters value = new DialogParameters();
  191. value.Add(ParameterNames.PDFDocument, topdfdoc);
  192. dialogs.ShowDialog(DialogNames.VerifyPassWordDialog, value, e =>
  193. {
  194. if (e.Result == ButtonResult.OK)
  195. {
  196. if (e.Parameters.ContainsKey(ParameterNames.PassWord) && e.Parameters.GetValue<string>(ParameterNames.PassWord) != null)
  197. {
  198. topdfdoc.UnlockWithPassword(e.Parameters.GetValue<string>(ParameterNames.PassWord).ToString());
  199. }
  200. }
  201. });
  202. if (topdfdoc.IsLocked)
  203. {
  204. //未成功解密文档时,释放Document对象,返回
  205. ImagesDataTable.Rows[fileNamesIndex]["FileState"] = "文件出错";
  206. ImagesCurrentDataTable.Rows[fileNamesIndex]["FileState"] = "文件出错";
  207. fileNamesIndex++;
  208. PictureToPDFGridIsEnabled = "True";
  209. return;
  210. }
  211. }
  212. int pageindex = topdfdoc.PageCount;
  213. foreach (var filename in fileNames)
  214. {
  215. ImagesDataTable.Rows[fileNamesIndex]["FileState"] = "准备转换";
  216. ImagesCurrentDataTable.Rows[fileNamesIndex]["FileState"] = "准备转换";
  217. Image img = Image.FromFile(filename);
  218. if (img == null)
  219. {
  220. ImagesDataTable.Rows[fileNamesIndex]["FileState"] = "文件出错";
  221. ImagesCurrentDataTable.Rows[fileNamesIndex]["FileState"] = "文件出错";
  222. continue;
  223. }
  224. FileInfo fileinfo = new FileInfo(filename);
  225. JpegInsertPage(ref topdfdoc, filename, fileinfo, img.Width, img.Height, pageindex);
  226. pageindex++;
  227. string file_size = (((float)fileinfo.Length) / 1024).ToString() + " K";
  228. ImagesDataTable.Rows[fileNamesIndex]["FileState"] = "完成";
  229. ImagesCurrentDataTable.Rows[fileNamesIndex]["FileState"] = "完成";
  230. fileNamesIndex++;
  231. }
  232. topdfdoc.WriteToLoadedPath();
  233. System.Diagnostics.Process.Start("Explorer", "/select," + topdfdoc.FilePath);
  234. topdfdoc.Release();
  235. }
  236. PictureToPDFGridIsEnabled = "True";
  237. fileNamesIndex=0;
  238. }
  239. /// <summary>
  240. /// 设置保存后的文件名
  241. /// </summary>
  242. public string savefilename(string filename)
  243. {
  244. FileInfo file = new FileInfo(filename);
  245. return CommonHelper.CreateFilePath(filename.Replace(file.Name, "") + pictureToPDFModel.FrontFileNameLabel + file.Name + pictureToPDFModel.RearFileNameLabel + ".pdf");
  246. }
  247. #endregion
  248. #region 批量处理逻辑函数
  249. /// <summary>
  250. /// 选择PDF文件
  251. /// </summary>
  252. private void selectFile()
  253. {
  254. System.Windows.Forms.OpenFileDialog dlg = new System.Windows.Forms.OpenFileDialog();
  255. dlg.Multiselect = false;
  256. dlg.Filter = "PDF|*.pdf;*.PDF;";
  257. if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
  258. {
  259. SelectFileName=dlg.FileName;
  260. pictureToPDFModel.FilePath = dlg.FileName;
  261. }
  262. }
  263. /// <summary>
  264. /// 添加图片文件
  265. /// </summary>
  266. private void addpicture()
  267. {
  268. FileNameNumber = fileNames.Count;
  269. System.Windows.Forms.OpenFileDialog dlg = new System.Windows.Forms.OpenFileDialog();
  270. dlg.Multiselect = true;
  271. dlg.Filter = "Picture|*.png;*.PNG;*.jpg;*.JPG;*.bmp;*.gif;*tiff;";
  272. if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
  273. {
  274. fileNames.AddRange(dlg.FileNames.ToList());
  275. RemoveExcess(ref fileNames);
  276. SetPictureToPDFGridIsEnabled = "True";
  277. AddFileVisibility = Visibility.Collapsed;
  278. updateListview("待确定");
  279. }
  280. }
  281. public void addPicture(string filename)
  282. {
  283. FileNameNumber = fileNames.Count;
  284. fileNames.Add(filename);
  285. RemoveExcess(ref fileNames);
  286. SetPictureToPDFGridIsEnabled = "True";
  287. AddFileVisibility = Visibility.Collapsed;
  288. updateListview("待确定");
  289. }
  290. /// <summary>
  291. /// 添加图片文件夹
  292. /// </summary>
  293. private void addpicturefiles()
  294. {
  295. FileNameNumber = fileNames.Count;
  296. FolderBrowserDialog dialog = new FolderBrowserDialog();
  297. dialog.Description = "请选择文件路径";
  298. if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
  299. {
  300. string foldPath = dialog.SelectedPath;
  301. var apps = System.IO.Directory.GetFiles(foldPath);
  302. foreach (string app in apps)
  303. {
  304. var fi = new FileInfo(app);
  305. if (fi.Extension == ".png" || fi.Extension == ".jpg" || fi.Extension == ".jpeg" || fi.Extension ==".bmp"|| fi.Extension == ".gif"|| fi.Extension == ".tiff")
  306. {
  307. fileNames.Add(app);
  308. }
  309. }
  310. RemoveExcess(ref fileNames);
  311. updateListview("待确定");
  312. SetPictureToPDFGridIsEnabled = "True";
  313. AddFileVisibility = Visibility.Collapsed;
  314. }
  315. }
  316. /// <summary>
  317. /// 删除图片文件
  318. /// </summary>
  319. public void removepicturefile() {
  320. FileNameNumber = fileNames.Count;
  321. Reverseorder(ref fileNamesView);
  322. foreach (int filenamesview in fileNamesView)
  323. {
  324. //Trace.WriteLine(filenamesview);
  325. fileNames.Remove(fileNames[filenamesview]);
  326. }
  327. if (fileNames.Count < 1)
  328. {
  329. SetPictureToPDFGridIsEnabled = "False";
  330. AddFileVisibility = Visibility.Visible;
  331. }
  332. updateListview("待确定");
  333. }
  334. public void removepdffile(int index)
  335. {
  336. ImagesCurrentDataTable.Rows.RemoveAt(index);
  337. fileNames.Remove(fileNames[index]);
  338. if (fileNames.Count < 1)
  339. {
  340. SetPictureToPDFGridIsEnabled = "False";
  341. AddFileVisibility = Visibility.Visible;
  342. }
  343. updateListview("待确定");
  344. }
  345. /// <summary>
  346. /// 打开文件图片
  347. /// </summary>
  348. public void openfiledialog(){
  349. foreach (int filenamesview in fileNamesView)
  350. {
  351. System.Diagnostics.Process.Start(fileNames[filenamesview]);
  352. }
  353. }
  354. /// <summary>
  355. /// 删除重复的文件
  356. /// </summary>
  357. public void RemoveExcess(ref List<string> Filenames) {
  358. List<string> filenames = new List<string>();
  359. foreach (var fileName in Filenames)
  360. {
  361. if (!filenames.Contains(fileName))
  362. {
  363. filenames.Add(fileName);
  364. }
  365. }
  366. Filenames.Clear();
  367. Filenames = filenames;
  368. }
  369. /// <summary>
  370. /// 逆序int类型集合
  371. /// </summary>
  372. public void Reverseorder(ref List<int> Numbers)
  373. {
  374. Numbers=Numbers.OrderBy(a=>a).ToList();
  375. Numbers.Reverse();
  376. }
  377. /// <summary>
  378. /// 更新listview显示
  379. /// state 状态显示字符串
  380. /// </summary>
  381. public void updateListview(string state) {
  382. updateCurrentListview();
  383. DataTable imagesdatatable = new DataTable();
  384. imagesdatatable.Columns.Add("FileName");
  385. imagesdatatable.Columns.Add("FileSize");
  386. imagesdatatable.Columns.Add("FileState");
  387. int datatableindex = 0;
  388. foreach (var fileName in fileNames)
  389. {
  390. string file_all = fileName;
  391. FileInfo f = new FileInfo(file_all);
  392. string file_size = (((float)f.Length)/1024).ToString()+" K";
  393. imagesdatatable.Rows.Add(f.Name, file_size, ImagesCurrentDataTable.Rows[datatableindex]["FileState"]);
  394. datatableindex++;
  395. }
  396. ImagesDataTable = imagesdatatable;
  397. }
  398. /// <summary>
  399. /// 更新Currentlistview显示
  400. /// pagerangetext 自定义页面范围字符串 pagerangeselectindex combobox下拉索引(0全部页面 1奇数页 2偶数页 3自定义页面)isevenpageisenabled 偶数页状态 state 状态显示字符串
  401. /// </summary>
  402. public void updateCurrentListview( string state = "待完成")
  403. {
  404. if (fileNames.Count >= FileNameNumber)
  405. {
  406. for (int i = 0; fileNames.Count - FileNameNumber > i; i++)
  407. {
  408. ImagesCurrentDataTable.Rows.Add(state);
  409. }
  410. }
  411. else
  412. {
  413. Reverseorder(ref fileNamesView);
  414. foreach (int filenamesview in fileNamesView)
  415. {
  416. ImagesCurrentDataTable.Rows.RemoveAt(filenamesview);
  417. }
  418. }
  419. }
  420. #endregion
  421. #region 图片转换
  422. /// <summary>
  423. /// 图片转PNG
  424. /// picturefile 图片文件名
  425. /// filePath 保存路径
  426. /// </summary>
  427. public bool SavePng(string picturefile, string filePath)
  428. {
  429. Image img = Image.FromFile(picturefile);
  430. try
  431. {
  432. using (var bmp = new Bitmap(img.Width, img.Height))
  433. {
  434. bmp.SetResolution(img.HorizontalResolution, img.VerticalResolution);
  435. using (var g = Graphics.FromImage(bmp))
  436. {
  437. g.Clear(Color.White);
  438. g.DrawImageUnscaled(img, 0, 0);
  439. }
  440. bmp.Save(filePath, System.Drawing.Imaging.ImageFormat.Png);
  441. }
  442. return true;
  443. }
  444. catch
  445. {
  446. return false;
  447. }
  448. }
  449. /// <summary>
  450. /// 图片转JPeG
  451. /// picturefile 图片文件名
  452. /// filePath 保存路径
  453. /// </summary>
  454. public bool SaveJpeg(string picturefile, string filePath)
  455. {
  456. Image img = Image.FromFile(picturefile);
  457. try
  458. {
  459. using (var bmp = new Bitmap(img.Width, img.Height))
  460. {
  461. bmp.SetResolution(img.HorizontalResolution, img.VerticalResolution);
  462. using (var g = Graphics.FromImage(bmp))
  463. {
  464. g.Clear(Color.White);
  465. g.DrawImageUnscaled(img, 0, 0);
  466. }
  467. //存储各种格式
  468. //bmp.Save(filePath, System.Drawing.Imaging.ImageFormat.Gif);
  469. //bmp.Save(filePath, System.Drawing.Imaging.ImageFormat.Png);
  470. bmp.Save(filePath, System.Drawing.Imaging.ImageFormat.Jpeg);
  471. }
  472. return true;
  473. }
  474. catch
  475. {
  476. return false;
  477. }
  478. }
  479. /// <summary>
  480. /// 插入JPeG图片
  481. /// topdfdoc 所要插入的文档
  482. /// filename 图片文件名
  483. /// fileinfo 文件信息
  484. /// width page宽
  485. /// height page高
  486. /// index 插入位置
  487. /// </summary>
  488. private void JpegInsertPage(ref CPDFDocument topdfdoc,string filename, FileInfo fileinfo,int width,int height,int index=0) {
  489. string tempFileName = "";
  490. if (fileinfo.Extension == ".jpg"|| fileinfo.Extension == ".jpeg")
  491. {
  492. topdfdoc.InsertPage(index, width, height, filename);
  493. }
  494. else
  495. {
  496. tempFileName = Path.GetTempPath() + "pngtemp.jpg";
  497. if (!PictureConverter.SaveJpeg(filename, tempFileName))
  498. {
  499. MessageBoxEx.Show("图片格式有问题");
  500. }
  501. topdfdoc.InsertPage(index, width, height, tempFileName);
  502. }
  503. }
  504. #endregion
  505. #region 构架行为
  506. public string Title => "图片转PDF";
  507. public event Action<IDialogResult> RequestClose;
  508. public bool CanCloseDialog()
  509. {
  510. return true;
  511. }
  512. public void OnDialogClosed()
  513. {
  514. }
  515. public void OnDialogOpened(IDialogParameters parameters)
  516. {
  517. string[] filepath=null;
  518. parameters.TryGetValue<string[]>(ParameterNames.FilePath, out filepath);
  519. if (filepath!=null)
  520. {
  521. fileNames=filepath.ToList();
  522. updateListview("待确定");
  523. }
  524. }
  525. #endregion
  526. }
  527. }