123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658 |
- using ComPDFKit.PDFDocument;
- using ComPDFKit.PDFPage;
- using ComPDFKitViewer.PdfViewer;
- using Dropbox.Api.TeamLog;
- using Microsoft.Office.Interop.Word;
- using Microsoft.Win32;
- using PDF_Master.CustomControl;
- using PDF_Master.EventAggregators;
- using PDF_Master.Helper;
- using PDF_Master.Model;
- using PDF_Master.Model.Dialog.ToolsDialogs;
- using PDF_Master.Properties;
- using PDF_Master.Views.Dialog;
- using Prism.Commands;
- using Prism.Events;
- using Prism.Mvvm;
- using Prism.Services.Dialogs;
- using System;
- using System.Collections.Generic;
- using System.Collections.ObjectModel;
- using System.IO;
- using System.Linq;
- using System.Reflection;
- using System.Text;
- using System.Threading.Tasks;
- using System.Windows;
- using System.Windows.Controls;
- using System.Windows.Media;
- using System.Windows.Media.Imaging;
- using static Dropbox.Api.TeamLog.PaperDownloadFormat;
- using static PDF_Master.Model.Dialog.ToolsDialogs.SaftyDialogs.DeleteSafetySettintgsModel;
- namespace PDF_Master.ViewModels.Dialog.ToolsDialogs
- {
- class MergeDialogViewModel : BindableBase, IDialogAware
- {
- // Fix:存储当前程序加载的文档的路径和tag,
- //如果路径相同则用tag里的密码解锁,
- //解锁失败再另行提权
- private string CurrentFilePath = string.Empty;
- private string currentLoadedPassword = string.Empty;
- private IEventAggregator eventAggregator;
- enum PageSizeType
- {
- kDefault = 0,
- A4 = 1,
- A3 = 2,
- Letter = 3,
- Legal = 4,
- Customized = 5,
- }
- #region 框架内容
- public string Title => "";
- public event Action<IDialogResult> RequestClose;
- public bool CanCloseDialog()
- {
- return true;
- }
- public void OnDialogClosed()
- {
- }
- public void OnDialogOpened(IDialogParameters parameters)
- {
- CPDFViewer pdfViewer = null;
- if (parameters.TryGetValue<CPDFViewer>(ParameterNames.PDFViewer, out pdfViewer) && pdfViewer != null && pdfViewer.Document != null)
- {
- VerifyPasswordResult condition = SecurityHelper.VerifyPasswordByPasswordKind(pdfViewer.Document, EnumPasswordKind.StatusPermissionsPassword, dialogs);
- if (condition.IsDiscryptied)
- {
- if (!string.IsNullOrEmpty(condition.Password))
- {
- if (pdfViewer.Document.UnlockWithPassword(condition.Password))
- {
- pdfViewer.Document.CheckOwnerPassword(condition.Password);
- }
- }
- string unicode;
- if (parameters.TryGetValue<string>(ParameterNames.Unicode, out unicode))
- {
- this.eventAggregator.GetEvent<ShowTipEvent>().Publish(new ShowTipEventArgs() { enumTipKind = EnumTipKind.StatusNone, Unicode = unicode });
- }
- }
- currentLoadedPassword = pdfViewer.Document.Password;
- }
- if (pdfViewer != null && pdfViewer.Document != null)
- {
- CurrentFilePath = pdfViewer.Document.FilePath;
- List<string> list = new List<string>();
- list.Add(CurrentFilePath);
- AddFiles(list.ToArray());
- }
- string[] Paths;
- parameters.TryGetValue<string[]>(ParameterNames.FilePath, out Paths);
- if (Paths != null)
- {
- AddFiles(Paths);
- }
- }
- #endregion
- #region 定义与初始化
- public ObservableCollection<MergeObject> MergeObjectlist { get; set; }
- public DelegateCommand CancelCommand { get; set; }
- public DelegateCommand<object> PreviewCancelDownCommand { get; set; }
- public DelegateCommand MergeCommand { get; set; }
- public DelegateCommand<object> AddFilesCommand { get; set; }
- public DelegateCommand ClearCommand { get; set; }
- public DelegateCommand<object> SetPageSizeTypeCommand { get; set; }
- public IDialogService dialogs;
- private PageSizeType pageSizeType = PageSizeType.kDefault;
- private string inputWidth;
- public string InputWidth
- {
- get { return inputWidth; }
- set
- {
- SetProperty(ref inputWidth, value);
- }
- }
- private string inputHeight;
- public string InputHeight
- {
- get { return inputHeight; }
- set
- {
- SetProperty(ref inputHeight, value);
- }
- }
- private int comboBoxSelectedIndex = 0;
- public int ComboBoxSelectedIndex
- {
- get { return comboBoxSelectedIndex; }
- set
- {
- SetProperty(ref comboBoxSelectedIndex, value);
- }
- }
- public MergeDialogViewModel(IDialogService dialogService, IEventAggregator eventAggregator)
- {
- this.eventAggregator = eventAggregator;
- dialogs = dialogService;
- MergeObjectlist = new ObservableCollection<MergeObject>();
- CancelCommand = new DelegateCommand(Cancel);
- PreviewCancelDownCommand = new DelegateCommand<object>(PreviewCancelDown);
- AddFilesCommand = new DelegateCommand<object>(ButtonAddFiles);
- MergeCommand = new DelegateCommand(Merge);
- ClearCommand = new DelegateCommand(Clear);
- SetPageSizeTypeCommand = new DelegateCommand<object>(SetPageSizeType);
- }
- #endregion
- #region 私有方法
- private void UpDataMergeObjectIndex()
- {
- for (int i = 0; i < MergeObjectlist.Count; i++)
- {
- MergeObjectlist[i].ItemIndex = i + 1;
- }
- }
- private void Cancel()
- {
- Clear();
- RequestClose.Invoke(new DialogResult(ButtonResult.Cancel));
- }
- /// <summary>
- /// 点击取消页面范围控件使失去焦点不生效
- /// </summary>
- private void PreviewCancelDown(object e)
- {
- var listView = e as ListView;
- if (listView != null)
- {
- if (listView.ItemsSource != null)
- {
- foreach (var item in listView.ItemsSource)
- {
- var pagerange= listView.ItemContainerGenerator.ContainerFromItem(item) as ListViewItem;
- if (pagerange != null)
- {
- var pagerangecombobox= CommonHelper.FindVisualChild<WritableComboBox>(pagerange);
- if(pagerangecombobox!=null)
- pagerangecombobox.IsloseFocus = false;
- }
- }
- }
- }
- }
- public void ButtonAddFiles(object data)
- {
- int index = Convert.ToInt32(data);
- switch (index)
- {
- case 0:
- //打开文件
- ComboBoxSelectedIndex = 0;//打开文件弹窗会影响UI更新,所以手动更新
- AddFiles(OpenFile());
- break;
- case 1:
- //打开文件夹
- ComboBoxSelectedIndex = 1;//打开文件夹弹窗会影响UI更新,所以手动更新
- AddFiles(OpenFileFolder());
- break;
- case 2:
- //打开当前文件
- List<string> list = new List<string>();
- for (int i = 0; i < App.OpenedFileList.Count; i++)
- {
- list.Add(App.OpenedFileList[i]);
- }
- AddFiles(list.ToArray());
- break;
- default:
- break;
- }
- }
- private string[] OpenFileFolder()
- {
- System.Windows.Forms.FolderBrowserDialog openFile = new System.Windows.Forms.FolderBrowserDialog();
- if (openFile.ShowDialog() == System.Windows.Forms.DialogResult.Cancel)
- {
- return null;
- }
- DirectoryInfo tempfolder = new DirectoryInfo(openFile.SelectedPath);
- FileInfo[] fileInfos = tempfolder.GetFiles();
- List<string> list = new List<string>();
- foreach (FileInfo item in fileInfos)
- {
- list.Add(item.FullName);
- }
- DirectoryInfo[] directoryInfos = tempfolder.GetDirectories();
- foreach (DirectoryInfo fileInfo in directoryInfos)
- {
- FileInfo[] fileinfo = fileInfo.GetFiles();
- foreach (FileInfo item in fileinfo)
- {
- list.Add(item.FullName);
- }
- }
- return list.ToArray();
- }
- private string[] OpenFile()
- {
- OpenFileDialog openFile = new OpenFileDialog();
- openFile.Multiselect = true;
- openFile.Filter = Properties.Resources.imageex.ToLower() + "|*";
- if (openFile.ShowDialog() == false)
- {
- return null;
- }
- return openFile.FileNames;
- }
- private void Merge()
- {
-
- bool result = true;
- CPDFDocument SaveDoc = CPDFDocument.CreateDocument();
- for (int i = 0; i < MergeObjectlist.Count; i++)
- {
- List<int> listnum = new List<int>();
- if (MergeObjectlist[i].SetPageRange == null || MergeObjectlist[i].SetPageRange.Count == 0)
- {
- AlertsMessage alertsMessage = new AlertsMessage();
- alertsMessage.ShowDialog("", App.MainPageLoader.GetString("PageRangeWarning"), App.ServiceLoader.GetString("Text_ok"));
- return;
- }
- }
-
- for (int i = 0; i < MergeObjectlist.Count; i++)
- {
- if (MergeObjectlist[i].SetPageRange == null)
- {
- AlertsMessage alertsMessage = new AlertsMessage();
- alertsMessage.ShowDialog("", App.MainPageLoader.GetString("PageRangeWarning"), App.ServiceLoader.GetString("Text_ok"));
- }
- //图片
- if (Path.GetExtension(MergeObjectlist[i].FilePath).Trim().ToLower() != ".pdf")
- {
- if (Path.GetExtension(MergeObjectlist[i].FilePath).Trim().ToLower() == ".gif")
- {//GIF下面方法产生虚影改成与图片转PDF一致
- System.Drawing.Image img = System.Drawing.Image.FromFile(MergeObjectlist[i].FilePath);
- string tempFileName = Path.GetTempPath() + "pngtemp.jpg";
- if (!PictureConverter.SaveJpeg(MergeObjectlist[i].FilePath, tempFileName))
- {
- MessageBoxEx.Show("图片格式有问题");
- }
- // 之前插入位置为零点导致插入为第一页,改为尾插 2023/5/24
- result = SaveDoc.InsertPage(SaveDoc.PageCount, img.Width, img.Height, tempFileName);
- try { if (File.Exists(tempFileName)) File.Delete(tempFileName); }
- catch
- { }
- if (!result)
- {
- SaveDoc.Release();
- return;
- }
- continue;
- }
- else
- {
- BitmapSource frame = MergeObjectlist[i].DocThumbnail;
- byte[] imageData = new byte[frame.PixelWidth * frame.PixelHeight * 4];
- if (frame.Format != PixelFormats.Bgra32)
- {
- FormatConvertedBitmap covert = new FormatConvertedBitmap(frame, PixelFormats.Bgra32, frame.Palette, 0);
- covert.CopyPixels(imageData, frame.PixelWidth * 4, 0);
- }
- else
- {
- frame.CopyPixels(imageData, frame.PixelWidth * 4, 0);
- }
- frame.CopyPixels(imageData, frame.PixelWidth * 4, 0);
- // 之前插入位置为零点导致插入为第一页,改为尾插 2023/5/24
- result = SaveDoc.InsertPage(SaveDoc.PageCount, frame.PixelWidth, frame.PixelHeight, imageData, CPDFDocumentImageMode.CPDFDocumentImageModeScaleToFill);
- if (!result)
- {
- SaveDoc.Release();
- return;
- }
- continue;
- }
- }
- else
- {
- CPDFDocument tempDoc = CPDFDocument.InitWithFilePath(MergeObjectlist[i].FilePath);
- if (!string.IsNullOrEmpty(MergeObjectlist[i].Password))
- {
- tempDoc.UnlockWithPassword(MergeObjectlist[i].Password);
- }
- if (!string.IsNullOrEmpty(MergeObjectlist[i].SetPageRangeStr))
- {
- result = SaveDoc.ImportPages(tempDoc, MergeObjectlist[i].SetPageRangeStr);
- }
- else
- {
- //下拉框控件传出来的list是页面索引集合,
- //此处传给SDK的合并接口的是页码集合,因此需要将集合项遍历+1,只有合并接口是接收页码集合,其余接口是接受页面索引集合
- List<int> pageIndexs = new List<int>();
- for (int j = 0; j < MergeObjectlist[i].SetPageRange.Count; j++)
- {
- pageIndexs.Add(MergeObjectlist[i].SetPageRange[j] + 1);
- }
- result = SaveDoc.ImportPages(tempDoc, CommonHelper.GetPageParmFromList(pageIndexs));
- }
- if (!result)
- {
- SaveDoc.Release();
- tempDoc.Release();
- return;
- }
- tempDoc.Release();
- }
- }
- SaveFileDialog saveFileDialog = new SaveFileDialog();
- saveFileDialog.FileName = "Untitle";
- saveFileDialog.Filter = "PDF|*.pdf;";
- if (saveFileDialog.ShowDialog() == false)
- {
- return;
- }
- string path = saveFileDialog.FileName;
- System.Windows.Rect rect = new System.Windows.Rect();
- switch (pageSizeType)
- {
- case PageSizeType.kDefault:
- break;
- case PageSizeType.A4:
- rect.Width = CommonHelper.GetPageSizeFomrUnit(210);
- rect.Height = CommonHelper.GetPageSizeFomrUnit(297);
- break;
- case PageSizeType.A3:
- rect.Width = CommonHelper.GetPageSizeFomrUnit(297);
- rect.Height = CommonHelper.GetPageSizeFomrUnit(420);
- break;
- case PageSizeType.Letter:
- rect.Width = CommonHelper.GetPageSizeFomrUnit(216);
- rect.Height = CommonHelper.GetPageSizeFomrUnit(279);
- break;
- case PageSizeType.Legal:
- rect.Width = CommonHelper.GetPageSizeFomrUnit(216);
- rect.Height = CommonHelper.GetPageSizeFomrUnit(356);
- break;
- case PageSizeType.Customized:
- if (!string.IsNullOrEmpty(InputWidth) && !string.IsNullOrEmpty(InputHeight))
- {
- rect.Width = CommonHelper.GetPageSizeFomrUnit(Convert.ToInt32(InputWidth));
- rect.Height = CommonHelper.GetPageSizeFomrUnit(Convert.ToInt32(InputHeight));
- }
- else
- {
- rect.Width = CommonHelper.GetPageSizeFomrUnit(595);
- rect.Height = CommonHelper.GetPageSizeFomrUnit(841);
- }
- break;
- default:
- break;
- }
- if (rect.Width > 0 && rect.Height > 0)
- {
- //裁剪
- for (int i = 0; i < SaveDoc.PageCount; i++)
- {
- CPDFPage page = SaveDoc.PageAtIndex(i);
- page.CropPage(CPDFDisplayBox.MediaBox, rect);
- }
- }
- bool saveResult = SaveDoc.WriteToFilePath(path);
- SaveDoc.Release();
- CommonHelper.ShowFileBrowser(path);
- DialogParameters valuePairs = new DialogParameters();
- valuePairs.Add(ParameterNames.FilePath, path);
- RequestClose.Invoke(new DialogResult(ButtonResult.OK, valuePairs));
- }
- private void Clear()
- {
- MergeObjectlist.Clear();
- }
- private void SetPageSizeType(object button)
- {
- if (button is RadioButton)
- {
- pageSizeType = (PageSizeType)Convert.ToInt32((button as RadioButton).Tag);
- }
- }
- #endregion
- #region 公开方法
- public void DeleteItem(MergeObject merge)
- {
- MergeObjectlist.Remove(merge);
- UpDataMergeObjectIndex();
- }
- /// <summary>
- /// 拖拽插入
- /// </summary>
- public void MoveMerge(MergeObject targetNode, MergeObject soureNode)
- {
- int targetindex = MergeObjectlist.IndexOf(targetNode);
- MergeObjectlist.Remove(soureNode);
- if (targetNode.IsForward)
- {
- if (targetindex + 1 < MergeObjectlist.Count)
- {
- MergeObjectlist.Insert(targetindex + 1, soureNode);
- }
- else
- {
- MergeObjectlist.Add(soureNode);
- }
- }
- else
- {
- MergeObjectlist.Insert(targetindex, soureNode);
- }
- UpDataMergeObjectIndex();
- }
- public void AddFiles(string[] FilePath)
- {
- if (FilePath == null)
- {
- return;
- }
- bool showDialog = false;
- for (int i = 0; i < FilePath.Length; i++)
- {
- MergeObject mergeObject = new MergeObject();
- mergeObject.FilePath = FilePath[i];
- //通过路径判断文件是否已添加
- bool IsExists = false;
- for (int j = 0; j < MergeObjectlist.Count; j++)
- {
- if (MergeObjectlist[j].FilePath == mergeObject.FilePath)
- {
- IsExists = true;
- }
- }
- if (IsExists)
- {
- continue;
- }
- string FileType = Path.GetExtension(mergeObject.FilePath).Trim().ToLower();
- if (string.IsNullOrEmpty(FileType))
- {
- showDialog = true;
- //获取不到文件类型
- continue;
- }
- if (FileType != ".pdf")
- {
- string imagetype = "*" + FileType;
- string[] x = Properties.Resources.imageex.ToLower().Split(';');
- List<string> list = x.ToList();
- int imageindex = list.IndexOf(imagetype);
- if (imageindex < 0)
- {
- showDialog = true;
- //图片格式不支持
- continue;
- };
- mergeObject.DocName = Path.GetFileName(mergeObject.FilePath);
- mergeObject.DocPageCount = 1 + " " + App.MainPageLoader.GetString("Merge_ItemPages");
- mergeObject.SDKPageCount = 1;
- mergeObject.DocSize = CommonHelper.GetFileSize(mergeObject.FilePath);
- try
- {
- mergeObject.DocThumbnail = new BitmapImage(new Uri(mergeObject.FilePath));
- }
- catch (Exception)
- {
- showDialog = true;
- //解码错误
- continue;
- }
- }
- else
- {
- CPDFDocument doc = CPDFDocument.InitWithFilePath(mergeObject.FilePath);
- if (doc == null)
- {
- showDialog = true;
- //PDF打开失败
- continue;
- }
- ///Fix:
- ///情况分为:
- ///开启路径是当前路径:
- ///已解锁或本身就无密码->直接加入
- ///未解锁-> release
- ///
- /// 不是当前路径
- ///解锁或取消->
- ///
- if (CurrentFilePath == doc.FilePath)
- {
- if ((!(!doc.IsLocked && (SecurityHelper.CheckHaveAllPermissions(doc)))) &&
- (!(!string.IsNullOrEmpty(currentLoadedPassword) &&
- doc.UnlockWithPassword(currentLoadedPassword) &&
- (doc.CheckOwnerPassword(currentLoadedPassword) || SecurityHelper.CheckHaveAllPermissions(doc)))))
- {
- doc.Release();
- continue;
- }
- //添加的第一个文档有权限密码时,保存密码,避免合并时因没有密码导致合并失败
- //表现为在首页打开一个带权限的文档进入合并,点击合并按钮没有反应
- if (!string.IsNullOrEmpty(currentLoadedPassword))
- {
- mergeObject.Password = currentLoadedPassword;
- }
- }
- else
- {
- VerifyPasswordResult condition = SecurityHelper.VerifyPasswordByPasswordKind(doc, EnumPasswordKind.StatusPermissionsPassword, dialogs);
- if (condition.IsDiscryptied)
- {
- if (condition.Password != null)
- {
- mergeObject.Password = condition.Password;
- if (doc.UnlockWithPassword(condition.Password) && doc.CheckOwnerPassword(condition.Password))
- {
- }
- }
- }
- else
- {
- doc.Release();
- continue;
- }
- }
- mergeObject.DocName = doc.FileName;
- mergeObject.DocPageCount = doc.PageCount.ToString() + " " + App.MainPageLoader.GetString("Merge_ItemPages");
- if (doc.PageCount > 1)
- {
- mergeObject.IsEvenPageIsEnabled = true;
- }
- else
- {
- mergeObject.IsEvenPageIsEnabled = false;
- }
- mergeObject.SDKPageCount = doc.PageCount;
- mergeObject.DocSize = CommonHelper.GetFileSize(mergeObject.FilePath);
- //获取第一页缩略图
- CPDFPage page = doc.PageAtIndex(0);
- Size size = doc.GetPageSize(0);
- byte[] bmpData = new byte[(int)(size.Width * size.Height * 4)];
- WriteableBitmap WirteBitmap = new WriteableBitmap((int)size.Width, (int)size.Height, 96, 96, PixelFormats.Bgra32, null);
- page.RenderPageBitmap(0, 0, (int)size.Width, (int)size.Height, 0xFFFFFFFF, bmpData, 1);
- WirteBitmap.WritePixels(new Int32Rect(0, 0, (int)size.Width, (int)size.Height), bmpData, WirteBitmap.BackBufferStride, 0);
- WirteBitmap.Freeze();
- mergeObject.DocThumbnail = WirteBitmap;
- doc.Release();
- }
- MergeObjectlist.Add(mergeObject);
- UpDataMergeObjectIndex();
- }
- if (showDialog)
- {
- AlertsMessage alertsMessage = new AlertsMessage();
- alertsMessage.ShowDialog("", App.MainPageLoader.GetString("ErrorFile_Warning"), App.ServiceLoader.GetString("Text_ok"));
- if (alertsMessage.result == ContentResult.Ok)
- {
- }
- }
- }
- #endregion
- }
- }
|