CommonHelper.cs 18 KB

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