PageEditContentViewModel.cs 85 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468
  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. namespace PDF_Master.ViewModels.PageEdit
  32. {
  33. public class PageEditContentViewModel : BindableBase, INavigationAware
  34. {
  35. #region 文案
  36. private string T_title;
  37. public string T_Title
  38. {
  39. get { return T_title; }
  40. set
  41. {
  42. SetProperty(ref T_title, value);
  43. }
  44. }
  45. private void InitString()
  46. {
  47. T_Title = App.MainPageLoader.GetString("Thumbnails_Title");
  48. }
  49. #endregion
  50. private CPDFViewer PDFViewer;
  51. private ViewContentViewModel viewContentViewModel;
  52. private IDialogService dialogs;
  53. private IEventAggregator eventor;
  54. /// <summary>
  55. /// 用于筛选多窗体时间的唯一识别码
  56. /// </summary>
  57. private string unicode = null;
  58. /// <summary>
  59. /// Undo操作记录栈
  60. /// 只有插入、移位、旋转,倒序需要记录
  61. /// </summary>
  62. private Stack<PageEditHistory> UndoStack = new Stack<PageEditHistory>();
  63. /// <summary>
  64. /// Redo操作记录栈
  65. /// </summary>
  66. private Stack<PageEditHistory> RedoStack = new Stack<PageEditHistory>();
  67. /// <summary>
  68. /// 项数据集合
  69. /// </summary>
  70. public ObservableCollection<PageEditItem> PageEditItems { get; set; }
  71. /// <summary>
  72. /// 页面范围的项集合
  73. /// </summary>
  74. public ObservableCollection<string> PageRangeItems { get; set; }
  75. #region 属性
  76. /// <summary>
  77. /// 是否是第一次加载
  78. /// </summary>
  79. private bool isFirstLoad = true;
  80. /// <summary>
  81. /// 记录多选项中最后一项的索引
  82. /// </summary>
  83. private int maxSelectedIndex = 0;
  84. private Visibility showTip = Visibility.Collapsed;
  85. /// <summary>
  86. /// 是否显示渐隐提示
  87. /// </summary>
  88. public Visibility ShowTip
  89. {
  90. get { return showTip; }
  91. set
  92. {
  93. SetProperty(ref showTip, value);
  94. }
  95. }
  96. private Visibility isLoading = Visibility.Collapsed;
  97. /// <summary>
  98. /// 是否正在处理中
  99. /// </summary>
  100. public Visibility IsLoading
  101. {
  102. get { return isLoading; }
  103. set
  104. {
  105. SetProperty(ref isLoading, value);
  106. }
  107. }
  108. private int listSelecedIndex;
  109. /// <summary>
  110. /// 缩略图选中项的索引
  111. /// </summary>
  112. public int ListSelectedIndex
  113. {
  114. get { return listSelecedIndex; }
  115. set
  116. {
  117. SetProperty(ref listSelecedIndex, value);
  118. //显示页面范围选择控件
  119. TbPageRangeVisibility = Visibility.Visible;
  120. TbPageRange = (ListSelectedIndex + 1).ToString();
  121. TxtPageInputVisibility = Visibility.Collapsed;
  122. if(IsBOTAThumb==Visibility.Visible&&PDFViewer!=null)
  123. {
  124. PDFViewer.GoToPage(listSelecedIndex);
  125. }
  126. }
  127. }
  128. private bool isMultiSelected;
  129. /// <summary>
  130. /// 是否有多选 用于判断倒序和替换功能
  131. /// </summary>
  132. public bool IsMultiSelected
  133. {
  134. get { return isMultiSelected; }
  135. set
  136. {
  137. SetProperty(ref isMultiSelected, value);
  138. }
  139. }
  140. private int comboxSelectIndex;
  141. /// <summary>
  142. /// 下拉框选项集合
  143. /// </summary>
  144. public int ComboxSelectIndex
  145. {
  146. get { return comboxSelectIndex; }
  147. set
  148. {
  149. SetProperty(ref comboxSelectIndex, value);
  150. //选中指定的页面范围
  151. SuitPageRange(comboxSelectIndex);
  152. //隐藏tb页面范围显示控件
  153. TbPageRangeVisibility = Visibility.Collapsed;
  154. }
  155. }
  156. private Visibility tbPageRangeVisibility = Visibility.Visible;
  157. /// <summary>
  158. /// 页面范围的文本显示
  159. /// </summary>
  160. public Visibility TbPageRangeVisibility
  161. {
  162. get { return tbPageRangeVisibility; }
  163. set
  164. {
  165. SetProperty(ref tbPageRangeVisibility, value);
  166. if (value == Visibility.Visible)
  167. {
  168. comboxSelectIndex = -1;
  169. }
  170. }
  171. }
  172. private string tbPageRange;
  173. /// <summary>
  174. /// 页面范围显示的内容
  175. /// </summary>
  176. public string TbPageRange
  177. {
  178. get { return tbPageRange; }
  179. set
  180. {
  181. SetProperty(ref tbPageRange, value);
  182. if(string.IsNullOrEmpty(TbPageRange))
  183. {
  184. TbPageRange = "请输入范围";
  185. }
  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. #endregion
  303. #region 命令
  304. public DelegateCommand<object> SelectionChangedCommand { get; set; }
  305. /// <summary>
  306. /// 拦截键盘输入的事件
  307. /// </summary>
  308. public DelegateCommand<object> PreviewKeyDown { get; set; }
  309. /// <summary>
  310. /// 响应键盘回车事件
  311. /// </summary>
  312. public DelegateCommand<object> KeyDown { get; set; }
  313. /// <summary>
  314. ///文本框失去焦点事件
  315. /// </summary>
  316. public DelegateCommand<object> LostFocusCommand { get; set; }
  317. /// <summary>
  318. /// 粘贴
  319. /// </summary>
  320. public DelegateCommand PasteCommand { get; set; }
  321. /// <summary>
  322. /// 复制
  323. /// </summary>
  324. public DelegateCommand CopyCommand { get; set; }
  325. /// <summary>
  326. /// 剪切
  327. /// </summary>
  328. public DelegateCommand CutCommand { get; set; }
  329. /// <summary>
  330. /// 替换文件
  331. /// </summary>
  332. public DelegateCommand ReplaceCommand { get; set; }
  333. /// <summary>
  334. /// 插入文件命令
  335. /// </summary>
  336. public DelegateCommand<object> InsertCommand { get; set; }
  337. /// <summary>
  338. /// 拆分文件
  339. /// </summary>
  340. public DelegateCommand SplitCommand { get; set; }
  341. /// <summary>
  342. /// 提取文件
  343. /// </summary>
  344. public DelegateCommand ExtractCommand { get; set; }
  345. /// <summary>
  346. /// 逆时针旋转
  347. /// </summary>
  348. public DelegateCommand LeftRotateCommand { get; set; }
  349. /// <summary>
  350. /// 顺时针旋转
  351. /// </summary>
  352. public DelegateCommand RightRotateCommand { get; set; }
  353. /// <summary>
  354. /// 删除
  355. /// </summary>
  356. public DelegateCommand DeleteCommand { get; set; }
  357. /// <summary>
  358. /// 倒序
  359. /// </summary>
  360. public DelegateCommand ReverseCommand { get; set; }
  361. /// <summary>
  362. /// 打印
  363. /// </summary>
  364. public DelegateCommand PrintCommand { get; set; }
  365. /// <summary>
  366. /// 放大
  367. /// </summary>
  368. public DelegateCommand ZoomInCommand { get; set; }
  369. /// <summary>
  370. /// 缩小
  371. /// </summary>
  372. public DelegateCommand ZoomOutCommand { get; set; }
  373. /// <summary>
  374. /// 显示页面大小
  375. /// </summary>
  376. public DelegateCommand ShowPageSizeCommand { get; set; }
  377. public DelegateCommand ClearSelectedCommand { get; set; }
  378. #endregion
  379. public PageEditContentViewModel(IDialogService dialogService, IEventAggregator eventAggregator)
  380. {
  381. //变量初始化
  382. dialogs = dialogService;
  383. eventor = eventAggregator;
  384. unicode = App.mainWindowViewModel.SelectedItem.Unicode;
  385. PageEditItems = new ObservableCollection<PageEditItem>();
  386. PageRangeItems = new ObservableCollection<string>();
  387. //绑定命令
  388. SelectionChangedCommand = new DelegateCommand<object>(SelectionChangedEvent);
  389. PreviewKeyDown = new DelegateCommand<object>(PreviewKeyDownEvent);
  390. KeyDown = new DelegateCommand<object>(KeyDownEvent);
  391. LostFocusCommand = new DelegateCommand<object>(lostfocus);
  392. SplitCommand = new DelegateCommand(SplitCommandEvent);
  393. InsertCommand = new DelegateCommand<object>(InsertCommandEvent);
  394. ReplaceCommand = new DelegateCommand(ReplaceCommandEvent, CanReplaceCommandExcute).ObservesProperty(() => IsMultiSelected);
  395. ExtractCommand = new DelegateCommand(ExtractCommandEvent, CanFileCommandExcute).ObservesProperty(() => ListSelectedIndex);
  396. DeleteCommand = new DelegateCommand(DeleteCommandEvent, CanFileCommandExcute).ObservesProperty(() => ListSelectedIndex);
  397. LeftRotateCommand = new DelegateCommand(LeftRotateCommandEvent, CanFileCommandExcute).ObservesProperty(() => ListSelectedIndex);
  398. RightRotateCommand = new DelegateCommand(RightRotateCommandEvent, CanFileCommandExcute).ObservesProperty(() => ListSelectedIndex);
  399. ReverseCommand = new DelegateCommand(ReverseCommandEvent, CanFileCommandExcute).ObservesProperty(() => ListSelectedIndex);
  400. ZoomInCommand = new DelegateCommand(ZoomInCommandEvent, CanZoomIn).ObservesProperty(() => ZoomIndex);
  401. ZoomOutCommand = new DelegateCommand(ZoomOutCommandEvent, CanZoomOut).ObservesProperty(() => ZoomIndex);
  402. ShowPageSizeCommand = new DelegateCommand(ShowPageSize);
  403. CopyCommand = new DelegateCommand(copy);
  404. PasteCommand = new DelegateCommand(paste,CanPasteExcute).ObservesProperty(() => CanPaste);
  405. CutCommand = new DelegateCommand(cut);
  406. PrintCommand = new DelegateCommand(print);
  407. ClearSelectedCommand = new DelegateCommand(clearSelected);
  408. //订阅页面刷新事件
  409. eventAggregator.GetEvent<PageEditRefreshEvent>().Subscribe(OnPageEditRefreshEvent, e => e.Unicode == unicode);
  410. CacheFilePath.Instance.PropertyChanged += Instance_PropertyChanged;
  411. RefreshPageRangeItem();
  412. InitString();
  413. }
  414. #region 事件
  415. private void Instance_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
  416. {
  417. if(e.PropertyName=="CopyDoc")
  418. {
  419. if(CacheFilePath.Instance.CopyDoc!=null)
  420. {
  421. CanPaste = true;
  422. }
  423. }
  424. }
  425. /// <summary>
  426. /// 替换功能的逻辑
  427. /// </summary>
  428. private async void ReplaceCommandEvent()
  429. {
  430. OpenFileDialog dialog = new OpenFileDialog();
  431. dialog.Multiselect = false;
  432. dialog.Filter = PDF_Master.Properties.Resources.OpenDialogFilter;
  433. if ((bool)dialog.ShowDialog())
  434. {
  435. IsLoading = Visibility.Visible;
  436. await Task.Delay(200);
  437. int pageCount = PDFViewer.Document.PageCount;
  438. int insertIndex = listSelecedIndex;
  439. //从文件插入到指定位置
  440. var result = await InsertFromFile(listSelecedIndex+1,dialog.FileName);
  441. if(result)
  442. {
  443. //插入成功后再删除原有页面
  444. DoRemoveSelectedPages(new List<int>() { listSelecedIndex });
  445. }
  446. ReloadAfterOption(true, true, Tuple.Create(insertIndex-1, insertIndex + pageCount));
  447. IsLoading = Visibility.Collapsed;
  448. }
  449. }
  450. /// <summary>
  451. /// 拆分功能的逻辑
  452. /// </summary>
  453. private void SplitCommandEvent()
  454. {
  455. DialogParameters valuePairs = new DialogParameters();
  456. valuePairs.Add(ParameterNames.PDFViewer, PDFViewer);
  457. dialogs.ShowDialog(DialogNames.SplitDialog, valuePairs,e=> {
  458. if(e.Result==ButtonResult.OK&&e.Parameters!=null)
  459. {
  460. var model = e.Parameters.GetValue<HomePageSplitDialogModel>(ParameterNames.DataModel);
  461. DoSplitPages(model);
  462. }
  463. });
  464. }
  465. /// <summary>
  466. /// 提取功能的逻辑
  467. /// </summary>
  468. private void ExtractCommandEvent()
  469. {
  470. dialogs.ShowDialog(DialogNames.ExtractDialog,null,e=> {
  471. if(e.Result==ButtonResult.OK&&e.Parameters!=null)
  472. {
  473. var model = e.Parameters.GetValue<ExtractModel>(ParameterNames.DataModel);
  474. DoExtractPages(model.IsEveryPageToFile,model.IsDeleteAfterExtract);
  475. }
  476. });
  477. }
  478. /// <summary>
  479. /// 插入功能的逻辑
  480. /// </summary>
  481. private async void InsertCommandEvent(object type)
  482. {
  483. if((string)type==null)
  484. {
  485. return;
  486. }
  487. //获取插入位置
  488. int insertIndex = 0;
  489. if(listSelecedIndex<0)
  490. {
  491. insertIndex = 0;
  492. }
  493. else
  494. {
  495. insertIndex = listSelecedIndex+1;
  496. if(isMultiSelected)
  497. {
  498. insertIndex = maxSelectedIndex+1;
  499. }
  500. }
  501. IsLoading = Visibility.Visible;
  502. await Task.Delay(3);
  503. PageEditHistory history = new PageEditHistory();
  504. history.InsertIndex = insertIndex;
  505. if((string)type==ParameterNames.InsertType_Blank)
  506. {
  507. history.Type = ActionType.InsertCustomPages;
  508. history.InsertFilePath = "";
  509. //插入空白页面
  510. bool result;
  511. if (insertIndex == 0)
  512. {
  513. result = PDFViewer.Document.InsertPage(insertIndex, PageEditItems[insertIndex].Size.Width, PageEditItems[insertIndex].Size.Height, null);
  514. history.PageSize = PageEditItems[insertIndex].Size;
  515. }
  516. else
  517. {
  518. result = PDFViewer.Document.InsertPage(insertIndex, PageEditItems[insertIndex-1].Size.Width, PageEditItems[insertIndex-1].Size.Height, null);
  519. history.PageSize = PageEditItems[insertIndex - 1].Size;
  520. }
  521. if(!result)
  522. {
  523. IsLoading = Visibility.Collapsed;
  524. ShowToast();
  525. return;
  526. }
  527. //UI层插入Item
  528. var item = GetNewPageEditItem(insertIndex);
  529. PageEditItems.Insert(insertIndex,item);
  530. ReloadAfterOption(true,true,Tuple.Create(insertIndex,insertIndex+1));
  531. await Task.Delay(10);
  532. //选中插入的页面
  533. ListSelectedIndex = insertIndex;
  534. }
  535. else if((string)type == ParameterNames.InsertType_File)
  536. {
  537. OpenFileDialog dialog = new OpenFileDialog();
  538. dialog.Multiselect = false;
  539. dialog.Filter = PDF_Master.Properties.Resources.OpenDialogFilter;
  540. if ((bool)dialog.ShowDialog())
  541. {
  542. //插入文件
  543. var result = await InsertFromFile(insertIndex,dialog.FileName);
  544. if(!result)
  545. {
  546. IsLoading = Visibility.Collapsed;
  547. ShowToast();
  548. return;
  549. }
  550. ReloadAfterOption(true,true,Tuple.Create(0,PDFViewer.Document.PageCount));
  551. }
  552. IsLoading = Visibility.Collapsed;
  553. //里面附带了Undo栈记录,需要提前返回,避免重复记录
  554. return;
  555. }
  556. else
  557. {
  558. DialogParameters keyValuePairs = new DialogParameters();
  559. Size size = new Size();
  560. size.Width =CommonHelper.GetUnitsFromPageSize(PDFViewer.Document.GetPageSize(listSelecedIndex).Width);
  561. size.Height = CommonHelper.GetUnitsFromPageSize(PDFViewer.Document.GetPageSize(listSelecedIndex).Height);
  562. keyValuePairs.Add("CurrentPageSize", size);
  563. //插入自定义页面
  564. dialogs.ShowDialog(DialogNames.InsertDialog, keyValuePairs,e=> {
  565. if(e.Result == ButtonResult.OK&&e.Parameters!=null)
  566. {
  567. var model = e.Parameters.GetValue<CustomInsertModel>(ParameterNames.DataModel);
  568. var result = InsertFromCustomPage(insertIndex, model.width, model.height, model.filepath);
  569. if(!result)
  570. {
  571. return;
  572. }
  573. history.Type = ActionType.InsertCustomPages;
  574. history.InsertFilePath = model.filepath;
  575. history.PageSize = new Size(model.width,model.height);
  576. }
  577. });
  578. }
  579. IsLoading = Visibility.Collapsed;
  580. //添加记录到Undo栈,清除Redo栈
  581. AddToUndoStack(history);
  582. }
  583. /// <summary>
  584. /// 删除选中页面
  585. /// </summary>
  586. private async void DeleteCommandEvent()
  587. {
  588. IsLoading = Visibility.Visible;
  589. await Task.Delay(3);
  590. DoRemoveSelectedPages();
  591. ReloadAfterOption(true, true, Tuple.Create(0,PDFViewer.Document.PageCount));
  592. IsLoading = Visibility.Collapsed;
  593. }
  594. /// <summary>
  595. /// 左旋转页面的逻辑
  596. /// </summary>
  597. private void LeftRotateCommandEvent()
  598. {
  599. RotateSelectedPages(false);
  600. }
  601. /// <summary>
  602. /// 右旋转页面的逻辑
  603. /// </summary>
  604. private void RightRotateCommandEvent()
  605. {
  606. RotateSelectedPages();
  607. }
  608. /// <summary>
  609. /// 页面倒序的逻辑
  610. /// </summary>
  611. private async void ReverseCommandEvent()
  612. {
  613. IsLoading = Visibility.Visible;
  614. await Task.Delay(3);
  615. List<int> pages = new List<int>();
  616. for (int i = 0; i <PageEditItems.Count; i++)
  617. {
  618. if (PageEditItems[i].Selected)
  619. {
  620. pages.Add(i);
  621. }
  622. }
  623. DoReverse(pages);
  624. IsLoading = Visibility.Collapsed;
  625. }
  626. /// <summary>
  627. /// 将指定页面结合进行倒序
  628. /// </summary>
  629. private async void DoReverse(List<int> pages, bool isFromUndoRedo = false)
  630. {
  631. if (pages.Count <= 1)
  632. {
  633. ShowToast("请至少选择两个图片进行倒序操作。");
  634. return;
  635. }
  636. pages.Sort();
  637. //记录原位置和目标位置 用于undo,redo
  638. Dictionary<int, int> sourceTarget = new Dictionary<int, int>();
  639. for (int i = 0; i < pages.Count; i++)
  640. {
  641. int preindex = pages[i];
  642. int laterIndex = pages[pages.Count - i - 1];//尾部的索引
  643. if (laterIndex <= preindex)//交换完成
  644. {
  645. //用于记录选中集合为奇数时,最中间Item的还原
  646. sourceTarget.Add(preindex, preindex);
  647. break;
  648. }
  649. var result = ExchangeItem(preindex,laterIndex);
  650. if(!result)
  651. {
  652. ShowToast();
  653. IsLoading = Visibility.Collapsed;
  654. return;
  655. }
  656. sourceTarget.Add(preindex, laterIndex);
  657. }
  658. await Task.Delay(20);
  659. //转换成页码数据集合,传递给UI,选中目标页面
  660. //因虚拟化加载的问题,通过Selected来控制Item选中效果会有问题
  661. List<int> pageRange = new List<int>();
  662. for (int i = 0; i < pages.Count; i++)
  663. {
  664. pageRange.Add(pages[i] + 1);
  665. }
  666. NotifyUIToRefresh(pageRange);
  667. ReloadAfterOption(true, true, null);
  668. if(!isFromUndoRedo)
  669. {
  670. PageEditHistory history = new PageEditHistory();
  671. history.Type = ActionType.Reverse;
  672. history.SourceTargetValue = sourceTarget;
  673. AddToUndoStack(history);
  674. }
  675. }
  676. /// <summary>
  677. /// 交换两个Item顺序
  678. /// </summary>
  679. /// <param name="preiIndex"></param>
  680. /// <param name="laterIndex"></param>
  681. /// <returns></returns>
  682. private bool ExchangeItem(int preiIndex,int laterIndex)
  683. {
  684. if (preiIndex == laterIndex)
  685. {
  686. return true;
  687. }
  688. var sourceitem = PageEditItems[preiIndex];
  689. var targetitem = PageEditItems[laterIndex];
  690. var result = PDFViewer.Document.ExchangePage(preiIndex, laterIndex);
  691. if (!result)
  692. {
  693. return false;
  694. }
  695. PageEditItems.Remove(sourceitem);
  696. PageEditItems.Remove(targetitem);
  697. PageEditItems.Insert(preiIndex, targetitem);
  698. PageEditItems.Insert(laterIndex, sourceitem);
  699. //PageEditItems.Remove(targetitem);
  700. //PageEditItems.Insert(laterIndex, sourceitem);
  701. //PageEditItems.Remove(sourceitem);
  702. //PageEditItems.Insert(preiIndex, targetitem);
  703. return true;
  704. }
  705. /// <summary>
  706. /// 是否可以执行文件操作命令 除插入、拆分外
  707. /// </summary>
  708. /// <returns></returns>
  709. private bool CanFileCommandExcute()
  710. {
  711. if (ListSelectedIndex < 0)
  712. {
  713. return false;
  714. }
  715. else
  716. {
  717. return true;
  718. }
  719. }
  720. /// <summary>
  721. /// 校验是否可以替换
  722. /// </summary>
  723. /// <returns></returns>
  724. private bool CanReplaceCommandExcute()
  725. {
  726. return !IsMultiSelected;
  727. }
  728. /// <summary>
  729. /// 放大页面
  730. /// </summary>
  731. private void ZoomInCommandEvent()
  732. {
  733. ZoomIndex++;
  734. ChangeItemSize(ItemSizes[ZoomIndex+1]);
  735. NotifyUIToRefresh();
  736. }
  737. /// <summary>
  738. /// 缩小页面
  739. /// </summary>
  740. private void ZoomOutCommandEvent()
  741. {
  742. ZoomIndex--;
  743. ChangeItemSize(ItemSizes[ZoomIndex+1]);
  744. NotifyUIToRefresh();
  745. }
  746. /// <summary>
  747. ///
  748. /// </summary>
  749. /// <param name="newsize"></param>
  750. public void ChangeItemSize(Size newsize)
  751. {
  752. for (int i = 0; i < PageEditItems.Count; i++)
  753. {
  754. PageEditItems[i].ItemSize = newsize;
  755. }
  756. //缩略图模式 调整item大小的时候,更新选中项
  757. NotifyUIToRefresh(new List<int>() { PDFViewer.CurrentIndex + 1 });
  758. }
  759. private bool CanZoomIn()
  760. {
  761. if (ZoomIndex >= 1)
  762. {
  763. return false;
  764. }
  765. else
  766. {
  767. return true;
  768. }
  769. }
  770. private bool CanZoomOut()
  771. {
  772. if (ZoomIndex <= -1)
  773. {
  774. return false;
  775. }
  776. else
  777. {
  778. return true;
  779. }
  780. }
  781. /// <summary>
  782. /// 响应UI发送刷新图片的事件
  783. /// </summary>
  784. /// <param name="e"></param>
  785. private void OnPageEditRefreshEvent(PageEditRefreshEventArgs e)
  786. {
  787. //UI发送事件过来通知刷新图片时
  788. //调整逻辑,前后预加载5页
  789. RefreshItemImage(e.PageRange.Item1 - 2, e.PageRange.Item2 + 2);
  790. }
  791. /// <summary>
  792. /// 选项改变事件
  793. /// 虚拟化的时候不会触发选中事件
  794. /// </summary>
  795. /// <param name="e"></param>
  796. private void SelectionChangedEvent(object e)
  797. {
  798. var args = e as SelectionChangedEventArgs;
  799. //下下策 从UI控件获取所有选项的集合
  800. var listbox = args.OriginalSource as ListBox;
  801. if (TbPageRangeVisibility == Visibility.Visible && args != null)
  802. {
  803. selectedPageList = new List<int>();
  804. for (int i = 0; i < listbox.SelectedItems.Count; i++)
  805. {
  806. if (!selectedPageList.Contains((listbox.SelectedItems[i] as PageEditItem).PageNumber))
  807. {
  808. selectedPageList.Add((listbox.SelectedItems[i] as PageEditItem).PageNumber);
  809. }
  810. }
  811. ////根据选中的范围 适配全部页面范围、奇数页面范围等
  812. //if (pagelist.Count == PageEditItems.Count)
  813. //{
  814. // ComboxSelectIndex = 0;
  815. // return;
  816. //}
  817. //只选中单个页面是,listselectedIndex 更准确
  818. if (selectedPageList.Count == 1)
  819. {
  820. TbPageRange = (listSelecedIndex + 1).ToString();
  821. }
  822. else
  823. {
  824. string pageparm = CommonHelper.GetPageParmFromList(selectedPageList);
  825. TbPageRange = pageparm;
  826. }
  827. }
  828. //Ctrl+A时让所有item选中
  829. var isCtrlorShiftDown =( (Keyboard.IsKeyDown(Key.LeftCtrl) && Keyboard.IsKeyDown(Key.A))|| (Keyboard.IsKeyDown(Key.RightCtrl) && Keyboard.IsKeyDown(Key.A)));
  830. if (isCtrlorShiftDown)
  831. {
  832. for (int i = 0; i < PageEditItems.Count; i++)
  833. {
  834. PageEditItems[i].Selected = true;
  835. }
  836. }
  837. //判断是否有选中多项
  838. if (listbox.SelectedItems.Count > 1)
  839. {
  840. IsMultiSelected = true;
  841. maxSelectedIndex = listbox.Items.IndexOf(listbox.SelectedItems[listbox.SelectedItems.Count - 1]);
  842. }
  843. else
  844. {
  845. IsMultiSelected = false;
  846. }
  847. }
  848. /// <summary>
  849. /// 限制文本框输入内容
  850. /// </summary>
  851. /// <param name="e"></param>
  852. private void PreviewKeyDownEvent(object e)
  853. {
  854. var args = e as KeyEventArgs;
  855. if (args == null)
  856. {
  857. return;
  858. }
  859. 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)))
  860. {
  861. args.Handled = true;
  862. }
  863. }
  864. /// <summary>
  865. /// 响应回车确认事件
  866. /// </summary>
  867. /// <param name="e"></param>
  868. private void KeyDownEvent(object e)
  869. {
  870. var args = e as KeyEventArgs;
  871. if (args == null)
  872. {
  873. return;
  874. }
  875. if (args.Key == Key.Enter)
  876. {
  877. List<int> TargetPageIndexs = new List<int>();
  878. var result = CommonHelper.GetPagesInRange(ref TargetPageIndexs, (args.OriginalSource as TextBox).Text, PDFViewer.Document.PageCount, new char[] { ',', ',' }, new char[] { '-' });
  879. if (!result&&ComboxSelectIndex==5)
  880. {
  881. AlertsMessage alertsMessage = new AlertsMessage();
  882. alertsMessage.ShowDialog("","请输入有效范围","OK");
  883. return;
  884. }
  885. //选中输入的页面范围
  886. List<int> pageRange = new List<int>();
  887. for (int i = 0; i < PageEditItems.Count; i++)
  888. {
  889. if (TargetPageIndexs.Contains(PageEditItems[i].PageNumber - 1))
  890. {
  891. pageRange.Add(i+1);
  892. }
  893. }
  894. NotifyUIToRefresh(pageRange);
  895. }
  896. }
  897. /// <summary>
  898. /// 失去焦点后选中页面
  899. /// </summary>
  900. /// <param name="obj"></param>
  901. private void lostfocus(object obj)
  902. {
  903. var args = obj as RoutedEventArgs;
  904. if (args == null||(args.OriginalSource as TextBox)==null)
  905. {
  906. return;
  907. }
  908. List<int> TargetPageIndexs = new List<int>();
  909. if(PageRangeItems.Contains((args.OriginalSource as TextBox).Text)&&ComboxSelectIndex!=5)
  910. {
  911. //选中其他项,失去焦点时不报错
  912. return;
  913. }
  914. var result = CommonHelper.GetPagesInRange(ref TargetPageIndexs, (args.OriginalSource as TextBox).Text, PDFViewer.Document.PageCount, new char[] { ',', ',' }, new char[] { '-' });
  915. if (!result)
  916. {
  917. AlertsMessage alertsMessage = new AlertsMessage();
  918. alertsMessage.ShowDialog("", "请输入有效范围", "OK");
  919. return;
  920. }
  921. //选中输入的页面范围
  922. List<int> pageRange = new List<int>();
  923. for (int i = 0; i < PageEditItems.Count; i++)
  924. {
  925. if (TargetPageIndexs.Contains(PageEditItems[i].PageNumber - 1))
  926. {
  927. pageRange.Add(i + 1);
  928. }
  929. }
  930. NotifyUIToRefresh(pageRange);
  931. }
  932. #endregion
  933. #region 方法
  934. /// <summary>
  935. /// Esc退出多选
  936. /// </summary>
  937. private void clearSelected()
  938. {
  939. ListSelectedIndex = -1;
  940. }
  941. /// <summary>
  942. /// 调用打印机
  943. /// </summary>
  944. private void print()
  945. {
  946. PDFViewer.GoToPage(listSelecedIndex);
  947. DialogParameters printValue = new DialogParameters();
  948. printValue.Add(ParameterNames.PDFViewer, PDFViewer);
  949. printValue.Add(ParameterNames.FilePath, PDFViewer.Document.FileName);
  950. printValue.Add(ParameterNames.PrintCurrentPage, PDFViewer.CurrentIndex);
  951. printValue.Add(ParameterNames.PageList,selectedPageList);
  952. dialogs.ShowDialog(DialogNames.HomePagePrinterDialog, printValue, e => { });
  953. }
  954. /// <summary>
  955. /// 剪切
  956. /// </summary>
  957. private void cut()
  958. {
  959. CacheFilePath.Instance.CopyDoc = null;
  960. CacheFilePath.Instance.CopyDoc = CPDFDocument.CreateDocument();
  961. List<int> pages = new List<int>();
  962. for (int i = 0; i < PageEditItems.Count; i++)
  963. {
  964. if (PageEditItems[i].Selected)
  965. {
  966. pages.Add(i + 1);
  967. }
  968. }
  969. bool result = CacheFilePath.Instance.CopyDoc.ImportPages(PDFViewer.Document, String.Join(",", pages));
  970. if (!result)
  971. {
  972. ShowToast("复制失败");
  973. return;
  974. }
  975. DoRemoveSelectedPages();
  976. ReloadAfterOption(true, true, Tuple.Create(0, PDFViewer.Document.PageCount));
  977. }
  978. /// <summary>
  979. /// 复制
  980. /// </summary>
  981. private void copy()
  982. {
  983. //付费锁
  984. if (!App.IsLogin)
  985. {
  986. dialogs.ShowDialog(DialogNames.IAPCompareDialog);
  987. return;
  988. }
  989. CacheFilePath.Instance.CopyDoc = null;
  990. CacheFilePath.Instance.CopyDoc = CPDFDocument.CreateDocument();
  991. List<int> pages = new List<int>();
  992. for(int i=0;i<PageEditItems.Count;i++)
  993. {
  994. if(PageEditItems[i].Selected)
  995. {
  996. pages.Add(i + 1);
  997. }
  998. }
  999. bool result = CacheFilePath.Instance.CopyDoc.ImportPages(PDFViewer.Document, String.Join(",",pages));
  1000. if (!result)
  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 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. //await Task.Delay(20);
  1885. //TbPageRange = "1,3";
  1886. break;
  1887. default:
  1888. break;
  1889. }
  1890. if(pageRange.Count>0)
  1891. {
  1892. NotifyUIToRefresh(pageRange);
  1893. }
  1894. else
  1895. {
  1896. if (index != 5)
  1897. {
  1898. //没有符合条件时 清空选中项
  1899. ListSelectedIndex = -1;
  1900. }
  1901. }
  1902. }
  1903. /// <summary>
  1904. /// 是否显示页面尺寸
  1905. /// </summary>
  1906. /// <param name="show">是或否</param>
  1907. private void ShowPageSize()
  1908. {
  1909. bool show = true;
  1910. if(HasShowPageSize== Visibility.Visible)
  1911. {
  1912. show = false;
  1913. HasShowPageSize = Visibility.Collapsed;
  1914. }
  1915. else
  1916. {
  1917. show = true;
  1918. HasShowPageSize = Visibility.Visible;
  1919. }
  1920. for (int i = 0; i < PageEditItems.Count; i++)
  1921. {
  1922. PageEditItems[i].ShowPageSize = show;
  1923. }
  1924. }
  1925. /// <summary>
  1926. /// 从PDFView获取所有Items集合
  1927. /// </summary>
  1928. private void GetSourceItems(bool isFirstLoad)
  1929. {
  1930. if (isFirstLoad||IsBOTAThumb==Visibility.Visible)
  1931. {
  1932. PageEditItems.Clear();
  1933. for (int i = 0; i < PDFViewer.Document.PageCount; i++)
  1934. {
  1935. var item = GetNewPageEditItem(i);
  1936. PageEditItems.Add(item);
  1937. }
  1938. }
  1939. //else
  1940. //{
  1941. // //后续进来仅刷新图片即可
  1942. // for (int i = 0; i < PageEditItems.Count; i++)
  1943. // {
  1944. // PageEditItems[i].IsGetImage = false;
  1945. // }
  1946. //}
  1947. }
  1948. /// <summary>
  1949. /// 刷新书签列表
  1950. /// </summary>
  1951. public void RefreshBookMarkList()
  1952. {
  1953. if (PDFViewer != null)
  1954. {
  1955. var booklist = PDFViewer.Document.GetBookmarkList();
  1956. if (booklist == null)
  1957. {
  1958. return;
  1959. }
  1960. //获取所有书签的Index集合
  1961. List<int> marks = new List<int>();
  1962. for (int i = 0; i < booklist.Count; i++)
  1963. {
  1964. marks.Add(booklist[i].PageIndex);
  1965. }
  1966. //不能只遍历marks集合,考虑书签集合元素删除的情况
  1967. for (int k = 0; k < PageEditItems.Count; k++)
  1968. {
  1969. if (marks.Contains(k))
  1970. PageEditItems[k].HaveBookMark = true;
  1971. else
  1972. PageEditItems[k].HaveBookMark = false;
  1973. }
  1974. }
  1975. }
  1976. /// <summary>
  1977. /// 刷新指定范围的图片
  1978. /// </summary>
  1979. /// <param name="startIndex"></param>
  1980. /// <param name="endIndex"></param>
  1981. private async void RefreshItemImage(int startIndex, int endIndex)
  1982. {
  1983. for (int i = startIndex; i <= endIndex; i++)
  1984. {
  1985. if (i <= PageEditItems.Count- 1 && i >= 0 && PageEditItems.Count > 0)
  1986. {
  1987. //宽高为样式中图片控件宽高
  1988. if (PageEditItems[i].isVertical)
  1989. {
  1990. //等比例缩放
  1991. if (PageEditItems[i].Size.Height > 300)
  1992. {
  1993. await PDFViewer.GetThumbnail(i, (int)(PageEditItems[i].Size.Width / (PageEditItems[i].Size.Height / 300)), 300);
  1994. }
  1995. else
  1996. {
  1997. await PDFViewer.GetThumbnail(i, (int)PageEditItems[i].Size.Width, (int)PageEditItems[i].Size.Height);
  1998. }
  1999. }
  2000. else
  2001. {
  2002. if (PageEditItems[i].Size.Width > 300)
  2003. {
  2004. await PDFViewer.GetThumbnail(i, 300, (int)(PageEditItems[i].Size.Height / (PageEditItems[i].Size.Width / 300)));
  2005. }
  2006. else
  2007. {
  2008. //获取横图
  2009. await PDFViewer.GetThumbnail(i, (int)PageEditItems[i].Size.Width, (int)PageEditItems[i].Size.Height);
  2010. }
  2011. }
  2012. }
  2013. }
  2014. }
  2015. /// <summary>
  2016. /// 拖拽排序功能
  2017. /// </summary>
  2018. /// <param name="targetIndex"></param>
  2019. /// <param name="pageIndexs"></param>
  2020. public void DragToSort(int targetIndex,List<int> pageIndexs,bool IsFromUndoRedo =false)
  2021. {
  2022. //拖拽排序后需要重新选中项的集合
  2023. List<int> selectedPages = new List<int>();
  2024. //记录原位置和目标位置的字典,用于Undo,Redo恢复
  2025. Dictionary<int, int> SourceTargetValue = new Dictionary<int, int>();
  2026. bool result = false;
  2027. //排序前,先对所有页码排序
  2028. pageIndexs.Sort();
  2029. //要考虑每一次交换都会导致局部页码发生改变
  2030. //每次整体往后移动时,先移动大页码;整体往前移动时,先移动小页码;往中间移动时,再按上述两种情况分别移动
  2031. if (targetIndex <= pageIndexs[0])
  2032. {
  2033. for (int i = 0; i < pageIndexs.Count; i++)
  2034. {
  2035. // list.Add(PageEditListBox.Items[pageIndexs[i]] as ListBoxItem);
  2036. //sourceindex.Add(pageIndexs[i]);
  2037. result = MoveItemToIndex(pageIndexs[i], targetIndex + i);
  2038. if(!result)
  2039. {
  2040. return;
  2041. }
  2042. SourceTargetValue.Add(pageIndexs[i], targetIndex + i);
  2043. selectedPages.Add(targetIndex + i+1);
  2044. }
  2045. }
  2046. else if (targetIndex > pageIndexs[pageIndexs.Count - 1])
  2047. {
  2048. //目标位置在所有选中内容右边 整体后移
  2049. for (int i = 0; i < pageIndexs.Count; i++)
  2050. {
  2051. result = MoveItemToIndex(pageIndexs[pageIndexs.Count - 1 - i], targetIndex - 1 - i);
  2052. if (!result)
  2053. {
  2054. return;
  2055. }
  2056. SourceTargetValue.Add(pageIndexs[pageIndexs.Count - 1 - i], targetIndex - 1 - i);
  2057. selectedPages.Add(targetIndex - i);
  2058. }
  2059. }
  2060. else//目标位置在所有选中项中间
  2061. {
  2062. int i, j, k;
  2063. //找出PageEditListBox.Items中页码等于destpage的下标
  2064. for (k = 0; k < pageIndexs.Count - 1; k++)
  2065. {
  2066. //这里要算入K---即前面部分的页面个数
  2067. if (pageIndexs[k] < targetIndex && pageIndexs[k + 1] >= targetIndex)
  2068. {
  2069. break;
  2070. }
  2071. }
  2072. //局部往后移动
  2073. for (i = 0; i <= k; i++)
  2074. {
  2075. result = MoveItemToIndex(pageIndexs[k - i], targetIndex - 1 - i);
  2076. if (!result)
  2077. {
  2078. return;
  2079. }
  2080. SourceTargetValue.Add(pageIndexs[k - i], targetIndex - 1 - i);
  2081. selectedPages.Add(targetIndex - i);
  2082. }
  2083. int newIndex = targetIndex;
  2084. //局部往前移动
  2085. for (j = i; j < pageIndexs.Count; j++)
  2086. {
  2087. result = MoveItemToIndex(pageIndexs[j], newIndex);
  2088. if (!result)
  2089. {
  2090. return;
  2091. }
  2092. SourceTargetValue.Add(pageIndexs[j], newIndex);
  2093. selectedPages.Add(newIndex + 1);
  2094. newIndex++;
  2095. }
  2096. }
  2097. //通知UI选中Items
  2098. //NotifyUIToRefresh(selectedPages);
  2099. //刷新页码和图片
  2100. ReloadAfterOption(true,true,new Tuple<int, int>(0,PDFViewer.Document.PageCount));
  2101. if (!IsFromUndoRedo)
  2102. {
  2103. //存入Undo栈
  2104. PageEditHistory history = new PageEditHistory();
  2105. history.Type = ActionType.DragSort;
  2106. history.SourceTargetValue = SourceTargetValue;
  2107. //用于Redo恢复
  2108. history.InsertIndex = targetIndex;
  2109. AddToUndoStack(history);
  2110. }
  2111. }
  2112. /// <summary>
  2113. /// 移动某个Item到指定位置
  2114. /// </summary>
  2115. private bool MoveItemToIndex(int sourceindex, int targetindex)
  2116. {
  2117. if (targetindex == sourceindex || targetindex < 0)
  2118. {
  2119. return false;
  2120. }
  2121. //文档层移动
  2122. var result = PDFViewer.Document.MovePage(sourceindex, targetindex);
  2123. if (!result)
  2124. {
  2125. return false;
  2126. }
  2127. //UI层移动
  2128. var source = PageEditItems[sourceindex];
  2129. PageEditItems.RemoveAt(sourceindex);
  2130. PageEditItems.Insert(targetindex, source);
  2131. return true;
  2132. }
  2133. /// <summary>
  2134. /// 从底层库获取对应页面的图片
  2135. /// </summary>
  2136. /// <param name="pageIndex"></param>
  2137. /// <param name="thumb"></param>
  2138. /// <param name="w"></param>
  2139. /// <param name="h"></param>
  2140. private void PDFViewer_OnThumbnailGenerated(int pageIndex, byte[] thumb, int w, int h)
  2141. {
  2142. try
  2143. {
  2144. if (PageEditItems.Count >= pageIndex + 1)
  2145. {
  2146. PixelFormat fmt = PixelFormats.Bgra32;
  2147. BitmapSource bps = BitmapSource.Create(w, h, 96.0, 96.0, fmt, null, thumb, (w * fmt.BitsPerPixel + 7) / 8);
  2148. PageEditItems[pageIndex].Image = bps;
  2149. PageEditItems[pageIndex].IsGetImage = true;
  2150. }
  2151. }
  2152. catch
  2153. {
  2154. }
  2155. }
  2156. #endregion
  2157. #region Navigate
  2158. public bool IsNavigationTarget(NavigationContext navigationContext)
  2159. {
  2160. return true;
  2161. }
  2162. public void OnNavigatedFrom(NavigationContext navigationContext)
  2163. {
  2164. }
  2165. /// <summary>
  2166. /// 从其他页面导航过来的时候会触发
  2167. /// 考虑只有在页面编辑的时候会进行页面的删减,可以尝试逻辑优化:仅第一次进入页面编辑时重新刷新页面
  2168. /// </summary>
  2169. /// <param name="navigationContext"></param>
  2170. public void OnNavigatedTo(NavigationContext navigationContext)
  2171. {
  2172. navigationContext.Parameters.TryGetValue<ViewContentViewModel>(ParameterNames.ViewContentViewModel, out viewContentViewModel);
  2173. navigationContext.Parameters.TryGetValue<CPDFViewer>(ParameterNames.PDFViewer, out PDFViewer);
  2174. bool isBOTA = false;
  2175. navigationContext.Parameters.TryGetValue<bool>(ParameterNames.BOTAThumb, out isBOTA);
  2176. if (PDFViewer != null)
  2177. {
  2178. if (isFirstLoad)
  2179. {
  2180. PDFViewer.OnThumbnailGenerated -= PDFViewer_OnThumbnailGenerated;
  2181. PDFViewer.OnThumbnailGenerated += PDFViewer_OnThumbnailGenerated;
  2182. PDFViewer.InfoChanged -= PDFViewer_InfoChanged;
  2183. PDFViewer.InfoChanged += PDFViewer_InfoChanged;
  2184. PDFViewer.AnnotEditHandler -= PDFViewer_AnnotEditHandler;
  2185. PDFViewer.AnnotEditHandler += PDFViewer_AnnotEditHandler;
  2186. ZoomIndex = 0;
  2187. if(viewContentViewModel!=null)
  2188. {
  2189. viewContentViewModel.PageEditUndo = Undo;
  2190. viewContentViewModel.PageEditRedo = Redo;
  2191. }
  2192. }
  2193. //BOTA缩略图时,显示不同的菜单栏
  2194. if(isBOTA)
  2195. {
  2196. IsBOTAThumb = Visibility.Visible;
  2197. }
  2198. else
  2199. {
  2200. IsBOTAThumb = Visibility.Collapsed;
  2201. }
  2202. GetSourceItems(isFirstLoad);
  2203. ListSelectedIndex = PDFViewer.CurrentIndex;
  2204. viewContentViewModel.CanUndo = this.CanUndo;
  2205. viewContentViewModel.CanRedo = this.CanRedo;
  2206. RefreshBookMarkList();
  2207. isFirstLoad = false;
  2208. }
  2209. }
  2210. private void PDFViewer_AnnotEditHandler(object sender, List<ComPDFKitViewer.AnnotEvent.AnnotEditEvent> e)
  2211. {
  2212. if (e != null && e.Count > 0)
  2213. {
  2214. int pageIndex = e[0].PageIndex;
  2215. RefreshItemImage(pageIndex, pageIndex);
  2216. }
  2217. }
  2218. private void PDFViewer_InfoChanged(object sender, KeyValuePair<string, object> e)
  2219. {
  2220. if(e.Key== "PageNum")
  2221. {
  2222. NotifyUIToRefresh(new List<int> { (e.Value as ComPDFKitViewer.RenderData).PageIndex});
  2223. }
  2224. }
  2225. #endregion
  2226. }
  2227. }