CommonHelper.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602
  1. using ComPDFKit.PDFDocument;
  2. using PDF_Master.Model.PageEdit;
  3. using PDF_Master.ViewModels.Dialog.BOTA;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Diagnostics;
  7. using System.IO;
  8. using System.Linq;
  9. using System.Reflection;
  10. using System.Runtime.InteropServices;
  11. using System.Runtime.Serialization.Formatters.Binary;
  12. using System.Text;
  13. using System.Text.RegularExpressions;
  14. using System.Threading.Tasks;
  15. using System.Windows;
  16. using System.Windows.Media;
  17. namespace PDF_Master.Helper
  18. {
  19. public class Compare<T, C> : IEqualityComparer<T>
  20. {
  21. private Func<T, C> _getField;
  22. public Compare(Func<T, C> getfield)
  23. {
  24. this._getField = getfield;
  25. }
  26. public bool Equals(T x, T y)
  27. {
  28. return EqualityComparer<C>.Default.Equals(_getField(x), _getField(y));
  29. }
  30. public int GetHashCode(T obj)
  31. {
  32. return EqualityComparer<C>.Default.GetHashCode(this._getField(obj));
  33. }
  34. }
  35. public enum FileExtension
  36. {
  37. JPG = 255216,
  38. GIF = 7173,
  39. PNG = 13780,
  40. SWF = 6787,
  41. RAR = 8297,
  42. ZIP = 8075,
  43. _7Z = 55122,
  44. VALIDFILE = 9999999
  45. }
  46. /// <summary>
  47. /// 1 FindVisualParent 查找目标类型的父类控件
  48. /// 2 FindVisualChild 查找目标类型的子类控件
  49. /// 3 GetPageParmFromList 从页码集合获取页码字符串,如1,2,3 转换成1-3
  50. /// 4 GetPagesInRange 校验PageRange 输入是否合法,且可返回List<int> Pages 存放的索引值
  51. /// 5.ShowFileBrowser 显示系统文件浏览器,可以根据传入的路径参数,自动选中对应的文件
  52. /// 6.CreateFilePath 检查对应路径是否有重名,有重名的情况追加尾号
  53. /// 7.CreateFolder 检查对应文件夹是否有重名,有重名的情况追加尾号
  54. /// 8.GetUnitsFromPageSize 将PDF页面宽高转换成对应的单位
  55. /// 9.GetDpi() 返回当前设备DPI
  56. /// 10.GetFileSize() 获取文件大小
  57. /// </summary>
  58. public static class CommonHelper
  59. {
  60. [DllImport("user32.dll")]
  61. private static extern IntPtr SetCapture(long hWnd);
  62. [DllImport("user32.dll")]
  63. private static extern long ReleaseCapture();
  64. /// <summary>
  65. /// 打开路径并定位文件...对于@"h:\Bleacher Report - Hardaway with the safe call ??.mp4"这样的,explorer.exe /select,d:xxx不认,用API整它
  66. /// </summary>
  67. /// <param name="filePath">文件绝对路径</param>
  68. [DllImport("shell32.dll", ExactSpelling = true)]
  69. private static extern void ILFree(IntPtr pidlList);
  70. [DllImport("shell32.dll", CharSet = CharSet.Unicode, ExactSpelling = true)]
  71. private static extern IntPtr ILCreateFromPathW(string pszPath);
  72. [DllImport("shell32.dll", ExactSpelling = true)]
  73. private static extern int SHOpenFolderAndSelectItems(IntPtr pidlList, uint cild, IntPtr children, uint dwFlags);
  74. /// <summary>
  75. /// 打开文件夹浏览,并选中一个文件(对于文件名称比较不规范的,可以用这个)
  76. /// </summary>
  77. /// <param name="filePath"></param>
  78. public static void ExplorerFile(string filePath)
  79. {
  80. try
  81. {
  82. if (!File.Exists(filePath) && !Directory.Exists(filePath))
  83. return;
  84. if (Directory.Exists(filePath))
  85. Process.Start(@"explorer.exe", "/select,\"" + filePath + "\"");
  86. else
  87. {
  88. IntPtr pidlList = ILCreateFromPathW(filePath);
  89. if (pidlList != IntPtr.Zero)
  90. {
  91. try
  92. {
  93. Marshal.ThrowExceptionForHR(SHOpenFolderAndSelectItems(pidlList, 0, IntPtr.Zero, 0));
  94. }
  95. finally
  96. {
  97. ILFree(pidlList);
  98. }
  99. }
  100. }
  101. }
  102. catch { }
  103. }
  104. /// <summary>
  105. /// 自定义Distinct扩展方法
  106. /// </summary>
  107. /// <typeparam name="T">要去重的对象类</typeparam>
  108. /// <typeparam name="C">自定义去重的字段类型</typeparam>
  109. /// <param name="source">要去重的对象</param>
  110. /// <param name="getfield">获取自定义去重字段的委托</param>
  111. /// <returns></returns>
  112. public static IEnumerable<T> DistinctHelper<T, C>(this IEnumerable<T> source, Func<T, C> getfield)
  113. {
  114. return source.Distinct(new Compare<T, C>(getfield));
  115. }
  116. /// <summary>
  117. /// 查找对象目标类型的父类控件
  118. /// </summary>
  119. /// <typeparam name="T"></typeparam>
  120. /// <param name="obj"></param>
  121. /// <returns></returns>
  122. public static T FindVisualParent<T>(DependencyObject obj) where T : class
  123. {
  124. try
  125. {
  126. while (obj != null)
  127. {
  128. if (obj is T)
  129. return obj as T;
  130. obj = VisualTreeHelper.GetParent(obj);
  131. }
  132. return null;
  133. }
  134. catch { return null; }
  135. }
  136. /// <summary>
  137. /// 根据对象查找目标类型的子类
  138. /// </summary>
  139. /// <typeparam name="childItem"></typeparam>
  140. /// <param name="obj"></param>
  141. /// <returns></returns>
  142. public static childItem FindVisualChild<childItem>(DependencyObject obj)
  143. where childItem : DependencyObject
  144. {
  145. try
  146. {
  147. for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
  148. {
  149. DependencyObject child = VisualTreeHelper.GetChild(obj, i);
  150. if (child != null && child is childItem)
  151. return (childItem)child;
  152. else
  153. {
  154. childItem childOfChild = FindVisualChild<childItem>(child);
  155. if (childOfChild != null)
  156. return childOfChild;
  157. }
  158. }
  159. return null;
  160. }
  161. catch { return null; }
  162. }
  163. public static T FindVisualChildByName<T>(DependencyObject parent, string name) where T : DependencyObject
  164. {
  165. for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++)
  166. {
  167. var child = VisualTreeHelper.GetChild(parent, i);
  168. string controlName = child.GetValue(System.Windows.Controls.Control.NameProperty) as string;
  169. if (controlName == name)
  170. {
  171. return child as T;
  172. }
  173. else
  174. {
  175. T result = FindVisualChildByName<T>(child, name);
  176. if (result != null)
  177. return result;
  178. }
  179. }
  180. return null;
  181. }
  182. /// <summary>
  183. /// 从页码集合获取页码字符串,如1,2,3 转换成1-3
  184. /// </summary>
  185. /// <param name="pagesList"></param>
  186. /// <returns></returns>
  187. public static string GetPageParmFromList(List<int> pagesList)
  188. {
  189. string pageParam = "";
  190. if (pagesList.Count != 0)
  191. {
  192. pagesList.Sort();//先对页码排序
  193. for (int i = 0; i < pagesList.Count; i++)
  194. {
  195. if (i == 0)
  196. {
  197. pageParam += pagesList[0].ToString();
  198. }
  199. else
  200. {
  201. if (pagesList[i] == pagesList[i - 1] + 1)//页码连续
  202. {
  203. if (i >= 2)
  204. {
  205. if (pagesList[i - 1] != pagesList[i - 2] + 1)
  206. pageParam += "-";
  207. }
  208. else
  209. pageParam += "-";
  210. if (i == pagesList.Count - 1)
  211. {
  212. pageParam += pagesList[i].ToString();
  213. }
  214. }
  215. else//页码不连续时
  216. {
  217. if (i >= 2)
  218. {
  219. if (pagesList[i - 1] == pagesList[i - 2] + 1)
  220. pageParam += pagesList[i - 1].ToString();
  221. }
  222. pageParam += "," + pagesList[i].ToString();
  223. }
  224. }
  225. }
  226. }
  227. return pageParam;
  228. }
  229. /// <summary>
  230. /// 校验PageRange 输入是否合法,且可返回List<int> Pages 存放的索引值
  231. /// </summary>
  232. /// <param name="pageIndexList">返回的页面索引集合</param>
  233. /// <param name="pageRange">需要判断的文本</param>
  234. /// <param name="count">页面总数</param>
  235. /// <param name="enumerationSeparator">例 new char[] { ',' }</param>
  236. /// <param name="rangeSeparator">例 new char[] { '-' }</param>
  237. /// <param name="inittag"></param>
  238. /// <returns></returns>
  239. public static bool GetPagesInRange(ref List<int> pageIndexList, string pageRange, int count, char[] enumerationSeparator, char[] rangeSeparator, bool inittag = false)
  240. {
  241. string[] rangeSplit = pageRange.Split(enumerationSeparator);//根据分隔符 拆分字符串
  242. pageIndexList.Clear();
  243. foreach (string range in rangeSplit)
  244. {
  245. int starttag = 1;
  246. if (inittag)
  247. {
  248. starttag = 0;
  249. }
  250. if (range.Contains("-"))//连续页
  251. {
  252. try
  253. {
  254. string[] limits = range.Split(rangeSeparator);//对子字符串再根据”-“ 拆分
  255. if (limits.Length >= 2 && !string.IsNullOrWhiteSpace(limits[0]) && !string.IsNullOrWhiteSpace(limits[1]))
  256. {
  257. int start = int.Parse(limits[0]);
  258. int end = int.Parse(limits[1]);
  259. if ((start < starttag) || (end > count) || (start > end))
  260. {
  261. return false;
  262. }
  263. for (int i = start; i <= end; ++i)
  264. {
  265. if (pageIndexList.Contains(i))
  266. {
  267. return false;
  268. }
  269. pageIndexList.Add(i - 1);
  270. }
  271. continue;
  272. }
  273. }
  274. catch
  275. {
  276. return false;
  277. }
  278. }
  279. int pageNr;
  280. try
  281. {
  282. // Single page
  283. pageNr = int.Parse(range);//单页
  284. }
  285. catch//格式不正确时
  286. {
  287. return false;
  288. }
  289. if (pageNr < starttag || pageNr > count)
  290. {
  291. return false;
  292. }
  293. if (pageIndexList.Contains(pageNr))
  294. {
  295. return false;
  296. }
  297. pageIndexList.Add(pageNr - 1);
  298. }
  299. return true;
  300. }
  301. /// <summary>
  302. /// 显示系统文件浏览器
  303. /// </summary>
  304. /// <param name="selectedFile">要选中的文件路径</param>
  305. public static void ShowFileBrowser(string selectedFile = null)
  306. {
  307. if (string.IsNullOrEmpty(selectedFile))
  308. {
  309. Process.Start(@"explorer.exe");
  310. }
  311. else
  312. {
  313. //if (File.Exists(selectedFile)){
  314. Process.Start(@"explorer.exe", "/select,\"" + selectedFile + "\"");
  315. //}
  316. }
  317. }
  318. /// <summary>
  319. /// 检测文件是否重复 追加尾号
  320. /// </summary>
  321. /// <param name="path"></param>
  322. /// <returns></returns>
  323. public static string CreateFilePath(string path)
  324. {
  325. int i = 1;
  326. string oldDestName = path;
  327. do
  328. {
  329. if (File.Exists(path))
  330. {
  331. int lastDot = oldDestName.LastIndexOf('.');
  332. string fileExtension = string.Empty;
  333. string fileName = oldDestName;
  334. if (lastDot > 0)
  335. {
  336. fileExtension = fileName.Substring(lastDot);
  337. fileName = fileName.Substring(0, lastDot);
  338. }
  339. path = fileName + string.Format(@"({0})", i) + fileExtension;
  340. }
  341. ++i;
  342. } while (File.Exists(path));
  343. return path;
  344. }
  345. /// <summary>
  346. /// 检查文件夹是否重复 追加尾号
  347. /// </summary>
  348. /// <param name="path"></param>
  349. /// <returns></returns>
  350. public static string CreateFolder(string folder)
  351. {
  352. int i = 1;
  353. string oldDestName = folder;
  354. DirectoryInfo info = new DirectoryInfo(folder);
  355. do
  356. {
  357. info = new DirectoryInfo(folder);
  358. if (info.Exists)
  359. {
  360. string fileName = oldDestName;
  361. folder = fileName + string.Format(@"({0})", i);
  362. }
  363. ++i;
  364. } while (info.Exists);
  365. info.Create();
  366. return folder;
  367. }
  368. /// <summary>
  369. /// 将Document 返回的PageSize 转换成对应单位
  370. /// </summary>
  371. /// <param name="size"></param>
  372. /// <param name="unit"></param>
  373. /// <returns></returns>
  374. public static double GetUnitsFromPageSize(double size, PageItemUnits unit = PageItemUnits.MM)
  375. {
  376. double sizeWithUnit = 0;
  377. switch (unit)
  378. {
  379. case PageItemUnits.MM:
  380. sizeWithUnit = size / 72 * 25.4;
  381. break;
  382. case PageItemUnits.CM:
  383. sizeWithUnit = size / 72 * 25.4 / 10.0;
  384. break;
  385. case PageItemUnits.IN:
  386. sizeWithUnit = size / 72;
  387. break;
  388. default:
  389. break;
  390. }
  391. return sizeWithUnit;
  392. }
  393. /// <summary>
  394. /// 将mm单位转换成pdf文件尺寸
  395. /// </summary>
  396. /// <param name="size"></param>
  397. /// <returns></returns>
  398. public static double GetPageSizeFomrUnit(double size)
  399. {
  400. double pagesize = 0;
  401. pagesize = size / 25.4 * 72.0;
  402. return pagesize;
  403. }
  404. /// <summary>
  405. /// 返回设备DPI
  406. /// </summary>
  407. /// <returns></returns>
  408. public static double GetDpi()
  409. {
  410. BindingFlags bindingAttr = BindingFlags.Static | BindingFlags.NonPublic;
  411. PropertyInfo property = typeof(SystemParameters).GetProperty("Dpi", bindingAttr);
  412. return (int)property.GetValue(null, null);
  413. }
  414. /// <summary>
  415. /// 根据路径计算文件大小
  416. /// </summary>
  417. /// <param name="path"></param>
  418. /// <returns></returns>
  419. public static string GetFileSize(string path)
  420. {
  421. System.IO.FileInfo fileInfo = null;
  422. try
  423. {
  424. fileInfo = new System.IO.FileInfo(path);
  425. }
  426. catch
  427. {
  428. return "0KB";
  429. }
  430. if (fileInfo != null && fileInfo.Exists)
  431. {
  432. var size = Math.Round(fileInfo.Length / 1024.0, 0);
  433. if (size > 1024)
  434. {
  435. var sizeDouble = Math.Round(size / 1024.0, 2);
  436. if (sizeDouble > 1024)
  437. {
  438. sizeDouble = Math.Round(sizeDouble / 1024.0, 2);
  439. return sizeDouble + "G";
  440. }
  441. else
  442. return sizeDouble + "M";
  443. }
  444. else
  445. {
  446. return (int)System.Math.Ceiling(size) + "KB";
  447. }
  448. }
  449. else
  450. {
  451. return "0KB";
  452. }
  453. }
  454. /// <summary>
  455. /// 将sdk里的日期转化为标准日期格式
  456. /// </summary>
  457. /// <param name="sdkDate"></param>
  458. /// <returns></returns>
  459. public static string GetDate(string sdkDate)
  460. {
  461. try
  462. {
  463. if (sdkDate == null || string.IsNullOrEmpty(sdkDate))
  464. {
  465. return "";
  466. }
  467. string dateStr = Regex.Match(sdkDate, "(?<=D\\:)[0-9]+(?=[\\+\\-])").Value;
  468. if (string.IsNullOrEmpty(dateStr))
  469. {
  470. return "";
  471. }
  472. string text = dateStr.Substring(0, 4) + "-" + dateStr.Substring(4, 2) + "-" + dateStr.Substring(6, 2) + " " + dateStr.Substring(8, 2) + ":" + dateStr.Substring(10, 2) + ":" + dateStr.Substring(12, 2);
  473. return text;
  474. }
  475. catch { return ""; }
  476. }
  477. /// <summary>
  478. /// 深拷贝方法(针对数据结构类型)
  479. /// </summary>
  480. /// <typeparam name="T"></typeparam>
  481. /// <param name="obj"></param>
  482. /// <returns></returns>
  483. public static T DeepClone<T>(T obj)
  484. {
  485. if (obj == null)
  486. {
  487. return default(T);
  488. }
  489. var objType = obj.GetType();
  490. if (objType.IsValueType || objType == typeof(string))
  491. {
  492. return obj;
  493. }
  494. // 创建新实例
  495. T newObj = (T)Activator.CreateInstance(objType);
  496. // 递归复制属性
  497. PropertyInfo[] properties = objType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
  498. foreach (PropertyInfo property in properties)
  499. {
  500. if (!property.CanWrite || !property.CanRead)
  501. {
  502. continue;
  503. }
  504. // 如果属性是引用类型,继续拷贝
  505. var propertyType = property.PropertyType;
  506. if (propertyType.IsClass && propertyType != typeof(string))
  507. {
  508. var propertyValue = property.GetValue(obj, null);
  509. var propertyValueClone = DeepClone(propertyValue);
  510. property.SetValue(newObj, propertyValueClone, null);
  511. }
  512. // 否则直接赋值
  513. else
  514. {
  515. var propertyValue = property.GetValue(obj, null);
  516. property.SetValue(newObj, propertyValue, null);
  517. }
  518. }
  519. return newObj;
  520. }
  521. /// <summary>
  522. /// 逆序int类型集合
  523. /// </summary>
  524. public static void Reverseorder(ref List<int> Numbers)
  525. {
  526. Numbers = Numbers.OrderBy(a => a).ToList();
  527. Numbers.Reverse();
  528. }
  529. }
  530. }