using ComPDFKit.PDFDocument; using PDF_Master.Model.PageEdit; using PDF_Master.ViewModels.Dialog.BOTA; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.Serialization.Formatters.Binary; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using System.Windows; using System.Windows.Media; namespace PDF_Master.Helper { public class Compare : IEqualityComparer { private Func _getField; public Compare(Func getfield) { this._getField = getfield; } public bool Equals(T x, T y) { return EqualityComparer.Default.Equals(_getField(x), _getField(y)); } public int GetHashCode(T obj) { return EqualityComparer.Default.GetHashCode(this._getField(obj)); } } public enum FileExtension { JPG = 255216, GIF = 7173, PNG = 13780, SWF = 6787, RAR = 8297, ZIP = 8075, _7Z = 55122, VALIDFILE = 9999999 } /// /// 1 FindVisualParent 查找目标类型的父类控件 /// 2 FindVisualChild 查找目标类型的子类控件 /// 3 GetPageParmFromList 从页码集合获取页码字符串,如1,2,3 转换成1-3 /// 4 GetPagesInRange 校验PageRange 输入是否合法,且可返回List Pages 存放的索引值 /// 5.ShowFileBrowser 显示系统文件浏览器,可以根据传入的路径参数,自动选中对应的文件 /// 6.CreateFilePath 检查对应路径是否有重名,有重名的情况追加尾号 /// 7.CreateFolder 检查对应文件夹是否有重名,有重名的情况追加尾号 /// 8.GetUnitsFromPageSize 将PDF页面宽高转换成对应的单位 /// 9.GetDpi() 返回当前设备DPI /// 10.GetFileSize() 获取文件大小 /// public static class CommonHelper { [DllImport("user32.dll")] private static extern IntPtr SetCapture(long hWnd); [DllImport("user32.dll")] private static extern long ReleaseCapture(); /// /// 打开路径并定位文件...对于@"h:\Bleacher Report - Hardaway with the safe call ??.mp4"这样的,explorer.exe /select,d:xxx不认,用API整它 /// /// 文件绝对路径 [DllImport("shell32.dll", ExactSpelling = true)] private static extern void ILFree(IntPtr pidlList); [DllImport("shell32.dll", CharSet = CharSet.Unicode, ExactSpelling = true)] private static extern IntPtr ILCreateFromPathW(string pszPath); [DllImport("shell32.dll", ExactSpelling = true)] private static extern int SHOpenFolderAndSelectItems(IntPtr pidlList, uint cild, IntPtr children, uint dwFlags); /// /// 打开文件夹浏览,并选中一个文件(对于文件名称比较不规范的,可以用这个) /// /// public static void ExplorerFile(string filePath) { try { if (!File.Exists(filePath) && !Directory.Exists(filePath)) return; if (Directory.Exists(filePath)) Process.Start(@"explorer.exe", "/select,\"" + filePath + "\""); else { IntPtr pidlList = ILCreateFromPathW(filePath); if (pidlList != IntPtr.Zero) { try { Marshal.ThrowExceptionForHR(SHOpenFolderAndSelectItems(pidlList, 0, IntPtr.Zero, 0)); } finally { ILFree(pidlList); } } } } catch { } } /// /// 自定义Distinct扩展方法 /// /// 要去重的对象类 /// 自定义去重的字段类型 /// 要去重的对象 /// 获取自定义去重字段的委托 /// public static IEnumerable DistinctHelper(this IEnumerable source, Func getfield) { return source.Distinct(new Compare(getfield)); } /// /// 查找对象目标类型的父类控件 /// /// /// /// public static T FindVisualParent(DependencyObject obj) where T : class { try { while (obj != null) { if (obj is T) return obj as T; obj = VisualTreeHelper.GetParent(obj); } return null; } catch { return null; } } /// /// 根据对象查找目标类型的子类 /// /// /// /// public static childItem FindVisualChild(DependencyObject obj) where childItem : DependencyObject { try { for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++) { DependencyObject child = VisualTreeHelper.GetChild(obj, i); if (child != null && child is childItem) return (childItem)child; else { childItem childOfChild = FindVisualChild(child); if (childOfChild != null) return childOfChild; } } return null; } catch { return null; } } public static T FindVisualChildByName(DependencyObject parent, string name) where T : DependencyObject { for (int i = 0; i < VisualTreeHelper.GetChildrenCount(parent); i++) { var child = VisualTreeHelper.GetChild(parent, i); string controlName = child.GetValue(System.Windows.Controls.Control.NameProperty) as string; if (controlName == name) { return child as T; } else { T result = FindVisualChildByName(child, name); if (result != null) return result; } } return null; } /// /// 从页码集合获取页码字符串,如1,2,3 转换成1-3 /// /// /// public static string GetPageParmFromList(List pagesList) { string pageParam = ""; if (pagesList.Count != 0) { pagesList.Sort();//先对页码排序 for (int i = 0; i < pagesList.Count; i++) { if (i == 0) { pageParam += pagesList[0].ToString(); } else { if (pagesList[i] == pagesList[i - 1] + 1)//页码连续 { if (i >= 2) { if (pagesList[i - 1] != pagesList[i - 2] + 1) pageParam += "-"; } else pageParam += "-"; if (i == pagesList.Count - 1) { pageParam += pagesList[i].ToString(); } } else//页码不连续时 { if (i >= 2) { if (pagesList[i - 1] == pagesList[i - 2] + 1) pageParam += pagesList[i - 1].ToString(); } pageParam += "," + pagesList[i].ToString(); } } } } return pageParam; } /// /// 校验PageRange 输入是否合法,且可返回List Pages 存放的索引值 /// /// 返回的页面索引集合 /// 需要判断的文本 /// 页面总数 /// 例 new char[] { ',' } /// 例 new char[] { '-' } /// /// public static bool GetPagesInRange(ref List pageIndexList, string pageRange, int count, char[] enumerationSeparator, char[] rangeSeparator, bool inittag = false) { string[] rangeSplit = pageRange.Split(enumerationSeparator);//根据分隔符 拆分字符串 pageIndexList.Clear(); foreach (string range in rangeSplit) { int starttag = 1; if (inittag) { starttag = 0; } if (range.Contains("-"))//连续页 { try { string[] limits = range.Split(rangeSeparator);//对子字符串再根据”-“ 拆分 if (limits.Length >= 2 && !string.IsNullOrWhiteSpace(limits[0]) && !string.IsNullOrWhiteSpace(limits[1])) { int start = int.Parse(limits[0]); int end = int.Parse(limits[1]); if ((start < starttag) || (end > count) || (start > end)) { return false; } for (int i = start; i <= end; ++i) { if (pageIndexList.Contains(i)) { return false; } pageIndexList.Add(i - 1); } continue; } } catch { return false; } } int pageNr; try { // Single page pageNr = int.Parse(range);//单页 } catch//格式不正确时 { return false; } if (pageNr < starttag || pageNr > count) { return false; } if (pageIndexList.Contains(pageNr)) { return false; } pageIndexList.Add(pageNr - 1); } return true; } /// /// 显示系统文件浏览器 /// /// 要选中的文件路径 public static void ShowFileBrowser(string selectedFile = null) { if (string.IsNullOrEmpty(selectedFile)) { Process.Start(@"explorer.exe"); } else { //if (File.Exists(selectedFile)){ Process.Start(@"explorer.exe", "/select,\"" + selectedFile + "\""); //} } } /// /// 检测文件是否重复 追加尾号 /// /// /// public static string CreateFilePath(string path) { int i = 1; string oldDestName = path; do { if (File.Exists(path)) { int lastDot = oldDestName.LastIndexOf('.'); string fileExtension = string.Empty; string fileName = oldDestName; if (lastDot > 0) { fileExtension = fileName.Substring(lastDot); fileName = fileName.Substring(0, lastDot); } path = fileName + string.Format(@"({0})", i) + fileExtension; } ++i; } while (File.Exists(path)); return path; } /// /// 检查文件夹是否重复 追加尾号 /// /// /// public static string CreateFolder(string folder) { int i = 1; string oldDestName = folder; DirectoryInfo info = new DirectoryInfo(folder); do { info = new DirectoryInfo(folder); if (info.Exists) { string fileName = oldDestName; folder = fileName + string.Format(@"({0})", i); } ++i; } while (info.Exists); info.Create(); return folder; } /// /// 将Document 返回的PageSize 转换成对应单位 /// /// /// /// public static double GetUnitsFromPageSize(double size, PageItemUnits unit = PageItemUnits.MM) { double sizeWithUnit = 0; switch (unit) { case PageItemUnits.MM: sizeWithUnit = size / 72 * 25.4; break; case PageItemUnits.CM: sizeWithUnit = size / 72 * 25.4 / 10.0; break; case PageItemUnits.IN: sizeWithUnit = size / 72; break; default: break; } return sizeWithUnit; } /// /// 将mm单位转换成pdf文件尺寸 /// /// /// public static double GetPageSizeFomrUnit(double size) { double pagesize = 0; pagesize = size / 25.4 * 72.0; return pagesize; } /// /// 返回设备DPI /// /// public static double GetDpi() { BindingFlags bindingAttr = BindingFlags.Static | BindingFlags.NonPublic; PropertyInfo property = typeof(SystemParameters).GetProperty("Dpi", bindingAttr); return (int)property.GetValue(null, null); } /// /// 根据路径计算文件大小 /// /// /// public static string GetFileSize(string path) { System.IO.FileInfo fileInfo = null; try { fileInfo = new System.IO.FileInfo(path); } catch { return "0KB"; } if (fileInfo != null && fileInfo.Exists) { var size = Math.Round(fileInfo.Length / 1024.0, 0); if (size > 1024) { var sizeDouble = Math.Round(size / 1024.0, 2); if (sizeDouble > 1024) { sizeDouble = Math.Round(sizeDouble / 1024.0, 2); return sizeDouble + "G"; } else return sizeDouble + "M"; } else { return (int)System.Math.Ceiling(size) + "KB"; } } else { return "0KB"; } } /// /// 将sdk里的日期转化为标准日期格式 /// /// /// public static string GetDate(string sdkDate) { try { if (sdkDate == null || string.IsNullOrEmpty(sdkDate)) { return ""; } string dateStr = Regex.Match(sdkDate, "(?<=D\\:)[0-9]+(?=[\\+\\-])").Value; if (string.IsNullOrEmpty(dateStr)) { return ""; } 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); return text; } catch { return ""; } } /// /// 深拷贝方法(针对数据结构类型) /// /// /// /// public static T DeepClone(T obj) { if (obj == null) { return default(T); } var objType = obj.GetType(); if (objType.IsValueType || objType == typeof(string)) { return obj; } // 创建新实例 T newObj = (T)Activator.CreateInstance(objType); // 递归复制属性 PropertyInfo[] properties = objType.GetProperties(BindingFlags.Public | BindingFlags.Instance); foreach (PropertyInfo property in properties) { if (!property.CanWrite || !property.CanRead) { continue; } // 如果属性是引用类型,继续拷贝 var propertyType = property.PropertyType; if (propertyType.IsClass && propertyType != typeof(string)) { var propertyValue = property.GetValue(obj, null); var propertyValueClone = DeepClone(propertyValue); property.SetValue(newObj, propertyValueClone, null); } // 否则直接赋值 else { var propertyValue = property.GetValue(obj, null); property.SetValue(newObj, propertyValue, null); } } return newObj; } /// /// 逆序int类型集合 /// public static void Reverseorder(ref List Numbers) { Numbers = Numbers.OrderBy(a => a).ToList(); Numbers.Reverse(); } } }