PageEditContentViewModel.cs 85 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475
  1. using Prism.Mvvm;
  2. using Prism.Regions;
  3. using Prism.Services.Dialogs;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Linq;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. using System.Windows.Media;
  10. using ComPDFKitViewer.PdfViewer;
  11. using PDF_Master.Model;
  12. using System.Collections.ObjectModel;
  13. using PDF_Master.Model.PageEdit;
  14. using Prism.Commands;
  15. using System.Windows;
  16. using System.Windows.Media.Imaging;
  17. using System.Windows.Controls.Primitives;
  18. using System.Diagnostics;
  19. using System.Windows.Controls;
  20. using System.Windows.Threading;
  21. using Prism.Events;
  22. using PDF_Master.EventAggregators;
  23. using System.Windows.Input;
  24. using PDF_Master.Helper;
  25. using Microsoft.Win32;
  26. using ComPDFKit.PDFDocument;
  27. using PDF_Master.CustomControl;
  28. using PDF_Master.Model.HomePageToolsDialogs;
  29. using System.IO;
  30. using System.Text.RegularExpressions;
  31. using static PDF_Master.Model.Dialog.ToolsDialogs.SaftyDialogs.DeleteSafetySettintgsModel;
  32. using PDF_Master.Model.Dialog.ToolsDialogs.SaftyDialogs;
  33. namespace PDF_Master.ViewModels.PageEdit
  34. {
  35. public class PageEditContentViewModel : BindableBase, INavigationAware
  36. {
  37. #region 文案
  38. private string T_title;
  39. public string T_Title
  40. {
  41. get { return T_title; }
  42. set
  43. {
  44. SetProperty(ref T_title, value);
  45. }
  46. }
  47. private void InitString()
  48. {
  49. T_Title = App.MainPageLoader.GetString("Thumbnails_Title");
  50. }
  51. #endregion
  52. public CPDFViewer PDFViewer;
  53. private ViewContentViewModel viewContentViewModel;
  54. private IDialogService dialogs;
  55. private IEventAggregator eventor;
  56. /// <summary>
  57. /// 用于筛选多窗体时间的唯一识别码
  58. /// </summary>
  59. private string unicode = null;
  60. /// <summary>
  61. /// Undo操作记录栈
  62. /// 只有插入、移位、旋转,倒序需要记录
  63. /// </summary>
  64. private Stack<PageEditHistory> UndoStack = new Stack<PageEditHistory>();
  65. /// <summary>
  66. /// Redo操作记录栈
  67. /// </summary>
  68. private Stack<PageEditHistory> RedoStack = new Stack<PageEditHistory>();
  69. /// <summary>
  70. /// 项数据集合
  71. /// </summary>
  72. public ObservableCollection<PageEditItem> PageEditItems { get; set; }
  73. /// <summary>
  74. /// 页面范围的项集合
  75. /// </summary>
  76. public ObservableCollection<string> PageRangeItems { get; set; }
  77. #region 属性
  78. /// <summary>
  79. /// 是否是第一次加载
  80. /// </summary>
  81. private bool isFirstLoad = true;
  82. /// <summary>
  83. /// 记录多选项中最后一项的索引
  84. /// </summary>
  85. private int maxSelectedIndex = 0;
  86. private Visibility showTip = Visibility.Collapsed;
  87. /// <summary>
  88. /// 是否显示渐隐提示
  89. /// </summary>
  90. public Visibility ShowTip
  91. {
  92. get { return showTip; }
  93. set
  94. {
  95. SetProperty(ref showTip, value);
  96. }
  97. }
  98. private Visibility isLoading = Visibility.Collapsed;
  99. /// <summary>
  100. /// 是否正在处理中
  101. /// </summary>
  102. public Visibility IsLoading
  103. {
  104. get { return isLoading; }
  105. set
  106. {
  107. SetProperty(ref isLoading, value);
  108. }
  109. }
  110. private int listSelecedIndex;
  111. /// <summary>
  112. /// 缩略图选中项的索引
  113. /// </summary>
  114. public int ListSelectedIndex
  115. {
  116. get { return listSelecedIndex; }
  117. set
  118. {
  119. SetProperty(ref listSelecedIndex, value);
  120. if (!IsSelectFormSelf&&value>=0)
  121. {
  122. //显示页面范围选择控件
  123. TxtPageInputVisibility = Visibility.Visible;
  124. TbPageRange = (ListSelectedIndex + 1).ToString();
  125. }
  126. //if (IsBOTAThumb == Visibility.Visible && PDFViewer != null)
  127. //{
  128. // PDFViewer.GoToPage(listSelecedIndex);
  129. //}
  130. }
  131. }
  132. private bool isMultiSelected;
  133. /// <summary>
  134. /// 是否有多选 用于判断倒序和替换功能
  135. /// </summary>
  136. public bool IsMultiSelected
  137. {
  138. get { return isMultiSelected; }
  139. set
  140. {
  141. SetProperty(ref isMultiSelected, value);
  142. }
  143. }
  144. private int comboxSelectIndex;
  145. /// <summary>
  146. /// 下拉框选项集合
  147. /// </summary>
  148. public int ComboxSelectIndex
  149. {
  150. get { return comboxSelectIndex; }
  151. set
  152. {
  153. SetProperty(ref comboxSelectIndex, value);
  154. //隐藏tb页面范围显示控件
  155. TxtPageInputVisibility = Visibility.Collapsed;
  156. //选中指定的页面范围
  157. SuitPageRange(comboxSelectIndex);
  158. }
  159. }
  160. private Visibility tbPageRangeVisibility = Visibility.Visible;
  161. /// <summary>
  162. /// 页面范围的文本显示
  163. /// </summary>
  164. public Visibility TbPageRangeVisibility
  165. {
  166. get { return tbPageRangeVisibility; }
  167. set
  168. {
  169. SetProperty(ref tbPageRangeVisibility, value);
  170. if (value == Visibility.Visible)
  171. {
  172. comboxSelectIndex = -1;
  173. }
  174. }
  175. }
  176. private string tbPageRange;
  177. /// <summary>
  178. /// 页面范围显示的内容
  179. /// </summary>
  180. public string TbPageRange
  181. {
  182. get { return tbPageRange; }
  183. set
  184. {
  185. SetProperty(ref tbPageRange, value);
  186. }
  187. }
  188. private Visibility txtPageInputVisibility = Visibility.Collapsed;
  189. /// <summary>
  190. /// 页面自定义输入框的显示
  191. /// </summary>
  192. public Visibility TxtPageInputVisibility
  193. {
  194. get { return txtPageInputVisibility; }
  195. set
  196. {
  197. SetProperty(ref txtPageInputVisibility, value);
  198. }
  199. }
  200. /// <summary>
  201. /// 页面缩放状态,-1 为最小值,1为最大值
  202. /// </summary>
  203. private int zoomIndex = 0;
  204. public int ZoomIndex
  205. {
  206. get { return zoomIndex; }
  207. set
  208. {
  209. SetProperty(ref zoomIndex, value);
  210. }
  211. }
  212. private string toastText = App.MainPageLoader.GetString("PageEdit_Failed");
  213. /// <summary>
  214. /// Toast提示
  215. /// </summary>
  216. public string ToastText
  217. {
  218. get { return toastText; }
  219. set
  220. {
  221. SetProperty(ref toastText, value);
  222. }
  223. }
  224. private Visibility isBOTAThumb = Visibility.Collapsed;
  225. /// <summary>
  226. /// 是否是BOTA侧边栏的缩略图
  227. /// </summary>
  228. public Visibility IsBOTAThumb
  229. {
  230. get { return isBOTAThumb; }
  231. set
  232. {
  233. SetProperty(ref isBOTAThumb, value);
  234. }
  235. }
  236. private Visibility hasShowPageSize = Visibility.Collapsed;
  237. /// <summary>
  238. /// 是否显示页面尺寸
  239. /// </summary>
  240. public Visibility HasShowPageSize
  241. {
  242. get { return hasShowPageSize; }
  243. set
  244. {
  245. SetProperty(ref hasShowPageSize, value);
  246. }
  247. }
  248. private bool canUndo;
  249. /// <summary>
  250. /// 是否可以进行Undo操作
  251. /// </summary>
  252. public bool CanUndo
  253. {
  254. get { return canUndo; }
  255. set
  256. {
  257. SetProperty(ref canUndo, value);
  258. if (viewContentViewModel != null)
  259. {
  260. viewContentViewModel.CanUndo = this.CanUndo;
  261. }
  262. }
  263. }
  264. private bool canRedo;
  265. /// <summary>
  266. /// 是否可以进行Redo操作
  267. /// </summary>
  268. public bool CanRedo
  269. {
  270. get { return canRedo; }
  271. set
  272. {
  273. SetProperty(ref canRedo, value);
  274. if (viewContentViewModel != null)
  275. {
  276. viewContentViewModel.CanRedo = this.CanRedo;
  277. }
  278. }
  279. }
  280. private bool canPaste = false;
  281. /// <summary>
  282. /// 是否可以粘贴
  283. /// </summary>
  284. public bool CanPaste
  285. {
  286. get { return canPaste; }
  287. set
  288. {
  289. SetProperty(ref canPaste, value);
  290. }
  291. }
  292. /// <summary>
  293. /// 页面缩放的范围
  294. /// </summary>
  295. private List<Size> ItemSizes = new List<Size>() {
  296. new Size(104,142),
  297. new Size(208, 294),
  298. new Size(312,441)
  299. };
  300. //选中的页面集合
  301. private List<int> selectedPageList = new List<int>();
  302. /// <summary>
  303. /// 是否是下拉框选项改变引起的选项变更事件
  304. /// </summary>
  305. private bool IsSelectFormSelf = false;
  306. #endregion
  307. #region 命令
  308. public DelegateCommand<object> SelectionChangedCommand { get; set; }
  309. /// <summary>
  310. /// 拦截键盘输入的事件
  311. /// </summary>
  312. public DelegateCommand<object> PreviewKeyDown { get; set; }
  313. /// <summary>
  314. /// 粘贴
  315. /// </summary>
  316. public DelegateCommand PasteCommand { get; set; }
  317. /// <summary>
  318. /// 复制
  319. /// </summary>
  320. public DelegateCommand CopyCommand { get; set; }
  321. /// <summary>
  322. /// 剪切
  323. /// </summary>
  324. public DelegateCommand CutCommand { get; set; }
  325. /// <summary>
  326. /// 替换文件
  327. /// </summary>
  328. public DelegateCommand ReplaceCommand { get; set; }
  329. /// <summary>
  330. /// 插入文件命令
  331. /// </summary>
  332. public DelegateCommand<object> InsertCommand { get; set; }
  333. /// <summary>
  334. /// 拆分文件
  335. /// </summary>
  336. public DelegateCommand SplitCommand { get; set; }
  337. /// <summary>
  338. /// 提取文件
  339. /// </summary>
  340. public DelegateCommand ExtractCommand { get; set; }
  341. /// <summary>
  342. /// 逆时针旋转
  343. /// </summary>
  344. public DelegateCommand LeftRotateCommand { get; set; }
  345. /// <summary>
  346. /// 顺时针旋转
  347. /// </summary>
  348. public DelegateCommand RightRotateCommand { get; set; }
  349. /// <summary>
  350. /// 删除
  351. /// </summary>
  352. public DelegateCommand DeleteCommand { get; set; }
  353. /// <summary>
  354. /// 倒序
  355. /// </summary>
  356. public DelegateCommand ReverseCommand { get; set; }
  357. /// <summary>
  358. /// 打印
  359. /// </summary>
  360. public DelegateCommand PrintCommand { get; set; }
  361. /// <summary>
  362. /// 放大
  363. /// </summary>
  364. public DelegateCommand ZoomInCommand { get; set; }
  365. /// <summary>
  366. /// 缩小
  367. /// </summary>
  368. public DelegateCommand ZoomOutCommand { get; set; }
  369. /// <summary>
  370. /// 显示页面大小
  371. /// </summary>
  372. public DelegateCommand ShowPageSizeCommand { get; set; }
  373. public DelegateCommand ClearSelectedCommand { get; set; }
  374. #endregion
  375. public PageEditContentViewModel(IDialogService dialogService, IEventAggregator eventAggregator)
  376. {
  377. //变量初始化
  378. dialogs = dialogService;
  379. eventor = eventAggregator;
  380. unicode = App.mainWindowViewModel.SelectedItem.Unicode;
  381. PageEditItems = new ObservableCollection<PageEditItem>();
  382. PageRangeItems = new ObservableCollection<string>();
  383. //绑定命令
  384. SelectionChangedCommand = new DelegateCommand<object>(SelectionChangedEvent);
  385. PreviewKeyDown = new DelegateCommand<object>(PreviewKeyDownEvent);
  386. SplitCommand = new DelegateCommand(SplitCommandEvent);
  387. InsertCommand = new DelegateCommand<object>(InsertCommandEvent);
  388. ReplaceCommand = new DelegateCommand(ReplaceCommandEvent, CanReplaceCommandExcute).ObservesProperty(() => IsMultiSelected);
  389. ExtractCommand = new DelegateCommand(ExtractCommandEvent, CanFileCommandExcute).ObservesProperty(() => ListSelectedIndex);
  390. DeleteCommand = new DelegateCommand(DeleteCommandEvent, CanFileCommandExcute).ObservesProperty(() => ListSelectedIndex);
  391. LeftRotateCommand = new DelegateCommand(LeftRotateCommandEvent, CanFileCommandExcute).ObservesProperty(() => ListSelectedIndex);
  392. RightRotateCommand = new DelegateCommand(RightRotateCommandEvent, CanFileCommandExcute).ObservesProperty(() => ListSelectedIndex);
  393. ReverseCommand = new DelegateCommand(ReverseCommandEvent, CanFileCommandExcute).ObservesProperty(() => ListSelectedIndex);
  394. ZoomInCommand = new DelegateCommand(ZoomInCommandEvent, CanZoomIn).ObservesProperty(() => ZoomIndex);
  395. ZoomOutCommand = new DelegateCommand(ZoomOutCommandEvent, CanZoomOut).ObservesProperty(() => ZoomIndex);
  396. ShowPageSizeCommand = new DelegateCommand(ShowPageSize);
  397. CopyCommand = new DelegateCommand(copy);
  398. PasteCommand = new DelegateCommand(paste, CanPasteExcute).ObservesProperty(() => CanPaste);
  399. CutCommand = new DelegateCommand(cut);
  400. PrintCommand = new DelegateCommand(print);
  401. ClearSelectedCommand = new DelegateCommand(clearSelected);
  402. //订阅页面刷新事件
  403. eventAggregator.GetEvent<PageEditRefreshEvent>().Subscribe(OnPageEditRefreshEvent, e => e.Unicode == unicode);
  404. CacheFilePath.Instance.PropertyChanged += Instance_PropertyChanged;
  405. RefreshPageRangeItem();
  406. InitString();
  407. }
  408. #region 事件
  409. private void Instance_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
  410. {
  411. if (e.PropertyName == "CopyDoc")
  412. {
  413. if (CacheFilePath.Instance.CopyDoc != null)
  414. {
  415. CanPaste = true;
  416. }
  417. }
  418. }
  419. /// <summary>
  420. /// 替换功能的逻辑
  421. /// </summary>
  422. private async void ReplaceCommandEvent()
  423. {
  424. OpenFileDialog dialog = new OpenFileDialog();
  425. dialog.Multiselect = false;
  426. dialog.Filter = PDF_Master.Properties.Resources.OpenDialogFilter;
  427. if ((bool)dialog.ShowDialog())
  428. {
  429. IsLoading = Visibility.Visible;
  430. await Task.Delay(200);
  431. int pageCount = PDFViewer.Document.PageCount;
  432. int insertIndex = listSelecedIndex;
  433. //从文件插入到指定位置
  434. var result = await InsertFromFile(listSelecedIndex + 1, dialog.FileName);
  435. if (result)
  436. {
  437. //插入成功后再删除原有页面
  438. DoRemoveSelectedPages(new List<int>() { listSelecedIndex });
  439. }
  440. ReloadAfterOption(true, true, Tuple.Create(insertIndex - 1, insertIndex + pageCount));
  441. IsLoading = Visibility.Collapsed;
  442. }
  443. }
  444. /// <summary>
  445. /// 拆分功能的逻辑
  446. /// </summary>
  447. private void SplitCommandEvent()
  448. {
  449. DialogParameters valuePairs = new DialogParameters();
  450. valuePairs.Add(ParameterNames.PDFViewer, PDFViewer);
  451. dialogs.ShowDialog(DialogNames.SplitDialog, valuePairs, e =>
  452. {
  453. if (e.Result == ButtonResult.OK && e.Parameters != null)
  454. {
  455. var model = e.Parameters.GetValue<HomePageSplitDialogModel>(ParameterNames.DataModel);
  456. DoSplitPages(model);
  457. }
  458. });
  459. }
  460. /// <summary>
  461. /// 提取功能的逻辑
  462. /// </summary>
  463. private void ExtractCommandEvent()
  464. {
  465. dialogs.ShowDialog(DialogNames.ExtractDialog, null, e =>
  466. {
  467. if (e.Result == ButtonResult.OK && e.Parameters != null)
  468. {
  469. var model = e.Parameters.GetValue<ExtractModel>(ParameterNames.DataModel);
  470. DoExtractPages(model.IsEveryPageToFile, model.IsDeleteAfterExtract);
  471. }
  472. });
  473. }
  474. /// <summary>
  475. /// 插入功能的逻辑
  476. /// </summary>
  477. private async void InsertCommandEvent(object type)
  478. {
  479. if ((string)type == null)
  480. {
  481. return;
  482. }
  483. //获取插入位置
  484. int insertIndex = 0;
  485. if (listSelecedIndex < 0)
  486. {
  487. insertIndex = 0;
  488. }
  489. else
  490. {
  491. insertIndex = listSelecedIndex + 1;
  492. if (isMultiSelected)
  493. {
  494. insertIndex = maxSelectedIndex + 1;
  495. }
  496. }
  497. IsLoading = Visibility.Visible;
  498. await Task.Delay(3);
  499. PageEditHistory history = new PageEditHistory();
  500. history.InsertIndex = insertIndex;
  501. if ((string)type == ParameterNames.InsertType_Blank)
  502. {
  503. history.Type = ActionType.InsertCustomPages;
  504. history.InsertFilePath = "";
  505. //插入空白页面
  506. bool result;
  507. if (insertIndex == 0)
  508. {
  509. result = PDFViewer.Document.InsertPage(insertIndex, PageEditItems[insertIndex].Size.Width, PageEditItems[insertIndex].Size.Height, null);
  510. history.PageSize = PageEditItems[insertIndex].Size;
  511. }
  512. else
  513. {
  514. result = PDFViewer.Document.InsertPage(insertIndex, PageEditItems[insertIndex - 1].Size.Width, PageEditItems[insertIndex - 1].Size.Height, null);
  515. history.PageSize = PageEditItems[insertIndex - 1].Size;
  516. }
  517. if (!result)
  518. {
  519. IsLoading = Visibility.Collapsed;
  520. ShowToast();
  521. return;
  522. }
  523. //UI层插入Item
  524. var item = GetNewPageEditItem(insertIndex);
  525. PageEditItems.Insert(insertIndex, item);
  526. ReloadAfterOption(true, true, Tuple.Create(insertIndex, insertIndex + 1));
  527. await Task.Delay(10);
  528. //选中插入的页面
  529. ListSelectedIndex = insertIndex;
  530. }
  531. else if ((string)type == ParameterNames.InsertType_File)
  532. {
  533. OpenFileDialog dialog = new OpenFileDialog();
  534. dialog.Multiselect = false;
  535. dialog.Filter = PDF_Master.Properties.Resources.OpenDialogFilter;
  536. if ((bool)dialog.ShowDialog())
  537. {
  538. //插入文件
  539. var result = await InsertFromFile(insertIndex, dialog.FileName);
  540. if (!result)
  541. {
  542. IsLoading = Visibility.Collapsed;
  543. ShowToast();
  544. return;
  545. }
  546. ReloadAfterOption(true, true, Tuple.Create(0, PDFViewer.Document.PageCount));
  547. }
  548. IsLoading = Visibility.Collapsed;
  549. //里面附带了Undo栈记录,需要提前返回,避免重复记录
  550. return;
  551. }
  552. else
  553. {
  554. DialogParameters keyValuePairs = new DialogParameters();
  555. Size size = new Size();
  556. size.Width = CommonHelper.GetUnitsFromPageSize(PDFViewer.Document.GetPageSize(listSelecedIndex).Width);
  557. size.Height = CommonHelper.GetUnitsFromPageSize(PDFViewer.Document.GetPageSize(listSelecedIndex).Height);
  558. keyValuePairs.Add("CurrentPageSize", size);
  559. //插入自定义页面
  560. dialogs.ShowDialog(DialogNames.InsertDialog, keyValuePairs, e =>
  561. {
  562. if (e.Result == ButtonResult.OK && e.Parameters != null)
  563. {
  564. var model = e.Parameters.GetValue<CustomInsertModel>(ParameterNames.DataModel);
  565. var result = InsertFromCustomPage(insertIndex, model.width, model.height, model.filepath);
  566. if (!result)
  567. {
  568. return;
  569. }
  570. history.Type = ActionType.InsertCustomPages;
  571. history.InsertFilePath = model.filepath;
  572. history.PageSize = new Size(model.width, model.height);
  573. }
  574. });
  575. }
  576. IsLoading = Visibility.Collapsed;
  577. //添加记录到Undo栈,清除Redo栈
  578. AddToUndoStack(history);
  579. }
  580. /// <summary>
  581. /// 删除选中页面
  582. /// </summary>
  583. private async void DeleteCommandEvent()
  584. {
  585. IsLoading = Visibility.Visible;
  586. await Task.Delay(3);
  587. DoRemoveSelectedPages();
  588. ReloadAfterOption(true, true, Tuple.Create(0, PDFViewer.Document.PageCount));
  589. IsLoading = Visibility.Collapsed;
  590. }
  591. /// <summary>
  592. /// 左旋转页面的逻辑
  593. /// </summary>
  594. private void LeftRotateCommandEvent()
  595. {
  596. RotateSelectedPages(false);
  597. }
  598. /// <summary>
  599. /// 右旋转页面的逻辑
  600. /// </summary>
  601. private void RightRotateCommandEvent()
  602. {
  603. RotateSelectedPages();
  604. }
  605. /// <summary>
  606. /// 页面倒序的逻辑
  607. /// </summary>
  608. private async void ReverseCommandEvent()
  609. {
  610. IsLoading = Visibility.Visible;
  611. await Task.Delay(3);
  612. List<int> pages = new List<int>();
  613. for (int i = 0; i < PageEditItems.Count; i++)
  614. {
  615. if (PageEditItems[i].Selected)
  616. {
  617. pages.Add(i);
  618. }
  619. }
  620. DoReverse(pages);
  621. IsLoading = Visibility.Collapsed;
  622. }
  623. /// <summary>
  624. /// 将指定页面结合进行倒序
  625. /// </summary>
  626. private async void DoReverse(List<int> pages, bool isFromUndoRedo = false)
  627. {
  628. if (pages.Count <= 1)
  629. {
  630. ShowToast("请至少选择两个图片进行倒序操作。");
  631. return;
  632. }
  633. pages.Sort();
  634. //记录原位置和目标位置 用于undo,redo
  635. Dictionary<int, int> sourceTarget = new Dictionary<int, int>();
  636. for (int i = 0; i < pages.Count; i++)
  637. {
  638. int preindex = pages[i];
  639. int laterIndex = pages[pages.Count - i - 1];//尾部的索引
  640. if (laterIndex <= preindex)//交换完成
  641. {
  642. //用于记录选中集合为奇数时,最中间Item的还原
  643. sourceTarget.Add(preindex, preindex);
  644. break;
  645. }
  646. var result = ExchangeItem(preindex, laterIndex);
  647. if (!result)
  648. {
  649. ShowToast();
  650. IsLoading = Visibility.Collapsed;
  651. return;
  652. }
  653. sourceTarget.Add(preindex, laterIndex);
  654. }
  655. await Task.Delay(20);
  656. //转换成页码数据集合,传递给UI,选中目标页面
  657. //因虚拟化加载的问题,通过Selected来控制Item选中效果会有问题
  658. List<int> pageRange = new List<int>();
  659. for (int i = 0; i < pages.Count; i++)
  660. {
  661. pageRange.Add(pages[i] + 1);
  662. }
  663. NotifyUIToRefresh(pageRange);
  664. ReloadAfterOption(true, true, null);
  665. if (!isFromUndoRedo)
  666. {
  667. PageEditHistory history = new PageEditHistory();
  668. history.Type = ActionType.Reverse;
  669. history.SourceTargetValue = sourceTarget;
  670. AddToUndoStack(history);
  671. }
  672. }
  673. /// <summary>
  674. /// 交换两个Item顺序
  675. /// </summary>
  676. /// <param name="preiIndex"></param>
  677. /// <param name="laterIndex"></param>
  678. /// <returns></returns>
  679. private bool ExchangeItem(int preiIndex, int laterIndex)
  680. {
  681. if (preiIndex == laterIndex)
  682. {
  683. return true;
  684. }
  685. var sourceitem = PageEditItems[preiIndex];
  686. var targetitem = PageEditItems[laterIndex];
  687. var result = PDFViewer.Document.ExchangePage(preiIndex, laterIndex);
  688. if (!result)
  689. {
  690. return false;
  691. }
  692. PageEditItems.Remove(sourceitem);
  693. PageEditItems.Remove(targetitem);
  694. PageEditItems.Insert(preiIndex, targetitem);
  695. PageEditItems.Insert(laterIndex, sourceitem);
  696. return true;
  697. }
  698. /// <summary>
  699. /// 是否可以执行文件操作命令 除插入、拆分外
  700. /// </summary>
  701. /// <returns></returns>
  702. private bool CanFileCommandExcute()
  703. {
  704. if (ListSelectedIndex < 0)
  705. {
  706. return false;
  707. }
  708. else
  709. {
  710. return true;
  711. }
  712. }
  713. /// <summary>
  714. /// 校验是否可以替换
  715. /// </summary>
  716. /// <returns></returns>
  717. private bool CanReplaceCommandExcute()
  718. {
  719. return !IsMultiSelected;
  720. }
  721. /// <summary>
  722. /// 放大页面
  723. /// </summary>
  724. private void ZoomInCommandEvent()
  725. {
  726. ZoomIndex++;
  727. ChangeItemSize(ItemSizes[ZoomIndex + 1]);
  728. NotifyUIToRefresh();
  729. }
  730. /// <summary>
  731. /// 缩小页面
  732. /// </summary>
  733. private void ZoomOutCommandEvent()
  734. {
  735. ZoomIndex--;
  736. ChangeItemSize(ItemSizes[ZoomIndex + 1]);
  737. NotifyUIToRefresh();
  738. }
  739. /// <summary>
  740. ///
  741. /// </summary>
  742. /// <param name="newsize"></param>
  743. public void ChangeItemSize(Size newsize)
  744. {
  745. for (int i = 0; i < PageEditItems.Count; i++)
  746. {
  747. PageEditItems[i].ItemSize = newsize;
  748. }
  749. //缩略图模式 调整item大小的时候,更新选中项
  750. NotifyUIToRefresh(new List<int>() { PDFViewer.CurrentIndex + 1 });
  751. }
  752. private bool CanZoomIn()
  753. {
  754. if (ZoomIndex >= 1)
  755. {
  756. return false;
  757. }
  758. else
  759. {
  760. return true;
  761. }
  762. }
  763. private bool CanZoomOut()
  764. {
  765. if (ZoomIndex <= -1)
  766. {
  767. return false;
  768. }
  769. else
  770. {
  771. return true;
  772. }
  773. }
  774. /// <summary>
  775. /// 响应UI发送刷新图片的事件
  776. /// </summary>
  777. /// <param name="e"></param>
  778. private void OnPageEditRefreshEvent(PageEditRefreshEventArgs e)
  779. {
  780. //UI发送事件过来通知刷新图片时
  781. //调整逻辑,前后预加载5页
  782. RefreshItemImage(e.PageRange.Item1 - 2, e.PageRange.Item2 + 2);
  783. }
  784. /// <summary>
  785. /// 选项改变事件
  786. /// 虚拟化的时候不会触发选中事件
  787. /// </summary>
  788. /// <param name="e"></param>
  789. private void SelectionChangedEvent(object e)
  790. {
  791. if (IsSelectFormSelf)
  792. {
  793. //避免频繁的触发该事件
  794. return;
  795. }
  796. var args = e as SelectionChangedEventArgs;
  797. //下下策 从UI控件获取所有选项的集合
  798. var listbox = args.OriginalSource as ListBox;
  799. if (TxtPageInputVisibility == Visibility.Visible && args != null)
  800. {
  801. selectedPageList = new List<int>();
  802. for (int i = 0; i < listbox.SelectedItems.Count; i++)
  803. {
  804. if (!selectedPageList.Contains((listbox.SelectedItems[i] as PageEditItem).PageNumber))
  805. {
  806. selectedPageList.Add((listbox.SelectedItems[i] as PageEditItem).PageNumber);
  807. }
  808. }
  809. ////根据选中的范围 适配全部页面范围、奇数页面范围等
  810. //if (pagelist.Count == PageEditItems.Count)
  811. //{
  812. // ComboxSelectIndex = 0;
  813. // return;
  814. //}
  815. //只选中单个页面是,listselectedIndex 更准确
  816. if (selectedPageList.Count == 1)
  817. {
  818. TbPageRange = (listSelecedIndex + 1).ToString();
  819. }
  820. else
  821. {
  822. string pageparm = CommonHelper.GetPageParmFromList(selectedPageList);
  823. TbPageRange = pageparm;
  824. }
  825. }
  826. //Ctrl+A时让所有item选中
  827. var isCtrlorShiftDown = ((Keyboard.IsKeyDown(Key.LeftCtrl) && Keyboard.IsKeyDown(Key.A)) || (Keyboard.IsKeyDown(Key.RightCtrl) && Keyboard.IsKeyDown(Key.A)));
  828. if (isCtrlorShiftDown)
  829. {
  830. for (int i = 0; i < PageEditItems.Count; i++)
  831. {
  832. PageEditItems[i].Selected = true;
  833. }
  834. }
  835. //判断是否有选中多项
  836. if (listbox.SelectedItems.Count > 1)
  837. {
  838. IsMultiSelected = true;
  839. maxSelectedIndex = listbox.Items.IndexOf(listbox.SelectedItems[listbox.SelectedItems.Count - 1]);
  840. }
  841. else
  842. {
  843. IsMultiSelected = false;
  844. }
  845. }
  846. /// <summary>
  847. /// 限制文本框输入内容
  848. /// </summary>
  849. /// <param name="e"></param>
  850. private void PreviewKeyDownEvent(object e)
  851. {
  852. var args = e as KeyEventArgs;
  853. if (args == null)
  854. {
  855. return;
  856. }
  857. //枚举 过滤所有不合理的输入
  858. if (args.Key != Key.Enter && args.Key != Key.Back && args.Key != Key.OemComma && args.Key != Key.OemMinus && args.Key != Key.Subtract && !((args.Key >= Key.D0 && args.Key <= Key.D9) || (args.Key >= Key.NumPad0 && args.Key <= Key.NumPad9)))
  859. {
  860. args.Handled = true;
  861. }
  862. if (args.Key == Key.Enter)
  863. {
  864. List<int> TargetPageIndexs = new List<int>();
  865. var result = CommonHelper.GetPagesInRange(ref TargetPageIndexs, (args.OriginalSource as TextBox).Text, PDFViewer.Document.PageCount, new char[] { ',', ',' }, new char[] { '-' });
  866. if (!result)
  867. {
  868. AlertsMessage alertsMessage = new AlertsMessage();
  869. alertsMessage.ShowDialog("", "请输入有效范围", "OK");
  870. return;
  871. }
  872. //选中输入的页面范围
  873. List<int> pageRange = new List<int>();
  874. for (int i = 0; i < PageEditItems.Count; i++)
  875. {
  876. if (TargetPageIndexs.Contains(PageEditItems[i].PageNumber - 1))
  877. {
  878. pageRange.Add(i + 1);
  879. }
  880. }
  881. NotifyUIToRefresh(pageRange);
  882. }
  883. }
  884. /// <summary>
  885. /// 失去焦点后选中页面
  886. /// </summary>
  887. /// <param name="obj"></param>
  888. public void lostfocus(object obj)
  889. {
  890. var args = obj as RoutedEventArgs;
  891. if (args == null || (args.OriginalSource as TextBox) == null)
  892. {
  893. return;
  894. }
  895. List<int> TargetPageIndexs = new List<int>();
  896. if (PageRangeItems.Contains((args.OriginalSource as TextBox).Text) && ComboxSelectIndex != 5)
  897. {
  898. //选中其他项,失去焦点时不报错
  899. return;
  900. }
  901. var result = CommonHelper.GetPagesInRange(ref TargetPageIndexs, (args.OriginalSource as TextBox).Text, PDFViewer.Document.PageCount, new char[] { ',', ',' }, new char[] { '-' });
  902. if (!result)
  903. {
  904. AlertsMessage alertsMessage = new AlertsMessage();
  905. alertsMessage.ShowDialog("", "请输入有效范围", "OK");
  906. return;
  907. }
  908. //选中输入的页面范围
  909. List<int> pageRange = new List<int>();
  910. for (int i = 0; i < PageEditItems.Count; i++)
  911. {
  912. if (TargetPageIndexs.Contains(PageEditItems[i].PageNumber - 1))
  913. {
  914. pageRange.Add(i + 1);
  915. }
  916. }
  917. NotifyUIToRefresh(pageRange);
  918. }
  919. #endregion
  920. #region 方法
  921. /// <summary>
  922. /// Esc退出多选
  923. /// </summary>
  924. private void clearSelected()
  925. {
  926. ListSelectedIndex = -1;
  927. }
  928. /// <summary>
  929. /// 调用打印机
  930. /// </summary>
  931. private void print()
  932. {
  933. PDFViewer.GoToPage(listSelecedIndex);
  934. DialogParameters printValue = new DialogParameters();
  935. printValue.Add(ParameterNames.PDFViewer, PDFViewer);
  936. printValue.Add(ParameterNames.FilePath, PDFViewer.Document.FileName);
  937. printValue.Add(ParameterNames.PrintCurrentPage, PDFViewer.CurrentIndex);
  938. printValue.Add(ParameterNames.PageList, selectedPageList);
  939. dialogs.ShowDialog(DialogNames.HomePagePrinterDialog, printValue, e => { });
  940. }
  941. /// <summary>
  942. /// 剪切
  943. /// </summary>
  944. private void cut()
  945. {
  946. CacheFilePath.Instance.CopyDoc = null;
  947. CacheFilePath.Instance.CopyDoc = CPDFDocument.CreateDocument();
  948. List<int> pages = new List<int>();
  949. for (int i = 0; i < PageEditItems.Count; i++)
  950. {
  951. if (PageEditItems[i].Selected)
  952. {
  953. pages.Add(i + 1);
  954. }
  955. }
  956. bool result = CacheFilePath.Instance.CopyDoc.ImportPages(PDFViewer.Document, String.Join(",", pages));
  957. if (!result)
  958. {
  959. ShowToast("复制失败");
  960. return;
  961. }
  962. DoRemoveSelectedPages();
  963. ReloadAfterOption(true, true, Tuple.Create(0, PDFViewer.Document.PageCount));
  964. }
  965. /// <summary>
  966. /// 复制
  967. /// </summary>
  968. private void copy()
  969. {
  970. //付费锁
  971. if (!App.IsLogin)
  972. {
  973. dialogs.ShowDialog(DialogNames.IAPCompareDialog);
  974. return;
  975. }
  976. VerifyPasswordResult verifyResult = SecurityHelper.VerifyPasswordForSelectedPermissions(PDFViewer.Document, EnumPermissionsSet.StatusAllowsCopying, dialogs);
  977. if (verifyResult.IsDiscryptied)
  978. {
  979. if (verifyResult.Password != null)
  980. {
  981. PDFViewer.Document.CheckOwnerPassword(verifyResult.Password);
  982. }
  983. CacheFilePath.Instance.CopyDoc = null;
  984. CacheFilePath.Instance.CopyDoc = CPDFDocument.CreateDocument();
  985. List<int> pages = new List<int>();
  986. for (int i = 0; i < PageEditItems.Count; i++)
  987. {
  988. if (PageEditItems[i].Selected)
  989. {
  990. pages.Add(i + 1);
  991. }
  992. }
  993. bool result = CacheFilePath.Instance.CopyDoc.ImportPages(PDFViewer.Document, String.Join(",", pages));
  994. if (!result)
  995. {
  996. ShowToast("复制失败");
  997. return;
  998. }
  999. }
  1000. else
  1001. {
  1002. ShowToast("复制失败");
  1003. return;
  1004. }
  1005. }
  1006. /// <summary>
  1007. /// 是否可以粘贴
  1008. /// </summary>
  1009. /// <returns></returns>
  1010. private bool CanPasteExcute()
  1011. {
  1012. return this.CanPaste;
  1013. }
  1014. /// <summary>
  1015. /// 粘贴
  1016. /// </summary>
  1017. private async void paste()
  1018. {
  1019. //付费锁
  1020. if (!App.IsLogin)
  1021. {
  1022. dialogs.ShowDialog(DialogNames.IAPCompareDialog);
  1023. return;
  1024. }
  1025. IsLoading = Visibility.Visible;
  1026. int insertindex = maxSelectedIndex > listSelecedIndex ? maxSelectedIndex : listSelecedIndex;
  1027. insertindex++;
  1028. int pagecount = CacheFilePath.Instance.CopyDoc.PageCount;
  1029. bool result = PDFViewer.Document.ImportPagesAtIndex(CacheFilePath.Instance.CopyDoc, "1-" + pagecount, insertindex);
  1030. if (!result)
  1031. {
  1032. IsLoading = Visibility.Collapsed;
  1033. ShowToast("粘贴失败");
  1034. return;
  1035. }
  1036. //UI层插入
  1037. for (int i = 0; i < pagecount; i++)
  1038. {
  1039. var item = GetNewPageEditItem(i);
  1040. PageEditItems.Insert(insertindex + i, item);
  1041. }
  1042. //加一点延时才能显示选中效果
  1043. await Task.Delay(200);
  1044. List<int> pageRange = new List<int>();
  1045. for (int i = 0; i < pagecount; i++)
  1046. {
  1047. pageRange.Add(insertindex + i + 1);
  1048. }
  1049. NotifyUIToRefresh(pageRange);
  1050. //刷新页码等
  1051. ReloadAfterOption(true, true, new Tuple<int, int>(0, PDFViewer.Document.PageCount));
  1052. NotifyUIToRefresh(pageRange);
  1053. IsLoading = Visibility.Collapsed;
  1054. }
  1055. /// <summary>
  1056. /// 页面编辑执行Undo操作的方法
  1057. /// </summary>
  1058. private async void Undo()
  1059. {
  1060. var history = UndoStack.Pop();
  1061. PageEditHistory redoHistory = new PageEditHistory();
  1062. switch (history.Type)
  1063. {
  1064. case ActionType.RightRotate:
  1065. var rightlist = history.SourceTargetValue.Keys.ToList<int>();
  1066. RotateSelectedPages(false, rightlist, true);
  1067. redoHistory.SourceTargetValue = history.SourceTargetValue;
  1068. redoHistory.Type = ActionType.LeftRotate;
  1069. break;
  1070. case ActionType.LeftRotate:
  1071. var leftlist = history.SourceTargetValue.Keys.ToList<int>();
  1072. RotateSelectedPages(true, leftlist, true);
  1073. redoHistory.SourceTargetValue = history.SourceTargetValue;
  1074. redoHistory.Type = ActionType.RightRotate;
  1075. break;
  1076. case ActionType.InsertFromFile:
  1077. List<int> pageList = new List<int>();
  1078. for (int i = 0; i < history.InsertPageCount; i++)
  1079. {
  1080. pageList.Add(history.InsertIndex + i);
  1081. }
  1082. DoRemoveSelectedPages(pageList, true);
  1083. redoHistory = history;
  1084. break;
  1085. case ActionType.InsertCustomPages:
  1086. DoRemoveSelectedPages(new List<int> { history.InsertIndex }, true);
  1087. redoHistory = history;
  1088. break;
  1089. case ActionType.DragSort:
  1090. //将字典倒序后,将每个Source的值恢复到Key的位置
  1091. var SourceTargets = history.SourceTargetValue;
  1092. var keys = SourceTargets.Keys.ToArray();
  1093. Array.Reverse(keys);
  1094. foreach (var key in keys)
  1095. {
  1096. MoveItemToIndex(SourceTargets[key], key);
  1097. }
  1098. //刷新页码等
  1099. ReloadAfterOption(true, true, new Tuple<int, int>(0, PDFViewer.Document.PageCount));
  1100. List<int> selectedPages = new List<int>();
  1101. //将索引集合转换成页码集合
  1102. foreach (var key in SourceTargets.Keys)
  1103. {
  1104. selectedPages.Add(key + 1);
  1105. }
  1106. //通知UI选中Item
  1107. NotifyUIToRefresh(selectedPages);
  1108. redoHistory = history;
  1109. break;
  1110. case ActionType.Reverse:
  1111. //将字典倒序后,将每个Source的值恢复到Key的位置
  1112. var SourceTarget = history.SourceTargetValue;
  1113. var pres = SourceTarget.Keys.ToArray();
  1114. foreach (var key in pres)
  1115. {
  1116. if (key != SourceTarget[key])
  1117. {
  1118. ExchangeItem(key, SourceTarget[key]);
  1119. }
  1120. }
  1121. await Task.Delay(20);
  1122. //刷新页码等
  1123. ReloadAfterOption(true, true, null);
  1124. List<int> Pages = new List<int>();
  1125. //将索引集合转换成页码集合
  1126. foreach (var key in SourceTarget.Keys)
  1127. {
  1128. Pages.Add(key + 1);
  1129. }
  1130. foreach (var key in SourceTarget.Values)
  1131. {
  1132. Pages.Add(key + 1);
  1133. }
  1134. //通知UI选中Item
  1135. NotifyUIToRefresh(Pages);
  1136. redoHistory = history;
  1137. break;
  1138. default:
  1139. break;
  1140. }
  1141. RedoStack.Push(redoHistory);
  1142. CanRedo = true;
  1143. //检查是否可以再进行Undo
  1144. if (UndoStack.Count <= 0)
  1145. {
  1146. this.CanUndo = false;
  1147. }
  1148. }
  1149. /// <summary>
  1150. /// 页面编辑执行Redo操作的方法
  1151. /// </summary>
  1152. private async void Redo()
  1153. {
  1154. var history = RedoStack.Pop();
  1155. PageEditHistory undoHistory = new PageEditHistory();
  1156. switch (history.Type)
  1157. {
  1158. case ActionType.RightRotate:
  1159. var rightlist = history.SourceTargetValue.Keys.ToList<int>();
  1160. RotateSelectedPages(false, rightlist, true);
  1161. undoHistory.SourceTargetValue = history.SourceTargetValue;
  1162. undoHistory.Type = ActionType.LeftRotate;
  1163. break;
  1164. case ActionType.LeftRotate:
  1165. var leftlist = history.SourceTargetValue.Keys.ToList<int>();
  1166. RotateSelectedPages(true, leftlist, true);
  1167. undoHistory.SourceTargetValue = history.SourceTargetValue;
  1168. undoHistory.Type = ActionType.RightRotate;
  1169. break;
  1170. case ActionType.InsertFromFile:
  1171. await InsertFromFile(history.InsertIndex, history.InsertFilePath, history.InsertFilePassWord, true);
  1172. ReloadAfterOption(true, true, Tuple.Create(history.InsertIndex - 1, history.InsertIndex + history.InsertPageCount));
  1173. undoHistory = history;
  1174. break;
  1175. case ActionType.InsertCustomPages:
  1176. InsertFromCustomPage(history.InsertIndex, history.PageSize.Width, history.PageSize.Height, history.InsertFilePath);
  1177. ListSelectedIndex = history.InsertIndex;
  1178. undoHistory = history;
  1179. break;
  1180. case ActionType.DragSort:
  1181. DragToSort(history.InsertIndex, history.SourceTargetValue.Keys.ToList<int>(), true);
  1182. undoHistory = history;
  1183. break;
  1184. case ActionType.Reverse:
  1185. var list = history.SourceTargetValue.Keys.ToList<int>().Union(history.SourceTargetValue.Values.ToList<int>()).ToList<int>();
  1186. DoReverse(list, true);
  1187. undoHistory = history;
  1188. break;
  1189. default:
  1190. break;
  1191. }
  1192. UndoStack.Push(undoHistory);
  1193. CanUndo = true;
  1194. if (RedoStack.Count <= 0)
  1195. {
  1196. this.CanRedo = false;
  1197. }
  1198. }
  1199. /// <summary>
  1200. /// 退出页面编辑面试,回到阅读页
  1201. /// </summary>
  1202. public void BackToPDFViewer(int PageIndex)
  1203. {
  1204. PDFViewer.GoToPage(PageIndex);
  1205. viewContentViewModel.ExitToolMode();
  1206. }
  1207. /// <summary>
  1208. /// 显示Toast提示
  1209. /// </summary>
  1210. private void ShowToast(string content = "")
  1211. {
  1212. if (!string.IsNullOrEmpty(content))
  1213. {
  1214. ToastText = content;
  1215. }
  1216. else
  1217. {
  1218. ToastText = "操作失败";
  1219. }
  1220. ShowTip = Visibility.Visible;
  1221. }
  1222. /// <summary>
  1223. /// 通知UI刷新页面范围
  1224. /// 或通过xaml来设置选中项
  1225. /// </summary>vb nmjvcx
  1226. private void NotifyUIToRefresh(List<int> pageRange = null)
  1227. {
  1228. if (pageRange == null || pageRange.Count <= 0)
  1229. {
  1230. //通知UI刷新页面范围
  1231. eventor.GetEvent<PageEditNotifyEvent>().Publish(new PageEditNotifyEventArgs(unicode));
  1232. }
  1233. else
  1234. {
  1235. //通知UI刷新页面范围
  1236. eventor.GetEvent<PageEditNotifyEvent>().Publish(new PageEditNotifyEventArgs(unicode, NotifyType.SelectItems, pageRange));
  1237. }
  1238. }
  1239. /// <summary>
  1240. /// 获取已选中的页面集合
  1241. /// </summary>
  1242. /// <returns></returns>
  1243. private List<int> getSelectedPage()
  1244. {
  1245. List<int> pages = new List<int>();
  1246. for (int i = 0; i < PageEditItems.Count; i++)
  1247. {
  1248. if (PageEditItems[i].Selected)
  1249. {
  1250. pages.Add(i);
  1251. }
  1252. }
  1253. return pages;
  1254. }
  1255. /// <summary>
  1256. /// 删除选中项的方法 不带Reload操作
  1257. /// 方便其他逻辑中调用
  1258. /// </summary>
  1259. private void DoRemoveSelectedPages(List<int> pageList = null, bool isFromUndoRedo = false)
  1260. {
  1261. //付费锁
  1262. if (!App.IsLogin)
  1263. {
  1264. dialogs.ShowDialog(DialogNames.IAPCompareDialog);
  1265. return;
  1266. }
  1267. List<int> indexList = new List<int>();
  1268. if (pageList == null || pageList.Count < 0)
  1269. {
  1270. for (int i = 0; i < PageEditItems.Count; i++)
  1271. {
  1272. if (PageEditItems[i].Selected)
  1273. {
  1274. indexList.Add(i);
  1275. }
  1276. }
  1277. }
  1278. else
  1279. {
  1280. indexList = pageList;
  1281. }
  1282. if (indexList.Count > 0 && indexList.Count == PDFViewer.Document.PageCount)
  1283. {
  1284. AlertsMessage alertsMessage = new AlertsMessage();
  1285. alertsMessage.ShowDialog("", "不能删除所有页面", "OK");
  1286. return;
  1287. }
  1288. var result = PDFViewer.Document.RemovePages(indexList.ToArray());
  1289. if (!result)
  1290. {
  1291. ShowToast();
  1292. return;
  1293. }
  1294. //文档层操作成功后再删除UI层
  1295. for (int i = indexList.Count - 1; i >= 0; i--)
  1296. {
  1297. PageEditItems.RemoveAt(indexList[i]);
  1298. }
  1299. if (!isFromUndoRedo)
  1300. {
  1301. //清除页面编辑Undo,Redo栈
  1302. UndoStack.Clear();
  1303. RedoStack.Clear();
  1304. this.CanUndo = false;
  1305. this.CanRedo = false;
  1306. }
  1307. }
  1308. /// <summary>
  1309. /// 提取选中页面的方法
  1310. /// </summary>
  1311. /// <param name="isEveryPageToFile">是否每页生成一个文件</param>
  1312. /// <param name="isDeleteAfterExtract">是否提取后删除页面</param>
  1313. private async void DoExtractPages(bool isEveryPageToFile, bool isDeleteAfterExtract)
  1314. {
  1315. System.Windows.Forms.FolderBrowserDialog dialog = new System.Windows.Forms.FolderBrowserDialog();
  1316. if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
  1317. {
  1318. if (string.IsNullOrEmpty(dialog.SelectedPath))
  1319. {
  1320. AlertsMessage alertsMessage = new AlertsMessage();
  1321. alertsMessage.ShowDialog("", "", "OK");//补充提示文案
  1322. return;
  1323. }
  1324. }
  1325. else
  1326. return;
  1327. string selectedfile = "";
  1328. IsLoading = Visibility.Visible;
  1329. await Task.Delay(3);
  1330. List<int> pagenums = new List<int>();
  1331. for (int i = 0; i < PageEditItems.Count; i++)
  1332. {
  1333. if (PageEditItems[i].Selected)
  1334. {
  1335. pagenums.Add(PageEditItems[i].PageNumber);
  1336. }
  1337. }
  1338. if (isEveryPageToFile)
  1339. {
  1340. //每页生成的单独的文件
  1341. for (int i = 0; i < pagenums.Count; i++)
  1342. {
  1343. string filename = PDFViewer.Document.FileName + " " + pagenums[i] + ".pdf";
  1344. string path = System.IO.Path.Combine(dialog.SelectedPath, filename);
  1345. path = CommonHelper.CreateFilePath(path);
  1346. selectedfile = path;
  1347. CPDFDocument savedoc = CPDFDocument.CreateDocument();
  1348. bool result = savedoc.ImportPages(PDFViewer.Document, pagenums[i].ToString());
  1349. if (!result)
  1350. {
  1351. savedoc.Release();
  1352. continue;
  1353. }
  1354. result = savedoc.WriteToFilePath(path);
  1355. if (!result)
  1356. {
  1357. savedoc.Release();
  1358. continue;
  1359. }
  1360. savedoc.Release();//释放内存
  1361. }
  1362. }
  1363. else//全部生成一个文件
  1364. {
  1365. string filename = PDFViewer.Document.FileName + " " + CommonHelper.GetPageParmFromList(pagenums) + ".pdf";
  1366. string path = System.IO.Path.Combine(dialog.SelectedPath, filename);
  1367. path = CommonHelper.CreateFilePath(path);
  1368. selectedfile = path;
  1369. CPDFDocument savedoc = CPDFDocument.CreateDocument();
  1370. string range = String.Join(",", pagenums);
  1371. bool result = savedoc.ImportPages(PDFViewer.Document, range);
  1372. if (!result)
  1373. {
  1374. ShowToast();
  1375. IsLoading = Visibility.Collapsed;
  1376. return;
  1377. }
  1378. result = savedoc.WriteToFilePath(path);
  1379. if (!result)
  1380. {
  1381. ShowToast();
  1382. }
  1383. savedoc.Release();//释放内存
  1384. }
  1385. if (isDeleteAfterExtract)
  1386. {
  1387. DoRemoveSelectedPages();
  1388. ReloadAfterOption(true, true, Tuple.Create(0, PDFViewer.Document.PageCount));
  1389. }
  1390. CommonHelper.ShowFileBrowser(selectedfile);
  1391. IsLoading = Visibility.Collapsed;
  1392. }
  1393. private void DoSplitPages(HomePageSplitDialogModel model)
  1394. {
  1395. try
  1396. {
  1397. var pdfViewer = PDFViewer;
  1398. System.Windows.Forms.FolderBrowserDialog dialog = new System.Windows.Forms.FolderBrowserDialog();
  1399. //dialog.Description = App.MainPageLoader.GetString("Main_OpenFolderNoteWarning"); ;
  1400. if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
  1401. {
  1402. if (string.IsNullOrEmpty(dialog.SelectedPath))
  1403. {
  1404. return;
  1405. }
  1406. }
  1407. else
  1408. return;
  1409. var data = model;
  1410. int PageCount = pdfViewer.Document.PageCount;
  1411. string selectedfile = "";
  1412. if (data.Mode == HomePageSplitDialogModel.SplitMode.AveragePages)
  1413. {
  1414. int perPages = Convert.ToInt32(data.GetModeCount);
  1415. int SplitCount = (int)Math.Ceiling((double)PageCount / (double)perPages);
  1416. //TODO:命名规则是否要调整
  1417. selectedfile = data.FileName + " " + "1.pdf";
  1418. for (int i = 0; i < SplitCount; i++)
  1419. {
  1420. int startNum = i * perPages + 1;
  1421. int endNum = Math.Min(PageCount, (i + 1) * perPages);
  1422. string range = startNum.ToString() + "-" + endNum.ToString();
  1423. CPDFDocument savedoc = CPDFDocument.CreateDocument();
  1424. bool result = savedoc.ImportPages(pdfViewer.Document, range);
  1425. if (!result)
  1426. {
  1427. savedoc.Release();
  1428. continue;
  1429. }
  1430. string filename = data.FileName + " " + (i + 1) + ".pdf";
  1431. string path = System.IO.Path.Combine(dialog.SelectedPath, filename);
  1432. path = CommonHelper.CreateFilePath(path);
  1433. result = savedoc.WriteToFilePath(path);
  1434. if (!result)
  1435. {
  1436. savedoc.Release();
  1437. continue;
  1438. }
  1439. savedoc.Release();
  1440. selectedfile = path;
  1441. }
  1442. }
  1443. else if (data.Mode == HomePageSplitDialogModel.SplitMode.AverageFiles)
  1444. {
  1445. int docCount = Convert.ToInt32(data.GetModeCount);
  1446. int avePages = (int)Math.Floor((double)PageCount / (double)docCount);
  1447. int remain = PageCount % docCount;
  1448. int startNum = 1;
  1449. //TODO:命名规则是否要调整
  1450. selectedfile = data.FileName + " " + "1.pdf";
  1451. for (int i = 0; i < docCount; i++)
  1452. {
  1453. int endNum = startNum + (avePages - 1);
  1454. if (i < remain) endNum++;
  1455. endNum = Math.Min(endNum, PageCount);
  1456. string range = startNum + "-" + endNum;
  1457. startNum = endNum + 1;
  1458. string fileName = data.FileName + " " + (i + 1) + ".pdf";
  1459. string path = System.IO.Path.Combine(dialog.SelectedPath, fileName);
  1460. path = CommonHelper.CreateFilePath(path);
  1461. CPDFDocument savedoc = CPDFDocument.CreateDocument();
  1462. bool result = savedoc.ImportPages(pdfViewer.Document, range);
  1463. if (!result)
  1464. {
  1465. savedoc.Release();
  1466. continue;
  1467. }
  1468. result = savedoc.WriteToFilePath(path);
  1469. if (!result)
  1470. {
  1471. savedoc.Release();
  1472. continue;
  1473. }
  1474. savedoc.Release();
  1475. selectedfile = path;
  1476. }
  1477. }
  1478. else//自定义页码范围
  1479. {
  1480. string pageRange = "";
  1481. if (data.PageMode == HomePageSplitDialogModel.PageRangeMode.OddPage)
  1482. {
  1483. int[] page = new int[(PageCount + 1) / 2];
  1484. for (int i = 0; i < page.Length; i++)
  1485. {
  1486. page[i] = i * 2 + 1;
  1487. }
  1488. pageRange = string.Join(",", page);
  1489. }
  1490. else if (data.PageMode == HomePageSplitDialogModel.PageRangeMode.EvenPage)
  1491. {
  1492. int[] page = new int[PageCount / 2];
  1493. for (int i = 0; i < page.Length; i++)
  1494. {
  1495. page[i] = i * 2 + 2;
  1496. }
  1497. pageRange = string.Join(",", page);
  1498. }
  1499. List<int> pageList1 = new List<int>();
  1500. //如果是自定义输入页面范围的话,直接解析
  1501. CommonHelper.GetPagesInRange(ref pageList1, pageRange, PageCount, new char[] { ',' }, new char[] { '-' });
  1502. //part1
  1503. selectedfile = "";
  1504. CPDFDocument saveDoc1 = CPDFDocument.CreateDocument();
  1505. string filepath = data.FileName + " " + "1.pdf";
  1506. string path1 = Path.Combine(dialog.SelectedPath, filepath);
  1507. path1 = CommonHelper.CreateFilePath(path1);
  1508. bool result = saveDoc1.ImportPages(pdfViewer.Document, pageRange);
  1509. if (!result)
  1510. {
  1511. saveDoc1.Release();
  1512. ShowToast();
  1513. return;
  1514. }
  1515. result = saveDoc1.WriteToFilePath(path1);
  1516. if (!result)
  1517. {
  1518. saveDoc1.Release();
  1519. ShowToast();
  1520. return;
  1521. }
  1522. saveDoc1.Release();
  1523. //Part2
  1524. List<int> pageList2 = new List<int>();
  1525. for (int i = 1; i <= pdfViewer.Document.PageCount; i++)
  1526. {
  1527. if (!pageList1.Contains(i - 1))//pagelist1 存放的是index
  1528. pageList2.Add(i);
  1529. }
  1530. string pageRange2 = string.Join(",", pageList2);
  1531. CPDFDocument saveDoc2 = CPDFDocument.CreateDocument();
  1532. string filepath2 = data.FileName + " " + "2.pdf";
  1533. string path2 = Path.Combine(dialog.SelectedPath, filepath2);
  1534. path2 = CommonHelper.CreateFilePath(path2);
  1535. result = saveDoc2.ImportPages(pdfViewer.Document, pageRange2);
  1536. if (!result)
  1537. {
  1538. saveDoc2.Release();
  1539. ShowToast();
  1540. return;
  1541. }
  1542. result = saveDoc2.WriteToFilePath(path2);
  1543. if (!result)
  1544. {
  1545. saveDoc2.Release();
  1546. ShowToast();
  1547. return;
  1548. }
  1549. selectedfile = path1;
  1550. saveDoc2.Release();
  1551. }
  1552. //显示文件夹,并选中一个文件
  1553. Process.Start("explorer", "/select,\"" + selectedfile + "\"");
  1554. }
  1555. catch (Exception ex)
  1556. {
  1557. }
  1558. }
  1559. /// <summary>
  1560. /// 将文件插入到指定位置
  1561. /// </summary>
  1562. /// <param name="insertIndex"></param>
  1563. public async Task<bool> InsertFromFile(int insertIndex, string filePath, string oldPassWord = null, bool isFromUndoRedo = false)
  1564. {
  1565. CPDFDocument doc = CPDFDocument.InitWithFilePath(filePath);
  1566. if (doc == null)
  1567. {
  1568. ShowToast();
  1569. return false;
  1570. }
  1571. string password = "";
  1572. if (doc.IsLocked)
  1573. {
  1574. if (!string.IsNullOrEmpty(oldPassWord))
  1575. {
  1576. var result = doc.UnlockWithPassword(oldPassWord);
  1577. if (result)
  1578. {
  1579. password = oldPassWord;
  1580. }
  1581. }
  1582. //没有传入密码,或者用传入密码解密失败是,需要弹出界面弹窗
  1583. if (doc.IsLocked)
  1584. {
  1585. DialogParameters value = new DialogParameters();
  1586. value.Add(ParameterNames.PDFDocument, doc);
  1587. bool result = true;
  1588. dialogs.ShowDialog(DialogNames.VerifyPassWordDialog, value, e =>
  1589. {
  1590. if (e.Result != ButtonResult.OK)
  1591. {
  1592. result = false;
  1593. }
  1594. password = e.Parameters.GetValue<string>(ParameterNames.PassWord);
  1595. });
  1596. if (!result)
  1597. {
  1598. return false;
  1599. }
  1600. }
  1601. }
  1602. int pageCount = doc.PageCount;
  1603. //插入整个新文档
  1604. //文档层插入
  1605. var insertresult = PDFViewer.Document.ImportPagesAtIndex(doc, "1-" + pageCount, insertIndex);
  1606. if (!insertresult)
  1607. {
  1608. ShowToast();
  1609. return false;
  1610. }
  1611. //插入成功后释放临时Document对象
  1612. doc.Release();
  1613. //UI层插入
  1614. for (int i = 0; i < pageCount; i++)
  1615. {
  1616. var item = GetNewPageEditItem(i);
  1617. PageEditItems.Insert(insertIndex + i, item);
  1618. }
  1619. //加一点延时才能显示选中效果
  1620. await Task.Delay(200);
  1621. List<int> pageRange = new List<int>();
  1622. for (int i = 0; i < pageCount; i++)
  1623. {
  1624. pageRange.Add(insertIndex + i + 1);
  1625. }
  1626. NotifyUIToRefresh(pageRange);
  1627. //如果是undo redo里调用本方法,则不需要添加到Undo栈
  1628. if (!isFromUndoRedo)
  1629. {
  1630. //添加记录到Undo栈,清空Redo栈
  1631. PageEditHistory history = new PageEditHistory();
  1632. history.Type = ActionType.InsertFromFile;
  1633. history.InsertIndex = insertIndex;
  1634. history.InsertFilePath = filePath;
  1635. history.InsertFilePassWord = password;
  1636. history.InsertPageCount = pageCount;
  1637. AddToUndoStack(history);
  1638. }
  1639. return true;
  1640. }
  1641. /// <summary>
  1642. /// 添加记录到Undo栈
  1643. /// </summary>
  1644. /// <param name="history"></param>
  1645. private void AddToUndoStack(PageEditHistory history)
  1646. {
  1647. UndoStack.Push(history);
  1648. CanUndo = true;
  1649. RedoStack.Clear();
  1650. CanRedo = false;
  1651. }
  1652. /// <summary>
  1653. /// 插入自定义页面
  1654. /// </summary>
  1655. /// <param name="insertIndex"></param>
  1656. /// <param name="width"></param>
  1657. /// <param name="height"></param>
  1658. /// <param name="filePath"></param>
  1659. /// <returns></returns>
  1660. private bool InsertFromCustomPage(int insertIndex, double width, double height, string filePath)
  1661. {
  1662. try
  1663. {
  1664. bool result = false;
  1665. //文档层插入
  1666. if (!string.IsNullOrEmpty(filePath))
  1667. {
  1668. BitmapFrame frame = BitmapFrame.Create(new Uri(filePath));
  1669. byte[] imageData = new byte[frame.PixelWidth * frame.PixelHeight * 4];
  1670. frame.CopyPixels(imageData, frame.PixelWidth * 4, 0);
  1671. result = PDFViewer.Document.InsertPage(insertIndex, frame.Width, frame.Height, imageData, CPDFDocumentImageMode.CPDFDocumentImageModeScaleToFill);
  1672. }
  1673. else
  1674. {
  1675. result = PDFViewer.Document.InsertPage(insertIndex, width, height, null);
  1676. }
  1677. if (!result)
  1678. {
  1679. ShowToast();
  1680. return false;
  1681. }
  1682. PageEditItem item = new PageEditItem();
  1683. item.Size = PDFViewer.Document.GetPageSize(insertIndex);
  1684. PageEditItems.Insert(insertIndex, item);
  1685. ReloadAfterOption(true, true, Tuple.Create(insertIndex - 1, insertIndex + 1));
  1686. return true;
  1687. }
  1688. catch
  1689. { return false; }
  1690. }
  1691. /// <summary>
  1692. /// 根据索引创建新的Item
  1693. /// </summary>
  1694. /// <param name="index"></param>
  1695. /// <returns></returns>
  1696. private PageEditItem GetNewPageEditItem(int index)
  1697. {
  1698. PageEditItem item = new PageEditItem();
  1699. if (PDFViewer.Document.PageAtIndex(index).Rotation % 2 != 0)
  1700. {
  1701. ///标记为横向页面
  1702. item.isVertical = false;
  1703. }
  1704. item.PageNumber = index + 1;
  1705. var pagesize = PDFViewer.Document.GetPageSize(index);
  1706. item.Size = pagesize;
  1707. //double width = CommonHelper.GetUnitsFromPageSize(pagesize.Width);
  1708. //double height = CommonHelper.GetUnitsFromPageSize(pagesize.Height);
  1709. //item.PageSize = $"{width.ToString("F0")}mm*{height.ToString("F0")} mm";
  1710. return item;
  1711. }
  1712. /// <summary>
  1713. /// 进行文件操作后刷新PDFView
  1714. /// 清除undo 栈
  1715. /// 重加载Document
  1716. /// 设置保存状态
  1717. /// </summary>
  1718. /// <param name="needRefreshPageNum">是否需要刷新页码</param>
  1719. /// <param name="needClearUndoHistory">是否需要清空注释Undo栈</param>
  1720. /// <param name="pageRange">需要刷新的页面范围图片</param>
  1721. public void ReloadAfterOption(bool needRefreshPageNum = false, bool needClearUndoHistory = true, Tuple<int, int> pageRange = null)
  1722. {
  1723. if (needRefreshPageNum)
  1724. {
  1725. RefreshPageNum();
  1726. }
  1727. if (needClearUndoHistory)
  1728. {
  1729. PDFViewer.UndoManager.ClearHistory();
  1730. }
  1731. if (pageRange != null)
  1732. {
  1733. if (pageRange.Item2 - pageRange.Item1 > 30)
  1734. {
  1735. //范围较大时,通知UI获取更准确的刷新范围
  1736. NotifyUIToRefresh();
  1737. }
  1738. else
  1739. {
  1740. RefreshItemImage(pageRange.Item1, pageRange.Item2);
  1741. }
  1742. }
  1743. PDFViewer.UndoManager.CanSave = true;
  1744. PDFViewer.ReloadDocument();
  1745. }
  1746. /// <summary>
  1747. /// 旋转所有选中页面
  1748. /// </summary>
  1749. /// <param name="rightRotate"></param>
  1750. private async void RotateSelectedPages(bool rightRotate = true, List<int> pageitems = null, bool isFromUndoRedo = false)
  1751. {
  1752. //付费锁
  1753. if (!App.IsLogin)
  1754. {
  1755. dialogs.ShowDialog(DialogNames.IAPCompareDialog);
  1756. return;
  1757. }
  1758. IsLoading = Visibility.Visible;
  1759. await Task.Delay(2);
  1760. Dictionary<int, int> items = new Dictionary<int, int>();
  1761. if (pageitems == null)
  1762. {
  1763. //旋转选中页面
  1764. for (int i = 0; i < PageEditItems.Count; i++)
  1765. {
  1766. if (PageEditItems[i].Selected)
  1767. {
  1768. //逆时针旋转传 - 1 顺时针旋转传1
  1769. PDFViewer.Document.RotatePage(i, rightRotate ? 1 : -1);
  1770. PDFViewer.Document.ReleasePages(i);
  1771. items.Add(i, i);
  1772. PageEditItems[i].Size = PDFViewer.Document.GetPageSize(i);
  1773. //重新拿图
  1774. PageEditItems[i].IsGetImage = false;
  1775. }
  1776. }
  1777. }
  1778. else
  1779. {
  1780. //旋转对应Items集合
  1781. for (int i = 0; i < pageitems.Count; i++)
  1782. {
  1783. PDFViewer.Document.RotatePage(pageitems[i], rightRotate ? 1 : -1);
  1784. PDFViewer.Document.ReleasePages(pageitems[i]);
  1785. items.Add(pageitems[i], pageitems[i]);
  1786. //重新拿图
  1787. PageEditItems[pageitems[i]].IsGetImage = false;
  1788. PageEditItems[i].Size = PDFViewer.Document.GetPageSize(i);
  1789. }
  1790. }
  1791. //旋转页面后取消选中
  1792. PDFViewer.ClearSelectPDFEdit(true);
  1793. //如果是undo,Redo里调用的方法,则不记录到栈里
  1794. if (!isFromUndoRedo)
  1795. {
  1796. //记录进Undo栈
  1797. PageEditHistory history = new PageEditHistory();
  1798. history.Type = rightRotate ? ActionType.RightRotate : ActionType.LeftRotate;
  1799. history.SourceTargetValue = items;
  1800. AddToUndoStack(history);
  1801. }
  1802. ReloadAfterOption(false, true, Tuple.Create(0, PageEditItems.Count));
  1803. IsLoading = Visibility.Collapsed;
  1804. }
  1805. /// <summary>
  1806. /// 刷新页码
  1807. /// </summary>
  1808. private void RefreshPageNum()
  1809. {
  1810. for (int i = 0; i < PageEditItems.Count; i++)
  1811. {
  1812. PageEditItems[i].PageNumber = i + 1;
  1813. PageEditItems[i].ShowPageSize = HasShowPageSize == Visibility.Visible ? true : false;
  1814. }
  1815. }
  1816. /// <summary>
  1817. /// 刷新页面范围下拉框
  1818. /// </summary>
  1819. private void RefreshPageRangeItem()
  1820. {
  1821. PageRangeItems.Clear();
  1822. PageRangeItems.Add("所有页面");
  1823. PageRangeItems.Add("奇数页");
  1824. PageRangeItems.Add("偶数页");
  1825. PageRangeItems.Add("横向页面");
  1826. PageRangeItems.Add("纵向页面");
  1827. PageRangeItems.Add("自定义");
  1828. }
  1829. /// <summary>
  1830. /// 选中目标页面范围的页面
  1831. /// </summary>
  1832. /// <param name="index">页面范围选中项索引</param>
  1833. private async void SuitPageRange(int index)
  1834. {
  1835. List<int> pageRange = new List<int>();
  1836. switch (index)
  1837. {
  1838. case 0:
  1839. for (int i = 0; i < PageEditItems.Count; i++)
  1840. {
  1841. pageRange.Add(i + 1);
  1842. }
  1843. break;
  1844. case 1:
  1845. //奇数页
  1846. for (int i = 0; i < PageEditItems.Count; i++)
  1847. {
  1848. if (i % 2 == 0)
  1849. {
  1850. pageRange.Add(i + 1);
  1851. }
  1852. }
  1853. break;
  1854. case 2:
  1855. //偶数页
  1856. for (int i = 0; i < PageEditItems.Count; i++)
  1857. {
  1858. if (i % 2 != 0)
  1859. {
  1860. pageRange.Add(i + 1);
  1861. }
  1862. }
  1863. break;
  1864. case 3://横向页面
  1865. ListSelectedIndex = -1;
  1866. for (int i = 0; i < PageEditItems.Count; i++)
  1867. {
  1868. if (!PageEditItems[i].isVertical)
  1869. {
  1870. pageRange.Add(i + 1);
  1871. }
  1872. }
  1873. break;
  1874. case 4://纵向页面
  1875. for (int i = 0; i < PageEditItems.Count; i++)
  1876. {
  1877. if (PageEditItems[i].isVertical)
  1878. {
  1879. pageRange.Add(i + 1);
  1880. }
  1881. }
  1882. break;
  1883. case 5://自定义
  1884. TxtPageInputVisibility = Visibility.Visible;
  1885. await Task.Delay(30);
  1886. TbPageRange = "";
  1887. break;
  1888. default:
  1889. break;
  1890. }
  1891. if (pageRange.Count > 0)
  1892. {
  1893. //避免在下面的过程中频繁触发SelectionChanged事件
  1894. IsSelectFormSelf = true;
  1895. NotifyUIToRefresh(pageRange);
  1896. IsSelectFormSelf = false;
  1897. }
  1898. else
  1899. {
  1900. //没有符合条件时 清空选中项
  1901. ListSelectedIndex = -1;
  1902. }
  1903. }
  1904. /// <summary>
  1905. /// 是否显示页面尺寸
  1906. /// </summary>
  1907. /// <param name="show">是或否</param>
  1908. private void ShowPageSize()
  1909. {
  1910. bool show = true;
  1911. if (HasShowPageSize == Visibility.Visible)
  1912. {
  1913. show = false;
  1914. HasShowPageSize = Visibility.Collapsed;
  1915. }
  1916. else
  1917. {
  1918. show = true;
  1919. HasShowPageSize = Visibility.Visible;
  1920. }
  1921. for (int i = 0; i < PageEditItems.Count; i++)
  1922. {
  1923. PageEditItems[i].ShowPageSize = show;
  1924. }
  1925. }
  1926. /// <summary>
  1927. /// 从PDFView获取所有Items集合
  1928. /// </summary>
  1929. private void GetSourceItems(bool isFirstLoad)
  1930. {
  1931. if (isFirstLoad || IsBOTAThumb == Visibility.Visible)
  1932. {
  1933. PageEditItems.Clear();
  1934. for (int i = 0; i < PDFViewer.Document.PageCount; i++)
  1935. {
  1936. var item = GetNewPageEditItem(i);
  1937. PageEditItems.Add(item);
  1938. }
  1939. }
  1940. //else
  1941. //{
  1942. // //后续进来仅刷新图片即可
  1943. // for (int i = 0; i < PageEditItems.Count; i++)
  1944. // {
  1945. // PageEditItems[i].IsGetImage = false;
  1946. // }
  1947. //}
  1948. }
  1949. /// <summary>
  1950. /// 刷新书签列表
  1951. /// </summary>
  1952. public void RefreshBookMarkList()
  1953. {
  1954. if (PDFViewer != null)
  1955. {
  1956. var booklist = PDFViewer.Document.GetBookmarkList();
  1957. if (booklist == null)
  1958. {
  1959. return;
  1960. }
  1961. //获取所有书签的Index集合
  1962. List<int> marks = new List<int>();
  1963. for (int i = 0; i < booklist.Count; i++)
  1964. {
  1965. marks.Add(booklist[i].PageIndex);
  1966. }
  1967. //不能只遍历marks集合,考虑书签集合元素删除的情况
  1968. for (int k = 0; k < PageEditItems.Count; k++)
  1969. {
  1970. if (marks.Contains(k))
  1971. PageEditItems[k].HaveBookMark = true;
  1972. else
  1973. PageEditItems[k].HaveBookMark = false;
  1974. }
  1975. }
  1976. }
  1977. /// <summary>
  1978. /// 刷新指定范围的图片
  1979. /// </summary>
  1980. /// <param name="startIndex"></param>
  1981. /// <param name="endIndex"></param>
  1982. private async void RefreshItemImage(int startIndex, int endIndex)
  1983. {
  1984. for (int i = startIndex; i <= endIndex; i++)
  1985. {
  1986. if (i <= PageEditItems.Count - 1 && i >= 0 && PageEditItems.Count > 0)
  1987. {
  1988. //宽高为样式中图片控件宽高
  1989. if (PageEditItems[i].isVertical)
  1990. {
  1991. //等比例缩放
  1992. if (PageEditItems[i].Size.Height > 300)
  1993. {
  1994. await PDFViewer.GetThumbnail(i, (int)(PageEditItems[i].Size.Width / (PageEditItems[i].Size.Height / 300)), 300);
  1995. }
  1996. else
  1997. {
  1998. await PDFViewer.GetThumbnail(i, (int)PageEditItems[i].Size.Width, (int)PageEditItems[i].Size.Height);
  1999. }
  2000. }
  2001. else
  2002. {
  2003. if (PageEditItems[i].Size.Width > 300)
  2004. {
  2005. await PDFViewer.GetThumbnail(i, 300, (int)(PageEditItems[i].Size.Height / (PageEditItems[i].Size.Width / 300)));
  2006. }
  2007. else
  2008. {
  2009. //获取横图
  2010. await PDFViewer.GetThumbnail(i, (int)PageEditItems[i].Size.Width, (int)PageEditItems[i].Size.Height);
  2011. }
  2012. }
  2013. }
  2014. }
  2015. }
  2016. /// <summary>
  2017. /// 拖拽排序功能
  2018. /// </summary>
  2019. /// <param name="targetIndex"></param>
  2020. /// <param name="pageIndexs"></param>
  2021. public void DragToSort(int targetIndex, List<int> pageIndexs, bool IsFromUndoRedo = false)
  2022. {
  2023. //拖拽排序后需要重新选中项的集合
  2024. List<int> selectedPages = new List<int>();
  2025. //记录原位置和目标位置的字典,用于Undo,Redo恢复
  2026. Dictionary<int, int> SourceTargetValue = new Dictionary<int, int>();
  2027. bool result = false;
  2028. //排序前,先对所有页码排序
  2029. pageIndexs.Sort();
  2030. //要考虑每一次交换都会导致局部页码发生改变
  2031. //每次整体往后移动时,先移动大页码;整体往前移动时,先移动小页码;往中间移动时,再按上述两种情况分别移动
  2032. if (targetIndex <= pageIndexs[0])
  2033. {
  2034. for (int i = 0; i < pageIndexs.Count; i++)
  2035. {
  2036. // list.Add(PageEditListBox.Items[pageIndexs[i]] as ListBoxItem);
  2037. //sourceindex.Add(pageIndexs[i]);
  2038. result = MoveItemToIndex(pageIndexs[i], targetIndex + i);
  2039. if (!result)
  2040. {
  2041. return;
  2042. }
  2043. SourceTargetValue.Add(pageIndexs[i], targetIndex + i);
  2044. selectedPages.Add(targetIndex + i + 1);
  2045. }
  2046. }
  2047. else if (targetIndex > pageIndexs[pageIndexs.Count - 1])
  2048. {
  2049. //目标位置在所有选中内容右边 整体后移
  2050. for (int i = 0; i < pageIndexs.Count; i++)
  2051. {
  2052. result = MoveItemToIndex(pageIndexs[pageIndexs.Count - 1 - i], targetIndex - 1 - i);
  2053. if (!result)
  2054. {
  2055. return;
  2056. }
  2057. SourceTargetValue.Add(pageIndexs[pageIndexs.Count - 1 - i], targetIndex - 1 - i);
  2058. selectedPages.Add(targetIndex - i);
  2059. }
  2060. }
  2061. else//目标位置在所有选中项中间
  2062. {
  2063. int i, j, k;
  2064. //找出PageEditListBox.Items中页码等于destpage的下标
  2065. for (k = 0; k < pageIndexs.Count - 1; k++)
  2066. {
  2067. //这里要算入K---即前面部分的页面个数
  2068. if (pageIndexs[k] < targetIndex && pageIndexs[k + 1] >= targetIndex)
  2069. {
  2070. break;
  2071. }
  2072. }
  2073. //局部往后移动
  2074. for (i = 0; i <= k; i++)
  2075. {
  2076. result = MoveItemToIndex(pageIndexs[k - i], targetIndex - 1 - i);
  2077. if (!result)
  2078. {
  2079. return;
  2080. }
  2081. SourceTargetValue.Add(pageIndexs[k - i], targetIndex - 1 - i);
  2082. selectedPages.Add(targetIndex - i);
  2083. }
  2084. int newIndex = targetIndex;
  2085. //局部往前移动
  2086. for (j = i; j < pageIndexs.Count; j++)
  2087. {
  2088. result = MoveItemToIndex(pageIndexs[j], newIndex);
  2089. if (!result)
  2090. {
  2091. return;
  2092. }
  2093. SourceTargetValue.Add(pageIndexs[j], newIndex);
  2094. selectedPages.Add(newIndex + 1);
  2095. newIndex++;
  2096. }
  2097. }
  2098. //通知UI选中Items
  2099. NotifyUIToRefresh(selectedPages);
  2100. //刷新页码和图片
  2101. ReloadAfterOption(true, true, new Tuple<int, int>(0, PDFViewer.Document.PageCount));
  2102. if (!IsFromUndoRedo)
  2103. {
  2104. //存入Undo栈
  2105. PageEditHistory history = new PageEditHistory();
  2106. history.Type = ActionType.DragSort;
  2107. history.SourceTargetValue = SourceTargetValue;
  2108. //用于Redo恢复
  2109. history.InsertIndex = targetIndex;
  2110. AddToUndoStack(history);
  2111. }
  2112. }
  2113. /// <summary>
  2114. /// 移动某个Item到指定位置
  2115. /// </summary>
  2116. private bool MoveItemToIndex(int sourceindex, int targetindex)
  2117. {
  2118. if (targetindex == sourceindex || targetindex < 0)
  2119. {
  2120. return false;
  2121. }
  2122. //文档层移动
  2123. var result = PDFViewer.Document.MovePage(sourceindex, targetindex);
  2124. if (!result)
  2125. {
  2126. return false;
  2127. }
  2128. //UI层移动
  2129. var source = PageEditItems[sourceindex];
  2130. PageEditItems.RemoveAt(sourceindex);
  2131. PageEditItems.Insert(targetindex, source);
  2132. if(PDFViewer.CurrentIndex==sourceindex)
  2133. {
  2134. PDFViewer.GoToPage(targetindex);
  2135. }
  2136. return true;
  2137. }
  2138. /// <summary>
  2139. /// 从底层库获取对应页面的图片
  2140. /// </summary>
  2141. /// <param name="pageIndex"></param>
  2142. /// <param name="thumb"></param>
  2143. /// <param name="w"></param>
  2144. /// <param name="h"></param>
  2145. private void PDFViewer_OnThumbnailGenerated(int pageIndex, byte[] thumb, int w, int h)
  2146. {
  2147. try
  2148. {
  2149. if (PageEditItems.Count >= pageIndex + 1)
  2150. {
  2151. PixelFormat fmt = PixelFormats.Bgra32;
  2152. BitmapSource bps = BitmapSource.Create(w, h, 96.0, 96.0, fmt, null, thumb, (w * fmt.BitsPerPixel + 7) / 8);
  2153. PageEditItems[pageIndex].Image = bps;
  2154. PageEditItems[pageIndex].IsGetImage = true;
  2155. }
  2156. }
  2157. catch
  2158. {
  2159. }
  2160. }
  2161. #endregion
  2162. #region Navigate
  2163. public bool IsNavigationTarget(NavigationContext navigationContext)
  2164. {
  2165. return true;
  2166. }
  2167. public void OnNavigatedFrom(NavigationContext navigationContext)
  2168. {
  2169. }
  2170. /// <summary>
  2171. /// 从其他页面导航过来的时候会触发
  2172. /// 考虑只有在页面编辑的时候会进行页面的删减,可以尝试逻辑优化:仅第一次进入页面编辑时重新刷新页面
  2173. /// </summary>
  2174. /// <param name="navigationContext"></param>
  2175. public void OnNavigatedTo(NavigationContext navigationContext)
  2176. {
  2177. navigationContext.Parameters.TryGetValue<ViewContentViewModel>(ParameterNames.ViewContentViewModel, out viewContentViewModel);
  2178. navigationContext.Parameters.TryGetValue<CPDFViewer>(ParameterNames.PDFViewer, out PDFViewer);
  2179. bool isBOTA = false;
  2180. navigationContext.Parameters.TryGetValue<bool>(ParameterNames.BOTAThumb, out isBOTA);
  2181. if (PDFViewer != null)
  2182. {
  2183. if (isFirstLoad)
  2184. {
  2185. PDFViewer.OnThumbnailGenerated -= PDFViewer_OnThumbnailGenerated;
  2186. PDFViewer.OnThumbnailGenerated += PDFViewer_OnThumbnailGenerated;
  2187. PDFViewer.InfoChanged -= PDFViewer_InfoChanged;
  2188. PDFViewer.InfoChanged += PDFViewer_InfoChanged;
  2189. PDFViewer.AnnotEditHandler -= PDFViewer_AnnotEditHandler;
  2190. PDFViewer.AnnotEditHandler += PDFViewer_AnnotEditHandler;
  2191. ZoomIndex = 0;
  2192. if (viewContentViewModel != null)
  2193. {
  2194. viewContentViewModel.PageEditUndo = Undo;
  2195. viewContentViewModel.PageEditRedo = Redo;
  2196. }
  2197. }
  2198. //BOTA缩略图时,显示不同的菜单栏
  2199. if (isBOTA)
  2200. {
  2201. IsBOTAThumb = Visibility.Visible;
  2202. }
  2203. else
  2204. {
  2205. IsBOTAThumb = Visibility.Collapsed;
  2206. }
  2207. GetSourceItems(isFirstLoad);
  2208. ListSelectedIndex = PDFViewer.CurrentIndex;
  2209. viewContentViewModel.CanUndo = this.CanUndo;
  2210. viewContentViewModel.CanRedo = this.CanRedo;
  2211. RefreshBookMarkList();
  2212. isFirstLoad = false;
  2213. }
  2214. }
  2215. private void PDFViewer_AnnotEditHandler(object sender, List<ComPDFKitViewer.AnnotEvent.AnnotEditEvent> e)
  2216. {
  2217. if (e != null && e.Count > 0)
  2218. {
  2219. int pageIndex = e[0].PageIndex;
  2220. RefreshItemImage(pageIndex, pageIndex);
  2221. }
  2222. }
  2223. private void PDFViewer_InfoChanged(object sender, KeyValuePair<string, object> e)
  2224. {
  2225. if (e.Key == "PageNum")
  2226. {
  2227. NotifyUIToRefresh(new List<int> { (e.Value as ComPDFKitViewer.RenderData).PageIndex });
  2228. }
  2229. }
  2230. #endregion
  2231. }
  2232. }