PageEditControl.xaml.cs 60 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656
  1. using ComPDFKitDemo.BOTA;
  2. using Microsoft.Win32;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Collections.ObjectModel;
  6. using System.Diagnostics;
  7. using System.Linq;
  8. using System.Threading.Tasks;
  9. using System.Windows;
  10. using System.Windows.Controls;
  11. using System.Windows.Controls.Primitives;
  12. using System.Windows.Input;
  13. using System.Windows.Media;
  14. using System.Windows.Media.Imaging;
  15. using ComPDFKit.PDFDocument;
  16. using ComPDFKitViewer.PdfViewer;
  17. namespace ComPDFKitDemo.PageEditor
  18. {
  19. public partial class PageEditControl : UserControl
  20. {
  21. public class DealPages
  22. {
  23. public List<ListBoxItem> Pages;
  24. public Option Op;
  25. public int[] OpInfo;
  26. }
  27. public enum Option
  28. {
  29. RightRotate,
  30. LeftRotate,
  31. Exchange,
  32. Insert,
  33. Reverser
  34. }
  35. internal static class Utils
  36. {
  37. public static T FindVisualParent<T>(DependencyObject obj) where T : class
  38. {
  39. while (obj != null)
  40. {
  41. if (obj is T)
  42. return obj as T;
  43. obj = VisualTreeHelper.GetParent(obj);
  44. }
  45. return null;
  46. }
  47. }
  48. public async void SetReadModeTip(bool show, string content, bool stayshow)
  49. {
  50. PageViewTipText.Text = content;
  51. if (show)
  52. {
  53. tip.Visibility = Visibility.Visible;
  54. tip.Opacity = 1;
  55. if (!stayshow)
  56. {
  57. await Task.Delay(1000);
  58. for (double i = 1; i > 0; i -= 0.05)
  59. {
  60. await Task.Delay(100);
  61. tip.Opacity = i;
  62. }
  63. tip.Visibility = Visibility.Collapsed;
  64. }
  65. }
  66. else
  67. tip.Visibility = Visibility.Collapsed;
  68. }
  69. public Stack<DealPages> UndoStack = new Stack<DealPages>();
  70. public ObservableCollection<ListBoxItem> BindPageList = new ObservableCollection<ListBoxItem>();
  71. public bool isInitialized = false;
  72. private const int THUMBNAIL_WIDTH = 150;
  73. private const int THUMBNAIL_HEIGHT = 150;
  74. private bool isSelectionChangeProgrammatic = false;
  75. private CPDFViewer pdfViewer;
  76. private bool IsModefied = false;
  77. private List<int> PageThumbnailsToRequest = new List<int>();
  78. private List<int> VisiblePageIndexes = new List<int>();
  79. private int zoomLevel = 2;
  80. private bool isZooming = false;
  81. private int[] thumbnailSize = {100, 150, 200, 300, 500 };
  82. private ListBoxItem TempItem;
  83. private bool isFrontHalf = false;
  84. private bool isDraging = false;
  85. private bool isDragingEnter = false;
  86. public event RoutedEventHandler DragAddTab;
  87. public PageEditControl()
  88. {
  89. InitializeComponent();
  90. }
  91. private void CommandBinding_Executed_LeftRotate(object sender, ExecutedRoutedEventArgs e)
  92. {
  93. DoRotate(-90);
  94. }
  95. private void CommandBinding_Executed_RightRotate(object sender, ExecutedRoutedEventArgs e)
  96. {
  97. DoRotate(90);
  98. }
  99. private void CommandBinding_Executed_Save(object sender, ExecutedRoutedEventArgs e)
  100. {
  101. DoSave();
  102. UndoStack.Clear();
  103. }
  104. private void CommandBinding_Executed_Delete(object sender, ExecutedRoutedEventArgs e)
  105. {
  106. var list = GetListFromSelectedItems();
  107. DoDelete(list,true);
  108. UndoStack.Clear();
  109. }
  110. private void CommandBinding_Executed_Copy(object sender, ExecutedRoutedEventArgs e)
  111. {
  112. DoCopy();
  113. }
  114. private void CommandBinding_Executed_Paste(object sender, ExecutedRoutedEventArgs e)
  115. {
  116. DoPaste();
  117. }
  118. private void CommandBinding_Executed_Revoke(object sender, ExecutedRoutedEventArgs e)
  119. {
  120. if(UndoStack.Count>0)
  121. {
  122. var pages = UndoStack.Pop();
  123. Undo(pages);
  124. }
  125. }
  126. private void PdfViewer_InfoChanged(object sender, KeyValuePair<string, object> e)
  127. {
  128. if (e.Key == "RenderNum")
  129. {
  130. isSelectionChangeProgrammatic = true;
  131. UpdateSelectedIndex();
  132. isSelectionChangeProgrammatic = false;
  133. }
  134. }
  135. private void _pdfviewer_OnThumbnailGenerated(int pageIndex, byte[] thumb, int w, int h)
  136. {
  137. try
  138. {
  139. if (PageEditListBox.Items.IsEmpty)
  140. {
  141. return;
  142. }
  143. ScrollViewer sv = GetScrollHost(PageEditListBox);
  144. ListBoxItem item = PageEditListBox.Items[pageIndex] as ListBoxItem;
  145. ListBoxItem listboxitem = PageEditListBox.ItemContainerGenerator.ContainerFromIndex(pageIndex) as ListBoxItem;
  146. if (ViewportHelper.IsInViewport(sv, listboxitem))
  147. {
  148. Debug.WriteLine("Got thumbnail for page {0}. It is visible, so adding thumb", pageIndex);
  149. PixelFormat fmt = PixelFormats.Bgra32;
  150. BitmapSource bps = BitmapSource.Create(w, h, 96.0, 96.0, fmt, null, thumb, (w * fmt.BitsPerPixel + 7) / 8);
  151. Image image = GetImageElement(PageEditListBox.Items[pageIndex] as ListBoxItem);
  152. image.Source = bps;
  153. }
  154. else
  155. {
  156. Debug.WriteLine("Got thumbnail for page {0}. It is NOT visible, so ignoring thumb", pageIndex);
  157. }
  158. }
  159. catch (Exception ex)
  160. {
  161. Debug.WriteLine(ex.ToString());
  162. }
  163. }
  164. private void UserControl_Loaded(object sender, RoutedEventArgs e)
  165. {
  166. PageEditListBox.Focus();
  167. if (PageEditListBox.HasItems)
  168. {
  169. PageEditListBox.ScrollIntoView(PageEditListBox.Items[pdfViewer.CurrentIndex < 0 ? 0 : pdfViewer.CurrentIndex]);
  170. PageEditListBox.SelectedIndex = pdfViewer.CurrentIndex;
  171. }
  172. }
  173. private void UserControl_Unloaded(object sender, RoutedEventArgs e)
  174. {
  175. if (IsModefied)
  176. {
  177. var result = MessageBox.Show("The document has not been saved. Do you want to save it?", null, MessageBoxButton.YesNoCancel);
  178. if (result == MessageBoxResult.Yes)
  179. {
  180. DoSave();
  181. }
  182. }
  183. }
  184. private void UserControl_PreviewMouseWheel(object sender, MouseWheelEventArgs e)
  185. {
  186. if (Keyboard.IsKeyDown(Key.LeftCtrl))
  187. {
  188. int oldZoomLevel = zoomLevel;
  189. if (e.Delta < 0)
  190. {
  191. if (zoomLevel > 0)
  192. zoomLevel--;
  193. }
  194. else
  195. {
  196. if (zoomLevel < thumbnailSize.Length - 1)
  197. zoomLevel++;
  198. }
  199. if (zoomLevel != oldZoomLevel)
  200. {
  201. isZooming = true;
  202. PopulateThumbnailList();
  203. PageEditListBox.ScrollIntoView(PageEditListBox.Items[pdfViewer.CurrentIndex]);
  204. PageEditListBox.SelectedIndex = pdfViewer.CurrentIndex;
  205. isZooming = false;
  206. }
  207. }
  208. }
  209. private async void PageEditListBox_ScrollChanged(object sender, ScrollChangedEventArgs e)
  210. {
  211. if (NeedScroll)
  212. {
  213. await Task.Delay(500);
  214. var scroller = GetScrollHost(PageEditListBox);
  215. var v = scroller.VerticalOffset;
  216. scroller.ScrollToVerticalOffset(v + Speed);
  217. return;
  218. }
  219. if (scrollType != ScrollEventType.EndScroll || isZooming)
  220. return;
  221. ItemsInViewHitTest();
  222. }
  223. private void PageEditListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
  224. {
  225. }
  226. private ScrollEventType scrollType = ScrollEventType.EndScroll;
  227. private void PageEditListBox_Scroll(object sender, System.Windows.Controls.Primitives.ScrollEventArgs e)
  228. {
  229. scrollType = e.ScrollEventType;
  230. if (scrollType != ScrollEventType.EndScroll || isZooming)
  231. return;
  232. ItemsInViewHitTest();
  233. }
  234. private bool IskeyDown = false;
  235. private void PageEditListBox_KeyUp(object sender, KeyEventArgs e)
  236. {
  237. if (e.Key == Key.LeftShift || e.Key == Key.LeftCtrl)
  238. {
  239. IskeyDown = true;
  240. return;
  241. }
  242. }
  243. private Point startPostion = new Point();
  244. private void PageEditListBox_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
  245. {
  246. NeedScroll = false;
  247. var pos = e.GetPosition(PageEditListBox);
  248. HitTestResult result = VisualTreeHelper.HitTest(PageEditListBox, pos);
  249. if (result == null)
  250. {
  251. return;
  252. }
  253. var listBoxItem = Utils.FindVisualParent<ListBoxItem>(result.VisualHit);
  254. var scroller = Utils.FindVisualParent<ScrollBar>(result.VisualHit);
  255. if (listBoxItem == null)
  256. {
  257. if (scroller != null)
  258. {
  259. startchoose = false;
  260. return;
  261. }
  262. startchoose = true;
  263. PageEditListBox.SelectedItems.Clear();
  264. startPostion = e.GetPosition(PageEditListBox);
  265. startPostion = new Point(startPostion.X,startPostion.Y+GetScrollHost(PageEditListBox).VerticalOffset);
  266. IskeyDown = false;
  267. Mouse.Capture(PageEditListBox);
  268. return;
  269. }
  270. startchoose = false;
  271. if (listBoxItem.IsSelected == true && !Keyboard.IsKeyDown(Key.LeftCtrl))
  272. {
  273. e.Handled = true;
  274. }
  275. }
  276. private void PageEditListBox_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
  277. {
  278. ChooseRect.Visibility = Visibility.Collapsed;
  279. var pos = e.GetPosition(PageEditListBox);
  280. HitTestResult result = VisualTreeHelper.HitTest(PageEditListBox, pos);
  281. if (result == null)
  282. {
  283. return;
  284. }
  285. var listBoxItem = Utils.FindVisualParent<ListBoxItem>(result.VisualHit);
  286. if (listBoxItem == null)
  287. {
  288. return;
  289. }
  290. if (IskeyDown && !Keyboard.IsKeyDown(Key.LeftCtrl)&&!Keyboard.IsKeyDown(Key.LeftShift))
  291. {
  292. IskeyDown = false;
  293. PageEditListBox.SelectedItems.Clear();
  294. PageEditListBox.SelectedItem = listBoxItem;
  295. listBoxItem.IsSelected = true;
  296. return;
  297. }
  298. }
  299. private void PageEditListBox_Drop(object sender, DragEventArgs e)
  300. {
  301. NeedScroll = false;
  302. if (!isDraging)
  303. {
  304. MidLane.Visibility = Visibility.Collapsed;
  305. return;
  306. }
  307. if (isDragingEnter)
  308. {
  309. CPDFDocument dragDoc = CPDFDocument.InitWithFilePath(dragingEnterPath);
  310. if (dragingEnterPath.Substring(dragingEnterPath.LastIndexOf(@".")).ToLower() == ".pdf")
  311. {
  312. int index = InsertIndex == -1 ? 0 : InsertIndex;
  313. pdfViewer.Document.ImportPagesAtIndex(dragDoc, "1-" + dragDoc.PageCount, index);
  314. PopulateThumbnailList();
  315. ItemsInViewHitTest();
  316. }
  317. else if (!string.IsNullOrEmpty(dragingEnterPath))
  318. DragAddTab.Invoke(dragingEnterPath, new RoutedEventArgs());
  319. MidLane.Visibility = Visibility.Collapsed;
  320. isDragingEnter = false;
  321. dragingEnterPath = null;
  322. return;
  323. }
  324. var pos = e.GetPosition(PageEditListBox);
  325. var result = VisualTreeHelper.HitTest(PageEditListBox, pos);
  326. if (result == null)
  327. {
  328. MidLane.Visibility = Visibility.Collapsed;
  329. isDraging = false;
  330. return;
  331. }
  332. var sourcePerson = e.Data.GetData(typeof(StackPanel)) as StackPanel;
  333. if (sourcePerson == null)
  334. {
  335. MidLane.Visibility = Visibility.Collapsed;
  336. isDraging = false;
  337. return;
  338. }
  339. int targetindex = 0;
  340. if (InsertIndex != -1)
  341. {
  342. targetindex = InsertIndex;
  343. }
  344. else
  345. {
  346. var listBoxItem = Utils.FindVisualParent<ListBoxItem>(result.VisualHit);
  347. if (listBoxItem == null)
  348. {
  349. MidLane.Visibility = Visibility.Collapsed;
  350. isDraging = false;
  351. return;
  352. }
  353. var targetPerson = listBoxItem;
  354. targetPerson.Opacity = 1;
  355. sourcePerson.Opacity = 1;
  356. if (ReferenceEquals(targetPerson, sourcePerson))
  357. {
  358. MidLane.Visibility = Visibility.Collapsed;
  359. isDraging = false;
  360. return;
  361. }
  362. targetindex = PageEditListBox.Items.IndexOf(targetPerson);
  363. }
  364. List<ListBoxItem> list = new List<ListBoxItem>();
  365. List<int> sourceindex = new List<int>();
  366. List<int> pages = new List<int>();
  367. for (int i = 0; i < PageEditListBox.SelectedItems.Count; i++)
  368. {
  369. var pageindex = PageEditListBox.Items.IndexOf(PageEditListBox.SelectedItems[i] as ListBoxItem);
  370. pages.Add(pageindex);
  371. }
  372. pages.Sort();
  373. if (targetindex <= pages[0])
  374. {
  375. sourceindex.Add(-1);
  376. list = new List<ListBoxItem>();
  377. for (int i = 0; i < pages.Count; i++)
  378. {
  379. list.Add(PageEditListBox.Items[pages[i]] as ListBoxItem);
  380. sourceindex.Add(pages[i]);
  381. DragToSort(pages[i], targetindex + i);
  382. }
  383. }
  384. else if (targetindex >= pages[pages.Count - 1])
  385. {
  386. sourceindex.Add(1);
  387. list = new List<ListBoxItem>();
  388. for (int i = 0; i < pages.Count; i++)
  389. {
  390. list.Add(PageEditListBox.Items[pages[pages.Count - 1 - i]] as ListBoxItem);
  391. sourceindex.Add(pages[pages.Count-1-i]);
  392. DragToSort(pages[pages.Count - 1 - i], targetindex - 1 - i);
  393. }
  394. }
  395. else
  396. {
  397. int i, j, k;
  398. for (k = 0; k < pages.Count - 1; k++)
  399. {
  400. if (pages[k] < targetindex && pages[k + 1] >= targetindex)
  401. break;
  402. }
  403. sourceindex.Add(0);
  404. list = new List<ListBoxItem>();
  405. for (i = 0; i <= k; i++)
  406. {
  407. list.Add(PageEditListBox.Items[pages[k - i]] as ListBoxItem);
  408. sourceindex.Add(pages[k - i]);
  409. DragToSort(pages[k - i], targetindex - 1 - i);
  410. }
  411. for (j = i; j < pages.Count; j++)
  412. {
  413. list.Add(PageEditListBox.Items[pages[j]] as ListBoxItem);
  414. sourceindex.Add(pages[j]);
  415. DragToSort(pages[j], targetindex);
  416. targetindex++;
  417. }
  418. sourceindex.Add(k);
  419. }
  420. DealPages dealPages = new DealPages()
  421. {
  422. Pages = list,
  423. Op = Option.Exchange,
  424. OpInfo = sourceindex.ToArray()
  425. };
  426. UndoStack.Push(dealPages);
  427. isDraging = false;
  428. }
  429. private void MidLane_Drop(object sender, DragEventArgs e)
  430. {
  431. MidLane.Visibility = Visibility.Collapsed;
  432. this.PageEditListBox_Drop(sender, e);
  433. }
  434. private bool startchoose = false;
  435. private void PageEditListBox_PreviewMouseMove(object sender, MouseEventArgs e)
  436. {
  437. try
  438. {
  439. if (e.LeftButton == MouseButtonState.Pressed)
  440. {
  441. if (startchoose)
  442. {
  443. var s = GetScrollHost(PageEditListBox);
  444. Point start = new Point();
  445. start = new Point(startPostion.X, startPostion.Y - s.VerticalOffset);
  446. var rec = new Rect(start, e.GetPosition(PageEditListBox));
  447. ChooseRect.Margin = new Thickness(rec.Left, rec.Top, 0, 0);
  448. ChooseRect.Width = rec.Width;
  449. ChooseRect.Height = rec.Height;
  450. ChooseRect.Visibility = Visibility.Visible;
  451. var item = PageEditListBox.Items[0] as ListBoxItem;
  452. var rang = GetRoughViewportRange(PageEditListBox, item.DesiredSize, item.Margin);
  453. var scroller = GetScrollHost(PageEditListBox);
  454. for (int i =0; i <= PageEditListBox.Items.Count; i++)
  455. {
  456. var _item = PageEditListBox.Items[i] as ListBoxItem;
  457. var v = VisualTreeHelper.GetOffset(_item);
  458. if (rec.IntersectsWith(new Rect(v.X, v.Y - scroller.VerticalOffset, _item.ActualWidth, _item.ActualHeight)))
  459. PageEditListBox.SelectedItems.Add(_item);
  460. else
  461. PageEditListBox.SelectedItems.Remove(_item);
  462. }
  463. return;
  464. }
  465. var pos = e.GetPosition(PageEditListBox);
  466. if (pos.Y < 0 || pos.Y > PageEditListBox.ActualHeight)
  467. {
  468. MidLane.Visibility = Visibility.Collapsed;
  469. return;
  470. }
  471. HitTestResult result = VisualTreeHelper.HitTest(PageEditListBox, pos);
  472. if (result == null)
  473. {
  474. return;
  475. }
  476. var listBoxItem = Utils.FindVisualParent<ListBoxItem>(result.VisualHit);
  477. if (listBoxItem == null)
  478. {
  479. return;
  480. }
  481. isDragingEnter = false;
  482. TempItem = listBoxItem;
  483. var panel = GetPanel(TempItem);
  484. var item_pos = e.GetPosition(panel);
  485. if (item_pos != null)
  486. {
  487. item_x = item_pos.X;
  488. item_y = item_pos.Y;
  489. }
  490. var scroll = GetScrollHost(PageEditListBox);
  491. DataObject dataObj = new DataObject(listBoxItem.Content as StackPanel);
  492. DragDrop.DoDragDrop(PageEditListBox, dataObj, DragDropEffects.Move);
  493. Mouse.Capture(PageEditListBox);
  494. return;
  495. }
  496. ChooseRect.Visibility = Visibility.Collapsed;
  497. IskeyDown = true;
  498. Mouse.Capture(null);
  499. }
  500. catch (Exception ex)
  501. {
  502. }
  503. }
  504. private bool NeedScroll = false;
  505. private int Speed = 0;
  506. private double item_x;
  507. private double item_y;
  508. private int InsertIndex = -1;
  509. private void Grid_DragOver(object sender, DragEventArgs e)
  510. {
  511. if (startchoose)
  512. {
  513. return;
  514. }
  515. try
  516. {
  517. if (e.KeyStates == (DragDropKeyStates.ControlKey | DragDropKeyStates.LeftMouseButton) || e.KeyStates == (DragDropKeyStates.ShiftKey | DragDropKeyStates.LeftMouseButton | DragDropKeyStates.ControlKey))
  518. return;
  519. var pos = e.GetPosition(PageEditListBox);
  520. var result = VisualTreeHelper.HitTest(PageEditListBox, pos);
  521. if (result == null)
  522. {
  523. }
  524. var listBoxItem = Utils.FindVisualParent<ListBoxItem>(result.VisualHit);
  525. if (listBoxItem == null)
  526. {
  527. }
  528. double xPos, yPos;
  529. if (!isDragingEnter)
  530. {
  531. Image image = GetImageElement(TempItem);
  532. Viewbox viewBox = (TempItem.Content as StackPanel).Children[0] as Viewbox;
  533. ShadowPicture.Width = viewBox.ActualWidth;
  534. ShadowPicture.Height = viewBox.ActualHeight;
  535. ShadowPicture.Source = image.Source;
  536. xPos = e.GetPosition(PageEditListBox).X - item_x;
  537. yPos = e.GetPosition(PageEditListBox).Y - item_y;
  538. }
  539. else
  540. {
  541. var pic = ToBitmapSource(dragingEnterPath);
  542. ShadowPicture.Width = pic.Width;
  543. ShadowPicture.Height = pic.Height;
  544. ShadowPicture.Source = pic;
  545. xPos = e.GetPosition(PageEditListBox).X - pic.Width / 2;
  546. yPos = e.GetPosition(PageEditListBox).Y - pic.Height / 2;
  547. }
  548. ShadowPicture.Margin = new Thickness(xPos, yPos, 0, 0);
  549. var scroll = GetScrollHost(PageEditListBox);
  550. if (listBoxItem != null)
  551. {
  552. var p = VisualTreeHelper.GetOffset(listBoxItem);
  553. MidLane.Visibility = Visibility.Visible;
  554. MidLane.X2 = MidLane.X1 = p.X + 10 + listBoxItem.ActualWidth;
  555. if (pos.X < p.X + 10 + listBoxItem.ActualWidth / 2)
  556. {
  557. isFrontHalf = true;
  558. MidLane.X2 = MidLane.X1 = p.X;
  559. InsertIndex = PageEditListBox.Items.IndexOf(listBoxItem);
  560. }
  561. else
  562. {
  563. isFrontHalf = false;
  564. InsertIndex = PageEditListBox.Items.IndexOf(listBoxItem) + 1;
  565. }
  566. MidLane.Y1 = p.Y;
  567. if (MidLane.Y1 < 0)
  568. MidLane.Y1 = 0;
  569. MidLane.Y2 = p.Y + listBoxItem.ActualHeight;
  570. if (MidLane.Y2 < 0)
  571. {
  572. MidLane.Y2 = 0;
  573. }
  574. }
  575. if (pos.Y <= 30 || pos.Y >= PageEditListBox.ActualHeight - 10)
  576. {
  577. MidLane.Visibility = Visibility.Collapsed;
  578. NeedScroll = false;
  579. }
  580. if (pos.X <= 40 || pos.X >= scroll.ViewportWidth - 50)
  581. {
  582. MidLane.Visibility = Visibility.Collapsed;
  583. NeedScroll = false;
  584. }
  585. Speed = 0;
  586. if (pos.Y >= PageEditListBox.ActualHeight - 30)
  587. {
  588. Speed = 30 - (int)(PageEditListBox.ActualHeight - pos.Y);
  589. NeedScroll = true;
  590. }
  591. else if (pos.Y <= 30)
  592. {
  593. Speed = (int)(pos.Y - 30);
  594. NeedScroll = true;
  595. }
  596. else
  597. NeedScroll = false;
  598. var v = scroll.VerticalOffset;
  599. scroll.ScrollToVerticalOffset(v + Speed);
  600. }
  601. catch (Exception ex)
  602. {
  603. }
  604. }
  605. private void ShadowPicture_Drop(object sender, DragEventArgs e)
  606. {
  607. this.PageEditListBox_Drop(sender, e);
  608. }
  609. private void ListBoxItem_DragLeave(object sender, DragEventArgs e)
  610. {
  611. isDraging = true;
  612. }
  613. private void Save_Click(object sender, RoutedEventArgs e)
  614. {
  615. DoSave();
  616. UndoStack.Clear();
  617. }
  618. private void Delete_Click(object sender, RoutedEventArgs e)
  619. {
  620. var list = GetListFromSelectedItems();
  621. DoDelete(list, true);
  622. UndoStack.Clear();
  623. }
  624. private void Rotate_Click(object sender, RoutedEventArgs e)
  625. {
  626. var item = sender as MenuItem;
  627. double step = 90;
  628. if (item.Name == "LeftRotate")
  629. step = -90;
  630. else
  631. step = 90;
  632. DoRotate(step);
  633. }
  634. private void Exchange_Click(object sender, RoutedEventArgs e)
  635. {
  636. List<ListBoxItem> list = new List<ListBoxItem>();
  637. list = GetListFromSelectedItems();
  638. DoExchange(list);
  639. DealPages pages = new DealPages()
  640. {
  641. Pages = list,
  642. Op = Option.Reverser
  643. };
  644. UndoStack.Push(pages);
  645. }
  646. private void ListBoxItem_PreviewMouseDoubleClick(object sender, MouseButtonEventArgs e)
  647. {
  648. e.GetPosition(PageEditListBox);
  649. var pos = e.GetPosition(PageEditListBox);
  650. HitTestResult result = VisualTreeHelper.HitTest(PageEditListBox, pos);
  651. if (result == null)
  652. {
  653. return;
  654. }
  655. var listBoxItem = Utils.FindVisualParent<ListBoxItem>(result.VisualHit);
  656. if (listBoxItem != null)
  657. {
  658. pdfViewer.GoToPage((int)listBoxItem.Tag);
  659. }
  660. this.Visibility = Visibility.Collapsed;
  661. }
  662. private void InsertBlank_Click(object sender, RoutedEventArgs e)
  663. {
  664. var send = sender as MenuItem;
  665. switch (send.Name)
  666. {
  667. case "InsertBlank":
  668. DoInsert("Blank");
  669. break;
  670. case "InsertFromPDF":
  671. var dialog = new OpenFileDialog();
  672. dialog.Multiselect = false;
  673. dialog.Filter = ComPDFKitDemo.Properties.Resources.OpenDialogFilter;
  674. if (dialog.ShowDialog() == true)
  675. {
  676. var index = PageEditListBox.Items.IndexOf(PageEditListBox.SelectedItem) + 1;
  677. DoAddFromOtherPdf(dialog.FileName, "all", index, 2);
  678. }
  679. break;
  680. default:
  681. break;
  682. }
  683. }
  684. private void Extract_Click(object sender, RoutedEventArgs e)
  685. {
  686. string page = PageEditListBox.SelectedItems.Count > 1 ? " pages " : " page ";
  687. SaveFileDialog save = new SaveFileDialog();
  688. save.FileName = pdfViewer.Document.FileName + page + GetPageParam() + " .pdf";
  689. if ((bool)save.ShowDialog())
  690. {
  691. DoExtract(save.FileName);
  692. }
  693. }
  694. private void Replace_Click(object sender, RoutedEventArgs e)
  695. {
  696. DoReplace();
  697. }
  698. private void Split_Click(object sender, RoutedEventArgs e)
  699. {
  700. }
  701. private void Paste_Click(object sender, RoutedEventArgs e)
  702. {
  703. DoPaste();
  704. }
  705. private void Copy_Click(object sender, RoutedEventArgs e)
  706. {
  707. DoCopy();
  708. }
  709. private void PageEditListBox_SizeChanged(object sender, SizeChangedEventArgs e)
  710. {
  711. PageEditListBox.ScrollIntoView(PageEditListBox.SelectedItem);
  712. }
  713. private void PageEditor_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
  714. {
  715. ListBoxItem item = PageEditListBox.Items[pdfViewer.CurrentIndex] as ListBoxItem;
  716. PageEditListBox.ScrollIntoView(PageEditListBox.SelectedItem);
  717. PageEditListBox.SelectedItem = item;
  718. }
  719. private async void ListBoxItem_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
  720. {
  721. var item = sender as ListBoxItem;
  722. Image img = GetImageElement(item);
  723. int itemindex = PageEditListBox.Items.IndexOf(item);
  724. if (img.Source == null)
  725. {
  726. await pdfViewer.GetThumbnail(itemindex, (int)img.Width, (int)img.Height);
  727. }
  728. }
  729. private String dragingEnterPath;
  730. private void PageGrid_PreviewDragEnter(object sender, DragEventArgs e)
  731. {
  732. var file = (System.Array)e.Data.GetData(DataFormats.FileDrop);
  733. if (file == null || file.Length > 1)
  734. { return; }
  735. foreach (var f in file)
  736. {
  737. dragingEnterPath = f.ToString();
  738. if (dragingEnterPath != null)
  739. {
  740. isDragingEnter = true;
  741. }
  742. }
  743. }
  744. private void ContextMenu_Loaded(object sender, RoutedEventArgs e)
  745. {
  746. if (App.CopyDoc == null)
  747. {
  748. var s = sender as ContextMenu;
  749. foreach (var item in s.Items)
  750. {
  751. if ((item as MenuItem).Name == "Paste")
  752. {
  753. (item as MenuItem).IsEnabled = false;
  754. }
  755. }
  756. }
  757. }
  758. #region Method
  759. public void Undo(DealPages dealPages)
  760. {
  761. var pages = dealPages.Pages;
  762. switch (dealPages.Op)
  763. {
  764. case Option.RightRotate:
  765. for (int i = 0; i < pages.Count; i++)
  766. {
  767. try
  768. {
  769. if(!PageEditListBox.Items.Contains(pages[i]))
  770. return;
  771. var image = GetImageElement(pages[i]);
  772. double angle = (double)image.LayoutTransform.GetValue(RotateTransform.AngleProperty);
  773. angle += -90;
  774. angle = angle % 360;
  775. image.LayoutTransform = new RotateTransform(angle, image.ActualWidth / 2, image.ActualHeight / 2);
  776. var index = PageEditListBox.Items.IndexOf(PageEditListBox.SelectedItems[i]);
  777. pdfViewer.Document.RotatePage(index, (int)-90 / 90);
  778. IsModefied = true;
  779. if (VisiblePageIndexes.Contains(index))
  780. VisiblePageIndexes.Remove(index);
  781. }
  782. catch(Exception ex)
  783. {
  784. }
  785. }
  786. ItemsInViewHitTest();
  787. break;
  788. case Option.LeftRotate:
  789. for (int i = 0; i < pages.Count; i++)
  790. {
  791. try
  792. {
  793. if (!PageEditListBox.Items.Contains(pages[i]))
  794. return;
  795. var image = GetImageElement(pages[i]);
  796. double angle = (double)image.LayoutTransform.GetValue(RotateTransform.AngleProperty);
  797. angle += 90;
  798. angle = angle % 360;
  799. image.LayoutTransform = new RotateTransform(angle, image.ActualWidth / 2, image.ActualHeight / 2);
  800. var index = PageEditListBox.Items.IndexOf(PageEditListBox.SelectedItems[i]);
  801. pdfViewer.Document.RotatePage(index, (int)90 / 90);
  802. IsModefied = true;
  803. if (VisiblePageIndexes.Contains(index))
  804. VisiblePageIndexes.Remove(index);
  805. }
  806. catch (Exception ex)
  807. {
  808. }
  809. }
  810. ItemsInViewHitTest();
  811. break;
  812. case Option.Exchange:
  813. UndoExchange(dealPages.Pages,dealPages.OpInfo.ToList());
  814. break;
  815. case Option.Insert:
  816. DoDelete(dealPages.Pages,false);
  817. break;
  818. case Option.Reverser:
  819. DoExchange(dealPages.Pages);
  820. break;
  821. default:
  822. break;
  823. }
  824. }
  825. private void UndoExchange(List<ListBoxItem> list,List<int>sourceindex)
  826. {
  827. int type = sourceindex[0];
  828. switch (type)
  829. {
  830. case -1:
  831. case 1:
  832. for (int i = 0; i < list.Count; i++)
  833. {
  834. int nowindex = PageEditListBox.Items.IndexOf(list[list.Count - 1 - i]);
  835. DragToSort(nowindex, sourceindex[sourceindex.Count - 1 - i]);
  836. }
  837. break;
  838. case 0:
  839. for (int i = 0; i < list.Count; i++)
  840. {
  841. int nowindex = PageEditListBox.Items.IndexOf(list[list.Count - 1 - i]);
  842. DragToSort(nowindex, sourceindex[sourceindex.Count - 2 - i]);
  843. }
  844. break;
  845. default:
  846. break;
  847. }
  848. }
  849. public void LoadThumbnails(CPDFViewer viewer)
  850. {
  851. if (viewer == null || viewer.Document == null)
  852. return;
  853. pdfViewer = viewer;
  854. if (!isInitialized)
  855. {
  856. this.PopulateThumbnailList();
  857. isInitialized = true;
  858. pdfViewer.OnThumbnailGenerated += _pdfviewer_OnThumbnailGenerated;
  859. }
  860. if(pdfViewer.CurrentIndex>=0)
  861. {
  862. PageEditListBox.ScrollIntoView(PageEditListBox.Items[pdfViewer.CurrentIndex]);
  863. (PageEditListBox.Items[pdfViewer.CurrentIndex] as ListBoxItem).IsSelected = true;
  864. }
  865. ItemsInViewHitTest();
  866. }
  867. public void PopulateThumbnailList()
  868. {
  869. PageEditListBox.Items.Clear();
  870. VisiblePageIndexes.Clear();
  871. BindPageList.Clear();
  872. GC.Collect();
  873. int thumbnailWidth = thumbnailSize[zoomLevel];
  874. for (int i = 0; i < pdfViewer.Document.PageCount; i++)
  875. {
  876. Size pageSize = pdfViewer.Document.GetPageSize(i);
  877. int imageWidth = pageSize.Width > pageSize.Height ? thumbnailWidth * 2 : (int)(pageSize.Width / pageSize.Height * thumbnailWidth * 2);
  878. int imageHeight = pageSize.Height > pageSize.Width ? thumbnailWidth * 2 : (int)(pageSize.Height / pageSize.Width * thumbnailWidth * 2);
  879. Image img = new Image()
  880. {
  881. Margin = new Thickness(0, 0, 5, 0),
  882. Width = imageWidth,
  883. Height = imageHeight,
  884. Stretch = Stretch.Uniform,
  885. };
  886. Border border = new Border()
  887. {
  888. BorderThickness = new Thickness(2),
  889. BorderBrush = Brushes.Black,
  890. Child = img,
  891. };
  892. Viewbox viewBox = new Viewbox()
  893. {
  894. Margin = new Thickness(0, 5, 0, 0),
  895. Stretch = System.Windows.Media.Stretch.Uniform,
  896. Width = thumbnailWidth,
  897. Height = thumbnailWidth,
  898. Child = border,
  899. };
  900. TextBlock text = new TextBlock()
  901. {
  902. HorizontalAlignment = System.Windows.HorizontalAlignment.Center,
  903. Text = (i + 1).ToString(),
  904. Foreground = Brushes.Black
  905. };
  906. StackPanel panel = new StackPanel();
  907. panel.Children.Add(viewBox);
  908. panel.Children.Add(text);
  909. ListBoxItem item = new ListBoxItem();
  910. item.Content = panel;
  911. item.Tag = i;
  912. item.Margin = new Thickness(5, 5, 5, 5);
  913. BindPageList.Add(item);
  914. }
  915. PageEditListBox.ItemsSource = BindPageList;
  916. }
  917. public ListBoxItem GetNewItem(int ItemIndex)
  918. {
  919. int thumbnailWidth = thumbnailSize[zoomLevel];
  920. Size pageSize = pdfViewer.Document.GetPageSize(ItemIndex);
  921. if(pageSize.Width==0||pageSize.Height==0)
  922. {
  923. pageSize = new Size(228,300);
  924. }
  925. int imageWidth = pageSize.Width > pageSize.Height ? thumbnailWidth * 2 : (int)(pageSize.Width / pageSize.Height * thumbnailWidth * 2);
  926. int imageHeight = pageSize.Height > pageSize.Width ? thumbnailWidth * 2 : (int)(pageSize.Height / pageSize.Width * thumbnailWidth * 2);
  927. Image img = new Image()
  928. {
  929. Margin = new Thickness(0, 0, 5, 0),
  930. Width = imageWidth,
  931. Height = imageHeight,
  932. Stretch = Stretch.Uniform,
  933. };
  934. Border border = new Border()
  935. {
  936. BorderThickness = new Thickness(2),
  937. BorderBrush = Brushes.Black,
  938. Child = img,
  939. };
  940. Viewbox viewBox = new Viewbox()
  941. {
  942. Margin = new Thickness(0, 5, 0, 0),
  943. Stretch = System.Windows.Media.Stretch.Uniform,
  944. Width = thumbnailWidth,
  945. Height = thumbnailWidth,
  946. Child = border,
  947. };
  948. TextBlock text = new TextBlock()
  949. {
  950. HorizontalAlignment = System.Windows.HorizontalAlignment.Center,
  951. Text = (ItemIndex + 1).ToString(),
  952. Foreground = Brushes.Black
  953. };
  954. StackPanel panel = new StackPanel();
  955. panel.Children.Add(viewBox);
  956. panel.Children.Add(text);
  957. ListBoxItem item = new ListBoxItem();
  958. item.Content = panel;
  959. item.Tag = ItemIndex;
  960. item.Margin = new Thickness(5, 5, 5, 5);
  961. return item;
  962. }
  963. public void AddBlankPages(int pagecount, int insertindex)
  964. {
  965. for (int i = 0; i < pagecount; i++)
  966. {
  967. var item = GetNewItem(insertindex + i);
  968. BindPageList.Insert(insertindex + i, item);
  969. if (VisiblePageIndexes.Contains(insertindex + i))
  970. VisiblePageIndexes.Remove(insertindex + i);
  971. }
  972. PageEditListBox.UpdateLayout();
  973. }
  974. private async void ItemsInViewHitTest()
  975. {
  976. try
  977. {
  978. ScrollViewer sv = GetScrollHost(PageEditListBox);
  979. if (sv == null) return;
  980. if (VisualTreeHelper.GetParent(this) == null)
  981. return;
  982. List<int> pagesOnScreen = new List<int>();
  983. PageThumbnailsToRequest.Clear();
  984. for (int i = 0; i < PageEditListBox.Items.Count; ++i)
  985. {
  986. ListBoxItem item = PageEditListBox.Items[i] as ListBoxItem;
  987. Image img = GetImageElement(item);
  988. if (ViewportHelper.IsInViewport(sv, item))
  989. {
  990. if (img.Source == null && !VisiblePageIndexes.Contains(i))
  991. {
  992. VisiblePageIndexes.Add(i);
  993. await pdfViewer.GetThumbnail(i, (int)img.Width, (int)img.Height);
  994. Debug.WriteLine("Page {0} is visible, asking for thumb", (i + 1));
  995. }
  996. else if (img.Source == null)
  997. {
  998. await pdfViewer.GetThumbnail(i, (int)img.Width, (int)img.Height);
  999. Debug.WriteLine("Page { 0} is visible, asking for thumb", (i + 1));
  1000. }
  1001. }
  1002. else
  1003. {
  1004. if (VisiblePageIndexes.Contains(i))
  1005. {
  1006. Image image = GetImageElement(PageEditListBox.Items[i] as ListBoxItem);
  1007. if (image.Source != null)
  1008. {
  1009. image.Source = null;
  1010. Debug.WriteLine("Page {0} is out of range, removed thumb", (i + 1));
  1011. }
  1012. else
  1013. {
  1014. Debug.WriteLine("Page {0} is out of range, but had no thumb", (i + 1));
  1015. }
  1016. VisiblePageIndexes.Remove(i);
  1017. }
  1018. }
  1019. }
  1020. }
  1021. catch (Exception ex)
  1022. {
  1023. Debug.WriteLine(ex.ToString());
  1024. }
  1025. }
  1026. private void UpdateSelectedIndex()
  1027. {
  1028. if (PageEditListBox.Items.Count == 0)
  1029. PageEditListBox.SelectedIndex = -1;
  1030. else if (PageEditListBox.Items.Count <= pdfViewer.CurrentIndex)
  1031. this.PageEditListBox.SelectedIndex = 0;
  1032. else if (PageEditListBox.SelectedIndex != pdfViewer.CurrentIndex)
  1033. PageEditListBox.SelectedIndex = pdfViewer.CurrentIndex;
  1034. }
  1035. private Image GetImageElement(ListBoxItem item)
  1036. {
  1037. Viewbox viewBox = (item.Content as StackPanel).Children[0] as Viewbox;
  1038. Image img = (viewBox.Child as Border).Child as Image;
  1039. return img;
  1040. }
  1041. private StackPanel GetPanel(ListBoxItem item)
  1042. {
  1043. StackPanel panel = item.Content as StackPanel;
  1044. return panel;
  1045. }
  1046. private TextBlock GetPageNumTextBlock(ListBoxItem item)
  1047. {
  1048. TextBlock text = (item.Content as StackPanel).Children[1] as TextBlock;
  1049. return text;
  1050. }
  1051. private ScrollViewer GetScrollHost(ListBox listBox)
  1052. {
  1053. if (VisualTreeHelper.GetChildrenCount(listBox) > 0)
  1054. {
  1055. Border border = VisualTreeHelper.GetChild(listBox, 0) as Border;
  1056. if (border != null)
  1057. {
  1058. return VisualTreeHelper.GetChild(border, 0) as ScrollViewer;
  1059. }
  1060. }
  1061. return null;
  1062. }
  1063. private void DragToSort(int sourceindex, int targetindex)
  1064. {
  1065. if (targetindex == sourceindex)
  1066. {
  1067. MidLane.Visibility = Visibility.Collapsed;
  1068. return;
  1069. }
  1070. var source = PageEditListBox.Items[sourceindex];
  1071. BindPageList.RemoveAt(sourceindex);
  1072. MidLane.Visibility = Visibility.Collapsed;
  1073. BindPageList.Insert(targetindex, source as ListBoxItem);
  1074. PageEditListBox.SelectedItems.Add(source);
  1075. var result = pdfViewer.Document.MovePage(sourceindex,targetindex);
  1076. if(!result)
  1077. {
  1078. throw new Exception();
  1079. }
  1080. IsModefied = true;
  1081. UpdateSortedPageNum(sourceindex,targetindex);
  1082. }
  1083. private void UpdateSortedPageNum(int sourceIndex,int targetIndex)
  1084. {
  1085. int sum = sourceIndex + targetIndex;
  1086. targetIndex = targetIndex > sourceIndex ? targetIndex : sourceIndex;
  1087. sourceIndex = sum - targetIndex;
  1088. sourceIndex = sourceIndex <= 0 ? 0 : sourceIndex;
  1089. targetIndex = targetIndex+1> PageEditListBox.Items.Count ? PageEditListBox.Items.Count-1:targetIndex;
  1090. for (int i = sourceIndex; i <= targetIndex; i++)
  1091. {
  1092. var item = PageEditListBox.Items[i] as ListBoxItem;
  1093. TextBlock pagenum = GetPageNumTextBlock(item);
  1094. pagenum.Text = (i + 1).ToString();
  1095. }
  1096. }
  1097. private void UpdateAllPageNum()
  1098. {
  1099. for(int i=0;i<PageEditListBox.Items.Count;i++)
  1100. {
  1101. var pagenum = GetPageNumTextBlock(PageEditListBox.Items[i] as ListBoxItem);
  1102. pagenum.Text = (i + 1).ToString();
  1103. }
  1104. }
  1105. private void DoSave()
  1106. {
  1107. if (pdfViewer.Document.IsLocked)
  1108. return;
  1109. var result = pdfViewer.Document.WriteToLoadedPath();
  1110. if (result)
  1111. {
  1112. IsModefied = false;
  1113. }
  1114. else
  1115. SetReadModeTip(true, "Failed to save the document. Please try again later", false);
  1116. }
  1117. private void DoInsert(string pagetype)
  1118. {
  1119. int insertIndex = 0;
  1120. if (PageEditListBox.SelectedItem == null || PageEditListBox.SelectedItems.Count == 0)
  1121. {
  1122. insertIndex = 0;
  1123. }
  1124. else
  1125. {
  1126. for (int i = 0; i < PageEditListBox.SelectedItems.Count; i++)
  1127. {
  1128. var pagenum = GetPageNumTextBlock(PageEditListBox.SelectedItems[i] as ListBoxItem);
  1129. int pageindex = Convert.ToInt32(pagenum.Text) - 1;
  1130. if (pageindex > insertIndex)
  1131. insertIndex = pageindex;
  1132. }
  1133. }
  1134. Viewbox box = ((PageEditListBox.Items[insertIndex] as ListBoxItem).Content as StackPanel).Children[0] as Viewbox;
  1135. ListBoxItem item = PageEditListBox.Items[insertIndex] as ListBoxItem;
  1136. switch (pagetype)
  1137. {
  1138. case "Blank":
  1139. pdfViewer.Document.InsertPage(insertIndex + 1,504, 661.4, null);
  1140. pdfViewer.ReloadDocument();
  1141. ListBoxItem listBoxItem = GetNewItem(insertIndex + 1);
  1142. BindPageList.Insert(insertIndex + 1, listBoxItem);
  1143. List<ListBoxItem> list = new List<ListBoxItem>();
  1144. list.Add(PageEditListBox.Items[insertIndex + 1] as ListBoxItem);
  1145. DealPages pages = new DealPages()
  1146. {
  1147. Pages = list,
  1148. Op = Option.Insert
  1149. };
  1150. UndoStack.Push(pages);
  1151. break;
  1152. default:
  1153. break;
  1154. }
  1155. ItemsInViewHitTest();
  1156. UpdateAllPageNum();
  1157. }
  1158. private void DoReplace()
  1159. {
  1160. OpenFileDialog dialog = new OpenFileDialog();
  1161. dialog.Multiselect = false;
  1162. dialog.Filter = ComPDFKitDemo.Properties.Resources.OpenDialogFilter;
  1163. if ((bool)dialog.ShowDialog())
  1164. {
  1165. CPDFDocument doc = CPDFDocument.InitWithFilePath(dialog.FileName);
  1166. int pagecount = doc.PageCount;
  1167. int insertindex = PageEditListBox.Items.IndexOf(PageEditListBox.SelectedItem);
  1168. if (insertindex == -1)
  1169. insertindex = 0;
  1170. pdfViewer.Document.ImportPagesAtIndex(doc, "1-" + pagecount, insertindex);
  1171. doc.Release();
  1172. for (int i = 0; i < pagecount; i++)
  1173. {
  1174. var item = GetNewItem(insertindex + i);
  1175. BindPageList.Insert(insertindex + i, item);
  1176. if (VisiblePageIndexes.Contains(insertindex + i))
  1177. VisiblePageIndexes.Remove(insertindex + i);
  1178. }
  1179. IsModefied = true;
  1180. ItemsInViewHitTest();
  1181. var list = GetListFromSelectedItems();
  1182. DoDelete(list,false);
  1183. UpdateAllPageNum();
  1184. }
  1185. }
  1186. private void DoRotate(double angleStep)
  1187. {
  1188. List<ListBoxItem> pages = new List<ListBoxItem>();
  1189. for (int i = 0; i < PageEditListBox.SelectedItems.Count; i++)
  1190. {
  1191. var image = GetImageElement(PageEditListBox.SelectedItems[i] as ListBoxItem);
  1192. pages.Add(PageEditListBox.SelectedItems[i] as ListBoxItem);
  1193. double angle = (double)image.LayoutTransform.GetValue(RotateTransform.AngleProperty);
  1194. angle += angleStep;
  1195. angle = angle % 360;
  1196. image.LayoutTransform = new RotateTransform(angle, image.ActualWidth / 2, image.ActualHeight / 2);
  1197. var index = PageEditListBox.Items.IndexOf(PageEditListBox.SelectedItems[i]);
  1198. pdfViewer.Document.RotatePage(index, (int)angleStep/90);
  1199. pdfViewer.Document.ReleasePages(index);
  1200. IsModefied = true;
  1201. if (VisiblePageIndexes.Contains(index))
  1202. VisiblePageIndexes.Remove(index);
  1203. }
  1204. pdfViewer.ReloadDocument();
  1205. DealPages dealPages = new DealPages() {
  1206. Pages = pages,
  1207. Op=angleStep>0?Option.RightRotate:Option.LeftRotate
  1208. };
  1209. UndoStack.Push(dealPages);
  1210. ItemsInViewHitTest();
  1211. }
  1212. private void DoExtract(string path)
  1213. {
  1214. CPDFDocument savedoc = CPDFDocument.CreateDocument();
  1215. string pagerange = GetPageParam();
  1216. bool result = savedoc.ImportPages(pdfViewer.Document, pagerange);
  1217. if (!result)
  1218. {
  1219. SetReadModeTip(true, "Extraction exception, please try again later", false);
  1220. }
  1221. result = savedoc.WriteToFilePath(path);
  1222. if (!result)
  1223. {
  1224. SetReadModeTip(true, "Save exception, please try again later", false);
  1225. }
  1226. IsModefied = true;
  1227. savedoc.Release();
  1228. }
  1229. private void DoPaste()
  1230. {
  1231. if (App.CopyDoc == null)
  1232. {
  1233. SetReadModeTip(true, "Please copy the page first", false);
  1234. }
  1235. int insertindex = PageEditListBox.Items.IndexOf(PageEditListBox.SelectedItem) + 1;
  1236. int pagecount = App.CopyDoc.PageCount;
  1237. bool result = pdfViewer.Document.ImportPagesAtIndex(App.CopyDoc, "1-" + pagecount, insertindex);
  1238. if (!result)
  1239. {
  1240. SetReadModeTip(true, "Replication failed. Please try again later", false);
  1241. return;
  1242. }
  1243. pdfViewer.ReloadDocument();
  1244. AddBlankPages(pagecount, insertindex);
  1245. IsModefied = true;
  1246. ItemsInViewHitTest();
  1247. List<ListBoxItem> pageList = new List<ListBoxItem>();
  1248. for (int i = 0; i < pagecount; i++)
  1249. {
  1250. pageList.Add(PageEditListBox.Items[insertindex + i] as ListBoxItem);
  1251. }
  1252. DealPages dealPages = new DealPages()
  1253. {
  1254. Pages = pageList,
  1255. Op = Option.Insert
  1256. };
  1257. UndoStack.Push(dealPages);
  1258. UpdateAllPageNum();
  1259. }
  1260. private void DoCopy()
  1261. {
  1262. App.CopyDoc = null;
  1263. App.CopyDoc = CPDFDocument.CreateDocument();
  1264. string pageparm = GetPageParam();
  1265. bool result = App.CopyDoc.ImportPages(pdfViewer.Document, pageparm);
  1266. if (!result)
  1267. {
  1268. SetReadModeTip(true, "Replication failed. Please try again later", false);
  1269. return;
  1270. }
  1271. }
  1272. private void DoExchange(List<ListBoxItem> pageLists)
  1273. {
  1274. if (pageLists.Count <= 1)
  1275. {
  1276. SetReadModeTip(true, "Select multiple pages for operation", false);
  1277. return;
  1278. }
  1279. List<int> pages = new List<int>();
  1280. for (int i = 0; i < pageLists.Count; i++)
  1281. {
  1282. int pageIndex = PageEditListBox.Items.IndexOf(pageLists[i] as ListBoxItem);
  1283. pages.Add(pageIndex);
  1284. }
  1285. pages.Sort();
  1286. for (int i = 0; i < pages.Count; i++)
  1287. {
  1288. int preindex = pages[i];
  1289. int laterIndex = pages[pages.Count - i - 1];
  1290. if (laterIndex <= preindex)
  1291. return;
  1292. var sourceitem = PageEditListBox.Items[preindex] as ListBoxItem;
  1293. var targetitem = PageEditListBox.Items[laterIndex] as ListBoxItem;
  1294. BindPageList.Remove(sourceitem);
  1295. BindPageList.Remove(targetitem);
  1296. BindPageList.Insert(preindex, targetitem);
  1297. BindPageList.Insert(laterIndex, sourceitem);
  1298. pdfViewer.Document.ExchangePage(preindex, laterIndex);
  1299. IsModefied = true;
  1300. PageEditListBox.SelectedItems.Add(targetitem);
  1301. PageEditListBox.SelectedItems.Add(sourceitem);
  1302. }
  1303. pdfViewer.ReloadDocument();
  1304. }
  1305. private void DoDelete(List<ListBoxItem> pageLists,bool tip)
  1306. {
  1307. if (pageLists.Count == PageEditListBox.Items.Count)
  1308. {
  1309. SetReadModeTip(true, "Unable to delete all pages, need to keep at least one!", false);
  1310. return;
  1311. }
  1312. MessageBoxResult result = MessageBoxResult.OK;
  1313. if (tip)
  1314. {
  1315. result = MessageBox.Show("Are you sure you want to delete the selected page?", null, MessageBoxButton.OKCancel);
  1316. }
  1317. if (result == MessageBoxResult.OK || !tip)
  1318. {
  1319. List<int> pages = new List<int>();
  1320. for (int i = 0; i < pageLists.Count; i++)
  1321. {
  1322. var index = PageEditListBox.Items.IndexOf(pageLists[i]);
  1323. pages.Add(index);
  1324. }
  1325. pages.Sort();
  1326. for (int i = pages.Count - 1; i >= 0; i--)
  1327. {
  1328. BindPageList.RemoveAt(pages[i]);
  1329. }
  1330. var r = pdfViewer.Document.RemovePages(pages.ToArray());
  1331. if (!r)
  1332. {
  1333. SetReadModeTip(true, "The deletion fails because the operation is abnormal. Please try again later!", false);
  1334. return;
  1335. }
  1336. pdfViewer.ReloadDocument();
  1337. IsModefied = true;
  1338. UpdateAllPageNum();
  1339. }
  1340. }
  1341. private List<ListBoxItem> GetListFromSelectedItems()
  1342. {
  1343. List<ListBoxItem> itemlists = new List<ListBoxItem>();
  1344. for(int i=0;i<PageEditListBox.SelectedItems.Count;i++)
  1345. {
  1346. itemlists.Add(PageEditListBox.SelectedItems[i] as ListBoxItem);
  1347. }
  1348. return itemlists;
  1349. }
  1350. private void DoAddFromOtherPdf(string filepath, string pagerange, int insertindex, int pagecount)
  1351. {
  1352. CPDFDocument doc = CPDFDocument.InitWithFilePath(filepath);
  1353. if (doc.IsEncrypted == true)
  1354. {
  1355. }
  1356. if(pagerange.ToLower()=="all")
  1357. {
  1358. pagecount = doc.PageCount;
  1359. pagerange = "1-" + pagecount;
  1360. }
  1361. var result = pdfViewer.Document.ImportPagesAtIndex(doc,pagerange,insertindex);
  1362. if(!result)
  1363. {
  1364. SetReadModeTip(true, "Insert failed. Please try again later.", false);
  1365. return;
  1366. }
  1367. doc.Release();
  1368. pdfViewer.ReloadDocument();
  1369. AddBlankPages(pagecount, insertindex);
  1370. List<ListBoxItem> lists = new List<ListBoxItem>();
  1371. for(int i=0;i<pagecount;i++)
  1372. {
  1373. lists.Add(PageEditListBox.Items[insertindex+i] as ListBoxItem);
  1374. }
  1375. DealPages pages = new DealPages()
  1376. {
  1377. Pages = lists,
  1378. Op = Option.Insert
  1379. };
  1380. UndoStack.Push(pages);
  1381. ItemsInViewHitTest();
  1382. UpdateAllPageNum();
  1383. }
  1384. private string GetPageParam()
  1385. {
  1386. string pageParam = "";
  1387. List<int> pagesList = new List<int>();
  1388. for (int i = 0; i < PageEditListBox.SelectedItems.Count; i++)
  1389. {
  1390. var item = PageEditListBox.SelectedItems[i] as ListBoxItem;
  1391. var page = GetPageNumTextBlock(item);
  1392. if (page != null)
  1393. {
  1394. pagesList.Add(int.Parse(page.Text));
  1395. }
  1396. }
  1397. if (pagesList.Count != 0)
  1398. {
  1399. pagesList.Sort();
  1400. for (int i = 0; i < pagesList.Count; i++)
  1401. {
  1402. if (i == 0)
  1403. {
  1404. pageParam += pagesList[0].ToString();
  1405. }
  1406. else
  1407. {
  1408. if (pagesList[i] == pagesList[i - 1] + 1)
  1409. {
  1410. if (i >= 2)
  1411. {
  1412. if (pagesList[i - 1] != pagesList[i - 2] + 1)
  1413. pageParam += "-";
  1414. }
  1415. else
  1416. pageParam += "-";
  1417. if (i == pagesList.Count - 1)
  1418. {
  1419. pageParam += pagesList[i].ToString();
  1420. }
  1421. }
  1422. else
  1423. {
  1424. if (i >= 2)
  1425. {
  1426. if (pagesList[i - 1] == pagesList[i - 2] + 1)
  1427. pageParam += pagesList[i - 1].ToString();
  1428. }
  1429. pageParam += "," + pagesList[i].ToString();
  1430. }
  1431. }
  1432. }
  1433. }
  1434. return pageParam;
  1435. }
  1436. public static BitmapSource ToBitmapSource(string path)
  1437. {
  1438. System.Drawing.Icon ico = System.Drawing.Icon.ExtractAssociatedIcon(path);
  1439. System.Drawing.Bitmap bitmap = ico.ToBitmap();
  1440. BitmapSource returnSource;
  1441. try
  1442. {
  1443. returnSource =System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(bitmap.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
  1444. }
  1445. catch
  1446. {
  1447. returnSource = null;
  1448. }
  1449. return returnSource;
  1450. }
  1451. private Tuple<int, int, int> GetRoughViewportRange(ListBox view, Size itemSize, Thickness itemMargin)
  1452. {
  1453. var scrollViewer = GetScrollHost(view);
  1454. if (scrollViewer == null || scrollViewer.ActualHeight == 0 || scrollViewer.ActualWidth == 0)
  1455. return new Tuple<int, int, int>(0, 0, 0);
  1456. try
  1457. {
  1458. var currentHeight = scrollViewer.ActualHeight - view.Padding.Top;
  1459. var currentWidth = scrollViewer.ActualWidth;
  1460. var columnCount = (int)(currentWidth / (itemSize.Width + itemMargin.Left));
  1461. var rowCount = (int)Math.Ceiling(currentHeight / (itemSize.Height + itemMargin.Bottom));
  1462. var preItemCount = (int)((scrollViewer.VerticalOffset / scrollViewer.ExtentHeight) * ((pdfViewer.Document.PageCount + columnCount - 1) / columnCount));//滑动百分比*行数 = 大概的垂直位置
  1463. preItemCount = preItemCount * columnCount;
  1464. var preEnd = (int)(((scrollViewer.VerticalOffset + scrollViewer.ActualHeight) / scrollViewer.ExtentHeight) * ((pdfViewer.Document.PageCount + columnCount - 1) / columnCount));
  1465. preEnd = preEnd * columnCount + columnCount - 1;
  1466. var middle = (int)Math.Ceiling(preItemCount + preEnd / 2d);
  1467. return new Tuple<int, int, int>(
  1468. Math.Max(preItemCount, 0),
  1469. Math.Min(view.Items.Count, preEnd),
  1470. middle);
  1471. }
  1472. catch (Exception ex)
  1473. {
  1474. }
  1475. return new Tuple<int, int, int>(0, 0, 0);
  1476. }
  1477. #endregion
  1478. }
  1479. }