using ComPDFKitViewer; using ComPDFKitViewer.PdfViewer; using Microsoft.Win32; using PDF_Master.EventAggregators; using PDF_Master.Helper; using PDF_Master.Model; using PDF_Master.ViewModels.Tools; using Prism.Commands; using Prism.Events; using Prism.Mvvm; using Prism.Regions; using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Drawing.Imaging; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Input; namespace PDF_Master.ViewModels.PropertyPanel.PDFEdit { public class ImageEditPropertyViewModel : PDFEditVM, INavigationAware { public TextEditToolContentViewModel TextEditToolContentViewModel; private IEventAggregator events; /// /// 用于区分事件的唯一码 /// private string unicode; #region 快捷键 private void ShortCut_KeyDown(object sender, KeyEventArgs e) { if (e.Key == Key.Escape) { if (PDFViewer != null) { if (PDFViewer.ToolManager != null && IsCrop == true) { CancelCropImg(); } } } else if (e.Key == Key.Enter) { CropImg(); } } #endregion 快捷键 #region 属性和变量 //防止自动保存属性值 private bool isCanSave = false; public event EventHandler ClearCheckedAglin; #region 是否为多选内容 private bool _isMultiSelectImage = false; public bool IsMultiSelectImage { get { return _isMultiSelectImage; } set { SetProperty(ref _isMultiSelectImage, value); } } #endregion 是否为多选内容 private string _opacity1 = "Opacity"; public string Opacity { get { return _opacity1; } set { SetProperty(ref _opacity1, value); } } //不透明度 private double _opacity; public double OpacityUI { get { return _opacity; } set { SetProperty(ref _opacity, value); } } private int _OpacitySelectedIndex = 1; public int OpacitySelectedIndex { get { return _OpacitySelectedIndex; } set { SetProperty(ref _OpacitySelectedIndex, value); } } private double _transpent; public double Transpent { get { return _transpent; } set { SetProperty(ref _transpent, value); if (Transpent == 100 || Transpent == 75 || Transpent == 50 || (Transpent == 25)) { switch (Transpent) { case 25: OpacitySelectedIndex = 0; break; case 50: OpacitySelectedIndex = 1; break; case 75: OpacitySelectedIndex = 2; break; case 100: OpacitySelectedIndex = 3; break; } TextEditEvent.Transparency = (int)Math.Ceiling((double)(_transpent * 255) / 100.0); TextEditEvent.UpdatePDFEditByEventArgs(); OpacityUI = _transpent / 100.0; } else { OpacitySelectedIndex = -1; } } } //是否为图片裁剪状态 private bool _isCrop = false; public bool IsCrop { get { return _isCrop; } set { SetProperty(ref _isCrop, value); } } public TextEditToolContentViewModel _viewModel1; //public ImageEditPropertyViewModel(TextEditToolContentViewModel viewModel1) //{ // _viewModel1 = viewModel1; // _viewModel1.PropertyChanged += OnViewModel1PropertyChanged; //} private void OnViewModel1PropertyChanged(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "flg") { IsCrop = _viewModel1.flg; } if (e.PropertyName == "ReplaceImgflg") { if (_viewModel1.ReplaceImgflg == true) { ReplaceImg(); _viewModel1.ReplaceImgflg = false; } } if (e.PropertyName == "REImgflg") { if (_viewModel1.REImgflg == true) { GetImagePreView(); _viewModel1.REImgflg = false; } } if (e.PropertyName == "CropImgflg") { if (_viewModel1.CropImgflg == true) { GetImagePreView(); _viewModel1.CropImgflg = false; } } } //选中的图像 private System.Windows.Media.Imaging.BitmapSource _currentImg; public System.Windows.Media.Imaging.BitmapSource CurrentImg { get { return _currentImg; } set { SetProperty(ref _currentImg, value); } } #endregion 属性和变量 #region Command //替换 public DelegateCommand ReplaceImgCommand { get; set; } //导出 public DelegateCommand ExportImgCommand { get; set; } //裁剪 public DelegateCommand CropImgCommand { get; set; } //对齐 public DelegateCommand ImgAlignCheckedCommand { get; set; } //逆时针旋转 public DelegateCommand AntiClockwiseCommand { get; set; } //顺时针旋转 public DelegateCommand ClockwiseCommand { get; set; } //左右翻转 public DelegateCommand FlipleftrightCommand { get; set; } //上下翻转 public DelegateCommand UpsidedownCommand { get; set; } //裁剪状态 public DelegateCommand CropModeCommand { get; set; } //取消裁剪状态 public DelegateCommand CancelCropCommand { get; set; } //还原裁剪状态 public DelegateCommand RestoreCropCommand { get; set; } //添加文本 public DelegateCommand AddTextCommand { get; set; } //添加图片 public DelegateCommand AddImgCommand { get; set; } //透明度条 public DelegateCommand TranspentslidCommand { get; set; } public DelegateCommand EditImgModeCommand { get; set; } #endregion Command public ImageEditPropertyViewModel(IEventAggregator eventAggregator) { InitCommand(); events = eventAggregator; unicode = App.mainWindowViewModel.SelectedItem.Unicode; } private void InitCommand() { AddTextCommand = new DelegateCommand(AddText); AddImgCommand = new DelegateCommand(AddImg); ReplaceImgCommand = new DelegateCommand(ReplaceImg); ExportImgCommand = new DelegateCommand(ExportImg); CropImgCommand = new DelegateCommand(CropImg); ImgAlignCheckedCommand = new DelegateCommand(ImgAlignChecked); TranspentslidCommand = new DelegateCommand(Transpentslid); AntiClockwiseCommand = new DelegateCommand(AntiClockwise); ClockwiseCommand = new DelegateCommand(Clockwise); FlipleftrightCommand = new DelegateCommand(Flipleftright); UpsidedownCommand = new DelegateCommand(Upsidedown); CropModeCommand = new DelegateCommand(CropMode); CancelCropCommand = new DelegateCommand(CancelCropImg); RestoreCropCommand = new DelegateCommand(RestoreCropImg); EditImgModeCommand = new DelegateCommand(EditImgMode); } #region Command实现 //不透明度滑动左键松开 private void Transpentslid() { if (TextEditEvent != null && isCanSave) { if (IsMultiSelectImage) { foreach (var item in TextEditEventList) { item.Transparency = (int)(_transpent * 2.55); item.UpdatePDFEditByEventArgs(); TextEditEvent.SaveClip(); } } else { TextEditEvent.Transparency = (int)((_transpent * 255) / 100.0); TextEditEvent.UpdatePDFEditByEventArgs(); OpacityUI = _transpent / 100.0; TextEditEvent.SaveClip(); } } } //点击编辑按钮,暂时保留 private void EditImgMode() { } //添加文本模式 private void AddText() { PDFViewer.SetPDFEditCreateType(ComPDFKit.PDFPage.CPDFEditType.EditText); } //添加图片 private void AddImg() { OpenFileDialog openFileDialog = new OpenFileDialog(); openFileDialog.Filter = "png|*.png;|Image|*.gif;*.jpg;*.jpeg;*.bmp;*.jfif;*.png;"; openFileDialog.Multiselect = true; if ((bool)openFileDialog.ShowDialog()) { if (string.IsNullOrEmpty(openFileDialog.FileName) == false) { PDFViewer.SetPDFEditCreateType(ComPDFKit.PDFPage.CPDFEditType.EditImage); PDFViewer.AddPDFEditImage(CompressImage(openFileDialog.FileName, 800), 500, 500); events.GetEvent().Publish(new PageEditNotifyEventArgs(unicode)); } } } /// /// 压缩 /// /// /// /// public static string CompressImage(string filePath, int maxwidth = 600) { try { string sourcepath = filePath; var guid = Guid.NewGuid().ToString(); string folder = Path.Combine(App.CurrentPath, "Temp"); if (!Directory.Exists(folder)) { Directory.CreateDirectory(folder); } var path = System.IO.Path.Combine(App.CurrentPath, "Temp", guid); Bitmap bitmap = new Bitmap(sourcepath); var b = bitmap; //bitmap.Dispose(); double scale = Math.Min((double)maxwidth / b.Width, (double)maxwidth / b.Height); scale = Math.Min(scale, 1); System.Drawing.Size newsize = new System.Drawing.Size(maxwidth, maxwidth); newsize.Width = (int)(scale * b.Width); newsize.Height = (int)(scale * b.Height); if (!File.Exists(path)) { if (CheckTextFile(sourcepath) == FileExtension.PNG) { using (var bp = new Bitmap(b, (int)newsize.Width, (int)newsize.Height)) { bp.Save(path, ImageFormat.Png); } } else { using (var bp = new Bitmap(b, (int)newsize.Width, (int)newsize.Height)) { bp.Save(path, ImageFormat.Jpeg); } } } return path; } catch { return filePath; } } /// /// 根据图片数据判断图片类型 /// /// /// public static FileExtension CheckTextFile(string fileName) { FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read); System.IO.BinaryReader br = new System.IO.BinaryReader(fs); string fileType = string.Empty; ; try { byte data = br.ReadByte(); fileType += data.ToString(); data = br.ReadByte(); fileType += data.ToString(); FileExtension extension; try { extension = (FileExtension)Enum.Parse(typeof(FileExtension), fileType); } catch { extension = FileExtension.VALIDFILE; } return extension; } catch (Exception ex) { throw ex; } finally { if (fs != null) { fs.Close(); br.Close(); } } } //进入裁剪模式 private void CropMode() { IsCrop = true; if (TextEditEvent != null) { TextEditEvent.ClipImage = true; TextEditEvent.UpdatePDFEditByEventArgs(); } } //取消裁剪 private void CancelCropImg() { if (TextEditEvent != null) { TextEditEvent.ClipImage = false; TextEditEvent.CancelClip(); TextEditEvent.UpdatePDFEditByEventArgs(); IsCrop = false; } } //还原裁剪 private void RestoreCropImg() { if (TextEditEvent != null) { TextEditEvent.RestoreClip(); events.GetEvent().Publish(new PageEditNotifyEventArgs(unicode)); } } //完成裁剪 private void CropImg() { if (TextEditEvent != null) { TextEditEvent.SaveClip(); TextEditEvent.ClipImage = false; TextEditEvent.UpdatePDFEditByEventArgs(); IsCrop = false; GetImagePreView(); } } //导出图片 private void ExportImg() { if (PDFViewer == null || TextEditEvent == null || TextEditEvent.EditType != ComPDFKit.PDFPage.CPDFEditType.EditImage) return; System.Windows.Forms.FolderBrowserDialog folder = new System.Windows.Forms.FolderBrowserDialog(); folder.SelectedPath = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile); if (folder.ShowDialog() == System.Windows.Forms.DialogResult.OK) { if (string.IsNullOrEmpty(folder.SelectedPath)) return; var keyValueList = PDFViewer.GetSelectedImages(); int i = 0; foreach (var bitmap in keyValueList) { foreach (var bitmapItem in bitmap.Value) { bitmapItem.Save(folder.SelectedPath + "\\" + i + ".png", System.Drawing.Imaging.ImageFormat.Png); i++; } } var strFilePath = folder.SelectedPath + "\\0.png"; CommonHelper.ShowFileBrowser(strFilePath); } } //替换图片 private void ReplaceImg() { OpenFileDialog openFileDialog = new OpenFileDialog(); openFileDialog.Filter = "png|*.png;|Image|*.gif;*.jpg;*.jpeg;*.bmp;*.jfif;*.png;"; openFileDialog.Multiselect = true; if ((bool)openFileDialog.ShowDialog()) { if (string.IsNullOrEmpty(openFileDialog.FileName) == false) { TextEditEvent.ReplaceImagePath = openFileDialog.FileName; TextEditEvent.UpdatePDFEditByEventArgs(); ReplaceimgTask(); Transpent = 100; } } } //此处只有异步 ReplaceimgTask()才有作用 private async void ReplaceimgTask() { await Task.Delay(10); GetImagePreView(); } //顺时针旋转 private void Clockwise() { ImgRoateAngle(90); } //逆时针旋转 private void AntiClockwise() { ImgRoateAngle(-90); } //左右翻转 private void Flipleftright() { TextEditEvent.HorizontalMirror = true; TextEditEvent.UpdatePDFEditByEventArgs(); GetImagePreView(); } //上下翻转 private void Upsidedown() { TextEditEvent.VerticalMirror = true; TextEditEvent.UpdatePDFEditByEventArgs(); GetImagePreView(); } //旋转逻辑 private void ImgRoateAngle(int angle) { if (IsMultiSelectImage) { foreach (var item in TextEditEventList) { item.Rotate = item.Rotate + angle; item.UpdatePDFEditByEventArgs(); } } else { TextEditEvent.Rotate = TextEditEvent.Rotate + angle; TextEditEvent.UpdatePDFEditByEventArgs(); GetImagePreView(); } } #endregion Command实现 #region 布局处理 private void ImgAlignChecked(object obj) { if (obj != null) { switch ((string)obj) { case "AlignLeft": PDFViewer.SetPDFEditAligment(AlignModes.AlignLeft); break; case "AlignHorizonCenter": PDFViewer.SetPDFEditAligment(AlignModes.AlignHorizonCenter); break; case "AlignRight": PDFViewer.SetPDFEditAligment(AlignModes.AlignRight); break; case "DistributeHorizontal": PDFViewer.SetPDFEditAligment(AlignModes.DistributeHorizontal); break; case "AlignTop": PDFViewer.SetPDFEditAligment(AlignModes.AlignTop); break; case "AlignVerticalCenter": PDFViewer.SetPDFEditAligment(AlignModes.AlignVerticalCenter); break; case "AlignBottom": PDFViewer.SetPDFEditAligment(AlignModes.AlignBottom); break; case "DistributeVertical": PDFViewer.SetPDFEditAligment(AlignModes.DistributeVertical); break; } } } #endregion 布局处理 protected List TextEditEventList; public void OnNavigatedTo(NavigationContext navigationContext) { navigationContext.Parameters.TryGetValue(ParameterNames.PDFViewer, out PDFViewer); navigationContext.Parameters.TryGetValue>(ParameterNames.AnnotEvent, out TextEditEventList); navigationContext.Parameters.TryGetValue(ParameterNames.TextEditToolContentViewModel, out TextEditToolContentViewModel); if (PDFViewer != null) { _viewModel1 = TextEditToolContentViewModel; _viewModel1.PropertyChanged += OnViewModel1PropertyChanged; PDFViewer.PDFEditActiveHandler -= PDFViewer_PDFEditActiveHandler; PDFViewer.PDFEditActiveHandler += PDFViewer_PDFEditActiveHandler; PDFViewer.PDFEditCommandHandler -= PDFViewer_PDFEditCommandHandler; PDFViewer.PDFEditCommandHandler += PDFViewer_PDFEditCommandHandler; PDFViewer.LostFocus -= PDFViewer_LostFocus; PDFViewer.LostFocus += PDFViewer_LostFocus; KeyEventsHelper.KeyDown -= ShortCut_KeyDown; KeyEventsHelper.KeyDown += ShortCut_KeyDown; LoadedPDFEdit(); isCanSave = true; } } private void PDFViewer_LostFocus(object sender, RoutedEventArgs e) { TextEditEvent.ClipImage = false; TextEditEvent.CancelClip(); TextEditEvent.UpdatePDFEditByEventArgs(); IsCrop = false; } //获取图片参数 private void LoadedPDFEdit() { if (TextEditEventList != null && TextEditEventList.Count > 0) { TextEditEvent = TextEditEventList[0]; if (TextEditEventList.Count > 1) { IsMultiSelectImage = true; } else { GetImagePreView(); } if (TextEditEventList.Count == 2) { IsLayoutAlign = true; IsLayoutAvgAlign = false; } else if (TextEditEventList.Count > 2) { IsLayoutAlign = true; IsLayoutAvgAlign = true; } else { IsLayoutAlign = false; IsLayoutAvgAlign = false; } var tranUI = (TextEditEvent.Transparency * 100 / 255); var temp = Math.Round((double)tranUI, 0); Transpent = temp; OpacityUI = temp / 100.0; } } #region 右键菜单 //点击空白处时 private ContextMenu EmptyStateMenu(object sender) { var popMenu = App.Current.FindResource("NoneMenu") as ContextMenu; CustomPopMenu customMenu = new CustomPopMenu(popMenu, sender); //粘贴 customMenu.SetMenuBinding(0, ApplicationCommands.Paste); //添加文本 customMenu.SetMenuBinding(1, AddTextCommand); //添加图像 customMenu.SetMenuBinding(2, AddImgCommand); return popMenu; } //选中图像时 private ContextMenu SelectImgPDFEdit(object sender) { var popMenu = App.Current.FindResource("SelectImgMenu") as ContextMenu; CustomPopMenu customMenu = new CustomPopMenu(popMenu, sender); //复制 customMenu.SetMenuBinding(0, ApplicationCommands.Copy); //剪切 customMenu.SetMenuBinding(1, ApplicationCommands.Cut); //粘贴 customMenu.SetMenuBinding(2, ApplicationCommands.Paste); //删除 customMenu.SetMenuBinding(3, ApplicationCommands.Delete); //裁剪 customMenu.SetMenuBinding(4, CropModeCommand); //替换 customMenu.SetMenuBinding(5, ReplaceImgCommand); //导出 customMenu.SetMenuBinding(6, ExportImgCommand); return popMenu; } //选中裁剪图像时 private ContextMenu CropImgPDFEdit(object sender) { var popMenu = App.Current.FindResource("CropImgMenu") as ContextMenu; CustomPopMenu customMenu = new CustomPopMenu(popMenu, sender); //确认裁剪 customMenu.SetMenuBinding(0, CropImgCommand); //取消裁剪 customMenu.SetMenuBinding(1, CancelCropCommand); //还原裁剪 customMenu.SetMenuBinding(2, RestoreCropCommand); return popMenu; } //多选图片右键 private ContextMenu SelectMoreImage(object sender) { var popMenu = App.Current.FindResource("SelectMoreImageMenu") as ContextMenu; CustomPopMenu customMenu = new CustomPopMenu(popMenu, sender); //复制 customMenu.SetMenuBinding(0, ApplicationCommands.Copy); //剪切 customMenu.SetMenuBinding(1, ApplicationCommands.Cut); //粘贴 customMenu.SetMenuBinding(2, ApplicationCommands.Paste); //删除 customMenu.SetMenuBinding(3, ApplicationCommands.Delete); //导出 customMenu.SetMenuBinding(4, ExportImgCommand); return popMenu; } #endregion 右键菜单 //左键点击逻辑 private void PDFViewer_PDFEditActiveHandler(object sender, List e) { //退出编辑模式 IsCrop = false; TextEditEvent.ClipImage = false; TextEditEvent.UpdatePDFEditByEventArgs(); } //右键逻辑 private void PDFViewer_PDFEditCommandHandler(object sender, PDFEditCommand e) { if (e == null) return; switch (e.CommandType) { case CommandType.Context: // if (e.EditType == ComPDFKit.PDFPage.CPDFEditType.EditImage) //{ // if (IsCrop == true) // { // e.PopupMenu =CropImgPDFEdit(sender); // } // else // { // e.PopupMenu = SelectImgPDFEdit(sender); // } //} //else if (e.EditType == ComPDFKit.PDFPage.CPDFEditType.None) { e.PopupMenu = EmptyStateMenu(sender); } break; default: e.DoCommand(); break; } if (e.PopupMenu != null) { e.Handle = true; } } //属性面板图像更新 private void GetImagePreView() { try { var list = PDFViewer.GetSelectedImages(); if (list != null && list.Count > 0) { System.Drawing.Bitmap bitmap = null; foreach (var item in list) { if (item.Value.Count > 0) { bitmap = item.Value[0]; break; } } if (bitmap != null) { IntPtr ip = bitmap.GetHbitmap(); System.Windows.Media.Imaging.BitmapSource bitmapSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(ip, IntPtr.Zero, Int32Rect.Empty, System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions()); CurrentImg = bitmapSource; events.GetEvent().Publish(new PageEditNotifyEventArgs(unicode)); } } } catch { } } public bool IsNavigationTarget(NavigationContext navigationContext) { return true; } public void OnNavigatedFrom(NavigationContext navigationContext) { isCanSave = false; IsMultiSelectImage = false; TextEditEvent = null; ClearCheckedAglin?.Invoke(null, null); PDFViewer.PDFEditCommandHandler -= PDFViewer_PDFEditCommandHandler; PDFViewer.PDFEditActiveHandler -= PDFViewer_PDFEditActiveHandler; KeyEventsHelper.KeyDown -= ShortCut_KeyDown; PDFViewer.LostFocus -= PDFViewer_LostFocus; } } }