CPDFPageEditControl.xaml.cs 80 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199
  1. using ComPDFKit.PDFDocument;
  2. using ComPDFKitViewer.PdfViewer;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Collections.ObjectModel;
  6. using System.Diagnostics;
  7. using System.Threading.Tasks;
  8. using System.Windows;
  9. using System.Windows.Controls;
  10. using System.Windows.Input;
  11. using System.Windows.Media;
  12. using System.Windows.Media.Imaging;
  13. using System.Windows.Shapes;
  14. using Winform = System.Windows.Forms;
  15. using static Compdfkit_Tools.Helper.CommonHelper;
  16. using System.Windows.Threading;
  17. using WpfToolkit.Controls;
  18. using Microsoft.Win32;
  19. using System.Windows.Controls.Primitives;
  20. using System.IO;
  21. using System.Windows.Media.Animation;
  22. namespace Compdfkit_Tools.PDFControl
  23. {
  24. public partial class CPDFPageEditControl : UserControl
  25. {
  26. #region Helper class Helper methods
  27. internal static class Utils
  28. {
  29. public static T FindVisualParent<T>(DependencyObject obj) where T : class
  30. {
  31. while (obj != null)
  32. {
  33. if (obj is T)
  34. return obj as T;
  35. obj = VisualTreeHelper.GetParent(obj);
  36. }
  37. return null;
  38. }
  39. public static childItem FindVisualChild<childItem>(DependencyObject obj)
  40. where childItem : DependencyObject
  41. {
  42. for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
  43. {
  44. DependencyObject child = VisualTreeHelper.GetChild(obj, i);
  45. if (child != null && child is childItem)
  46. return (childItem)child;
  47. else
  48. {
  49. childItem childOfChild = FindVisualChild<childItem>(child);
  50. if (childOfChild != null)
  51. return childOfChild;
  52. }
  53. }
  54. return null;
  55. }
  56. }
  57. #endregion
  58. private ObservableCollection<ListBoxItem> bindPageList = new ObservableCollection<ListBoxItem>();
  59. public bool isThumbInitialized = false;
  60. private const int THUMBNAIL_WIDTH = 150;
  61. private const int THUMBNAIL_HEIGHT = 150;
  62. public CPDFViewer pdfViewer;
  63. private List<int> pageThumbnailsToRequest = new List<int>();
  64. private List<int> visiblePageIndexes = new List<int>();
  65. private string dragingEnterPath;
  66. private ScrollEventType scrollType = ScrollEventType.EndScroll;
  67. private Point startPostion = new Point();
  68. private bool isFirstLoad = true;
  69. public bool isHided = false;
  70. private int zoomLevel = 2;
  71. private bool isZooming = false;
  72. private int[] thumbnailSize = { 100, 150, 200, 300, 500 };
  73. private bool startChoose = false; //Whether to start multiple selections (box selection)
  74. private int speed = 0; //Scrolling speed
  75. //The position in the item when the mouse clicks
  76. private double item_x;
  77. private double item_y;
  78. private int InsertIndex = -1;
  79. //Drag the Item
  80. private ListBoxItem tempItem;
  81. //Whether the mouse stays on the front half of the item
  82. //When the first half is displayed, the index obtained is the actual index value
  83. //When the second half is displayed, the obtained index needs add 1
  84. //private bool isFrontHalf = false;
  85. private bool isDraging = false;
  86. //Whether the file is being dragged in from the outside
  87. private bool isDragingEnter = false;
  88. //It is used to assist in the implementation of multi-select and then single-select problems
  89. private bool iskeyDown = false;
  90. //When the order or total number of pages changes
  91. public event RoutedEventHandler PageMoved;
  92. //When zooming
  93. public event RoutedEventHandler ChangedZoomFactor;
  94. private bool isFirstScrollChange = true;
  95. private bool isFirstSizeChange = true;
  96. public string SelectedItemsRange
  97. {
  98. get { return GetPageParam(); }
  99. }
  100. public int SelectedIndex
  101. {
  102. get { return PageEditListBox.SelectedIndex; }
  103. }
  104. public event EventHandler ExitPageEdit;
  105. public CPDFPageEditControl()
  106. {
  107. InitializeComponent();
  108. }
  109. public void PageEdit(string PageEditString)
  110. {
  111. var list = GetListFromSelectedItems();
  112. if (PageEditString == "Insert")
  113. {
  114. CPDFPageInsertWindow pageInsertWindow = new CPDFPageInsertWindow();
  115. Window parentWindow = Window.GetWindow(this);
  116. pageInsertWindow.InitPageInsertWindow(SelectedIndex, pdfViewer.Document.PageCount);
  117. pageInsertWindow.DialogClosed += PageInsertWindow_DialogClosed;
  118. pageInsertWindow.Owner = parentWindow;
  119. pageInsertWindow.ShowDialog();
  120. }
  121. else if (PageEditString == "Replace")
  122. {
  123. DoReplace();
  124. }
  125. else if (PageEditString == "Extract")
  126. {
  127. CPDFPageExtractWindow pageExtractWindow = new CPDFPageExtractWindow();
  128. Window parentWindow = Window.GetWindow(this);
  129. pageExtractWindow.InitPageExtractWindow(SelectedItemsRange, pdfViewer.Document.PageCount);
  130. pageExtractWindow.DialogClosed += PageExtractWindow_DialogClosed;
  131. pageExtractWindow.Owner = parentWindow;
  132. pageExtractWindow.ShowDialog();
  133. }
  134. else if (PageEditString == "Copy")
  135. {
  136. DoCopy();
  137. DoPaste();
  138. ViewportHelper.CopyDoc = null;
  139. }
  140. else if (PageEditString == "Rotate")
  141. {
  142. DoRotate(90);
  143. }
  144. else if (PageEditString == "Delete")
  145. {
  146. DoDelete(list, true);
  147. }
  148. }
  149. private void PageInsertWindow_DialogClosed(object sender, InsertDialogCloseEventArgs e)
  150. {
  151. InsertEventClass result = e.DialogResult;
  152. if (result != null)
  153. {
  154. DoInsert(result);
  155. }
  156. else
  157. {
  158. }
  159. }
  160. private void PageExtractWindow_DialogClosed(object sender, ExtractDialogCloseEventArgs e)
  161. {
  162. ExtractEventClass result = e.DialogResult;
  163. if (result != null)
  164. {
  165. DoExtract(result);
  166. }
  167. else
  168. {
  169. }
  170. }
  171. private void Timer_Tick(object sender, EventArgs e)
  172. {
  173. AlertBorder.Visibility = Visibility.Collapsed;
  174. DispatcherTimer timer = (DispatcherTimer)sender;
  175. timer.Stop();
  176. timer.Tick -= Timer_Tick;
  177. }
  178. #region Shortcut key binding
  179. private void CommandBinding_Executed_LeftRotate(object sender, ExecutedRoutedEventArgs e)
  180. {
  181. DoRotate(-90);
  182. }
  183. private void CommandBinding_Executed_RightRotate(object sender, ExecutedRoutedEventArgs e)
  184. {
  185. DoRotate(90);
  186. }
  187. private void CommandBinding_Executed_Delete(object sender, ExecutedRoutedEventArgs e)
  188. {
  189. var list = GetListFromSelectedItems();
  190. DoDelete(list, true);
  191. }
  192. private void CommandBinding_Executed_Copy(object sender, ExecutedRoutedEventArgs e)
  193. {
  194. DoCopy();
  195. DoPaste();
  196. ViewportHelper.CopyDoc = null;
  197. }
  198. #endregion
  199. #region Event
  200. private void PdfViewer_InfoChanged(object sender, KeyValuePair<string, object> e)
  201. {
  202. if (e.Key == "RenderNum" && this.Visibility == Visibility.Visible && !isHided)
  203. {
  204. UpdateSelectedIndex();
  205. }
  206. }
  207. private void _pdfviewer_OnThumbnailGenerated(int pageIndex, byte[] thumb, int w, int h)
  208. {
  209. try
  210. {
  211. if (PageEditListBox.Items.IsEmpty)
  212. {
  213. return;
  214. }
  215. ScrollViewer sv = GetScrollHost(PageEditListBox);
  216. ListBoxItem listboxitem = PageEditListBox.ItemContainerGenerator.ContainerFromIndex(pageIndex) as ListBoxItem;
  217. if (ViewportHelper.IsInViewport(sv, listboxitem))
  218. {
  219. Debug.WriteLine("Got thumbnail for page {0}. It is visible, so adding thumb", pageIndex);
  220. PixelFormat fmt = PixelFormats.Bgra32;
  221. BitmapSource bps = BitmapSource.Create(w, h, 96.0, 96.0, fmt, null, thumb, (w * fmt.BitsPerPixel + 7) / 8);
  222. Image image = GetImageElement(PageEditListBox.Items[pageIndex] as ListBoxItem);
  223. image.Source = bps;
  224. }
  225. else
  226. {
  227. Debug.WriteLine("Got thumbnail for page {0}. It is NOT visible, so ignoring thumb", pageIndex);
  228. }
  229. }
  230. catch (Exception ex)
  231. {
  232. Debug.WriteLine(ex.ToString());
  233. }
  234. }
  235. private void UserControl_Loaded(object sender, RoutedEventArgs e)
  236. {
  237. PageEditListBox.Focus();
  238. if (PageEditListBox.HasItems && pdfViewer.CurrentIndex < PageEditListBox.Items.Count)
  239. {
  240. PageEditListBox.ScrollIntoView(PageEditListBox.Items[pdfViewer.CurrentIndex < 0 ? 0 : pdfViewer.CurrentIndex]);
  241. PageEditListBox.SelectedIndex = pdfViewer.CurrentIndex;
  242. }
  243. if (pdfViewer != null)
  244. {
  245. pdfViewer.RenderCompleted += PdfViewer_InfoChanged;
  246. pdfViewer.AnnotEditHandler += PdfViewer_AnnotEditHandler;
  247. }
  248. }
  249. private void PdfViewer_AnnotEditHandler(object sender, List<ComPDFKitViewer.AnnotEvent.AnnotEditEvent> e)
  250. {
  251. if (e != null && e.Count > 0)
  252. {
  253. int pageIndex = e[0].PageIndex;
  254. RenderPage(pageIndex);
  255. }
  256. }
  257. private void UserControl_Unloaded(object sender, RoutedEventArgs e)
  258. {
  259. this.ReleaseMouseCapture();
  260. if (pdfViewer != null)
  261. {
  262. pdfViewer.AnnotEditHandler -= PdfViewer_AnnotEditHandler;
  263. pdfViewer.RenderCompleted -= PdfViewer_InfoChanged;
  264. }
  265. }
  266. private void UserControl_PreviewMouseWheel(object sender, MouseWheelEventArgs e)
  267. {
  268. if (Keyboard.IsKeyDown(Key.LeftCtrl))
  269. {
  270. var item = PageEditListBox.Items[0] as ListBoxItem;
  271. int oldZoomLevel = zoomLevel;
  272. if (e.Delta < 0)
  273. {
  274. if (zoomLevel > 0)
  275. zoomLevel--;
  276. }
  277. else
  278. {
  279. if (zoomLevel < thumbnailSize.Length - 1 && thumbnailSize[zoomLevel + 1] <= PageEditListBox.ActualWidth - 2 * item.Margin.Left)
  280. zoomLevel++;
  281. }
  282. if (zoomLevel != oldZoomLevel)
  283. {
  284. isZooming = true;
  285. RefreshThumbnail(true);
  286. isZooming = false;
  287. }
  288. ItemsInViewHitTest();
  289. return;
  290. }
  291. if (startChoose)
  292. {
  293. ScrollViewer s = GetScrollHost(PageEditListBox);
  294. var vs = s.VerticalOffset;
  295. s.ScrollToVerticalOffset(vs - e.Delta);
  296. return;
  297. }
  298. }
  299. public void ZoomOut()
  300. {
  301. if (zoomLevel > 0)
  302. {
  303. zoomLevel--;
  304. isZooming = true;
  305. PopulateThumbnailList();
  306. if (pdfViewer.CurrentIndex < PageEditListBox.Items.Count)
  307. PageEditListBox.ScrollIntoView(PageEditListBox.Items[pdfViewer.CurrentIndex]);
  308. PageEditListBox.SelectedIndex = pdfViewer.CurrentIndex;
  309. ItemsInViewHitTest();
  310. isZooming = false;
  311. }
  312. }
  313. public void ZoomIn()
  314. {
  315. if (zoomLevel < thumbnailSize.Length - 1)
  316. {
  317. zoomLevel++;
  318. isZooming = true;
  319. PopulateThumbnailList();
  320. if (pdfViewer.CurrentIndex < PageEditListBox.Items.Count)
  321. PageEditListBox.ScrollIntoView(PageEditListBox.Items[pdfViewer.CurrentIndex]);
  322. PageEditListBox.SelectedIndex = pdfViewer.CurrentIndex;
  323. ItemsInViewHitTest();
  324. isZooming = false;
  325. }
  326. }
  327. public int CanZoomOutOrIn()
  328. {
  329. if (zoomLevel <= 0)
  330. return 0;
  331. else if (zoomLevel > 0 && zoomLevel < thumbnailSize.Length - 1)
  332. return 1;
  333. else
  334. return 2;
  335. }
  336. private void TryChangedZoomFactor()
  337. {
  338. try
  339. {
  340. if (ChangedZoomFactor != null)
  341. ChangedZoomFactor.Invoke(null, null);
  342. }
  343. catch
  344. {
  345. }
  346. }
  347. public void RefreshThumbnail(bool isZooming = false)
  348. {
  349. try
  350. {
  351. if (pdfViewer == null) return;
  352. var items = GetListFromSelectedItems();
  353. PopulateThumbnailList();
  354. if (pdfViewer.CurrentIndex >= PageEditListBox.Items.Count)
  355. {
  356. PageEditListBox.ScrollIntoView(PageEditListBox.Items[PageEditListBox.Items.Count - 1]);
  357. }
  358. else
  359. PageEditListBox.ScrollIntoView(PageEditListBox.Items[pdfViewer.CurrentIndex]);
  360. if (!isZooming)
  361. PageEditListBox.SelectedIndex = pdfViewer.CurrentIndex;
  362. else
  363. {
  364. PageEditListBox.SelectedItems.Clear();
  365. for (int i = 0; i < items.Count; i++)
  366. {
  367. int index = int.Parse(items[i].Tag.ToString());
  368. if (index < PageEditListBox.Items.Count)
  369. PageEditListBox.SelectedItems.Add(PageEditListBox.Items[index]);
  370. }
  371. }
  372. ItemsInViewHitTest();
  373. RefreshBookMarkList();
  374. }
  375. catch { }
  376. }
  377. private void PageEditListBox_ScrollChanged(object sender, ScrollChangedEventArgs e)
  378. {
  379. ItemsInViewHitTest();
  380. if (startChoose)
  381. {
  382. DoSelectItems();
  383. }
  384. if (isFirstScrollChange)
  385. {
  386. isFirstScrollChange = false;
  387. TryChangedZoomFactor();
  388. return;
  389. }
  390. }
  391. private void DoSelectItems()
  392. {
  393. var s = GetScrollHost(PageEditListBox);
  394. Point start = new Point();
  395. start = new Point(startPostion.X, startPostion.Y - s.VerticalOffset);
  396. var rec = new Rect(start, Mouse.GetPosition(PageEditListBox));
  397. ChooseRect.Margin = new Thickness(rec.Left, rec.Top, 0, 0);
  398. ChooseRect.Width = rec.Width;
  399. ChooseRect.Height = rec.Height;
  400. ChooseRect.Visibility = Visibility.Visible;
  401. for (int i = 0; i < PageEditListBox.Items.Count; i++)
  402. {
  403. var _item = PageEditListBox.Items[i] as ListBoxItem;
  404. var parent = Utils.FindVisualParent<VirtualizingWrapPanel>(_item);
  405. if (parent == null)
  406. continue;
  407. var v = VisualTreeHelper.GetOffset(_item);
  408. if (rec.IntersectsWith(new Rect(v.X, v.Y, _item.ActualWidth, _item.ActualHeight)))
  409. {
  410. PageEditListBox.SelectedItems.Add(_item);
  411. }
  412. else
  413. {
  414. PageEditListBox.SelectedItems.Remove(_item);
  415. }
  416. }
  417. return;
  418. }
  419. private void PageEditListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
  420. {
  421. e.Handled = true;
  422. }
  423. private void PageEditListBox_Scroll(object sender, System.Windows.Controls.Primitives.ScrollEventArgs e)
  424. {
  425. scrollType = e.ScrollEventType;
  426. if (scrollType != ScrollEventType.EndScroll || isZooming)
  427. return;
  428. ItemsInViewHitTest();
  429. }
  430. private void PageEditListBox_KeyUp(object sender, KeyEventArgs e)
  431. {
  432. if (e.Key == Key.LeftShift || e.Key == Key.LeftCtrl)
  433. {
  434. iskeyDown = true;
  435. return;
  436. }
  437. }
  438. private void PageEditListBox_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
  439. {
  440. iskeyDown = true;
  441. var pos = e.GetPosition(PageEditListBox);
  442. HitTestResult result = VisualTreeHelper.HitTest(PageEditListBox, pos);
  443. if (result == null)
  444. {
  445. return;
  446. }
  447. var listBoxItem = Utils.FindVisualParent<ListBoxItem>(result.VisualHit);
  448. var scroller = Utils.FindVisualParent<ScrollBar>(result.VisualHit);
  449. if (listBoxItem == null)
  450. {
  451. if (scroller != null)
  452. {
  453. startChoose = false;
  454. return;
  455. }
  456. startChoose = true;
  457. PageEditListBox.SelectedItems.Clear();
  458. startPostion = e.GetPosition(PageEditListBox);
  459. startPostion = new Point(startPostion.X, startPostion.Y + GetWrapPanel(PageEditListBox).VerticalOffset);
  460. iskeyDown = false;
  461. Mouse.Capture(PageEditListBox);
  462. return;
  463. }
  464. startChoose = false;
  465. if (listBoxItem.IsSelected == true && !Keyboard.IsKeyDown(Key.LeftCtrl))
  466. {
  467. e.Handled = true;
  468. }
  469. }
  470. private void PageEditListBox_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
  471. {
  472. startChoose = false;
  473. ChooseRect.Visibility = Visibility.Collapsed;
  474. var pos = e.GetPosition(PageEditListBox);
  475. HitTestResult result = VisualTreeHelper.HitTest(PageEditListBox, pos);
  476. if (result == null)
  477. {
  478. return;
  479. }
  480. var listBoxItem = Utils.FindVisualParent<ListBoxItem>(result.VisualHit);
  481. if (listBoxItem == null)
  482. {
  483. return;
  484. }
  485. if (iskeyDown && !Keyboard.IsKeyDown(Key.LeftCtrl) && !Keyboard.IsKeyDown(Key.LeftShift))
  486. {
  487. PageEditListBox.SelectedItems.Clear();
  488. PageEditListBox.SelectedItem = listBoxItem;
  489. listBoxItem.IsSelected = true;
  490. return;
  491. }
  492. }
  493. private void PageEditListBox_Drop(object sender, DragEventArgs e)
  494. {
  495. if (!isDraging)
  496. {
  497. MidLane.Visibility = Visibility.Collapsed;
  498. return;
  499. }
  500. if (isDragingEnter)
  501. {
  502. CPDFDocument dragDoc = CPDFDocument.InitWithFilePath(dragingEnterPath);
  503. if (dragingEnterPath.Substring(dragingEnterPath.LastIndexOf(".")).ToLower() == ".pdf")
  504. {
  505. if (dragDoc != null)
  506. {
  507. int index = InsertIndex == -1 ? 0 : InsertIndex;
  508. pdfViewer.Document.ImportPagesAtIndex(dragDoc, "1-" + dragDoc.PageCount, index);
  509. PopulateThumbnailList();
  510. ItemsInViewHitTest();
  511. pdfViewer.UndoManager.ClearHistory();
  512. pdfViewer.UndoManager.CanSave = true;
  513. pdfViewer.ReloadDocument();
  514. PageEditListBox.ScrollIntoView(PageEditListBox.SelectedItem as ListBoxItem);
  515. PageMoved?.Invoke(this, new RoutedEventArgs());
  516. dragDoc.Release();
  517. }
  518. else
  519. {
  520. }
  521. }
  522. else if (!string.IsNullOrEmpty(dragingEnterPath))
  523. {
  524. }
  525. MidLane.Visibility = Visibility.Collapsed;
  526. isDragingEnter = false;
  527. dragingEnterPath = null;
  528. return;
  529. }
  530. var pos = e.GetPosition(PageEditListBox);
  531. var result = VisualTreeHelper.HitTest(PageEditListBox, pos);
  532. if (result == null)
  533. {
  534. MidLane.Visibility = Visibility.Collapsed;
  535. isDraging = false;
  536. return;
  537. }
  538. var sourcePerson = e.Data.GetData(typeof(StackPanel)) as StackPanel;
  539. if (sourcePerson == null)
  540. {
  541. MidLane.Visibility = Visibility.Collapsed;
  542. isDraging = false;
  543. return;
  544. }
  545. int targetindex = 0;
  546. if (InsertIndex != -1)
  547. {
  548. targetindex = InsertIndex;
  549. }
  550. else
  551. {
  552. var listBoxItem = Utils.FindVisualParent<ListBoxItem>(result.VisualHit);
  553. if (listBoxItem == null)
  554. {
  555. MidLane.Visibility = Visibility.Collapsed;
  556. isDraging = false;
  557. return;
  558. }
  559. var targetPerson = listBoxItem;
  560. targetPerson.Opacity = 1;
  561. sourcePerson.Opacity = 1;
  562. if (ReferenceEquals(targetPerson, sourcePerson))
  563. {
  564. MidLane.Visibility = Visibility.Collapsed;
  565. isDraging = false;
  566. return;
  567. }
  568. targetindex = PageEditListBox.Items.IndexOf(targetPerson);
  569. }
  570. List<ListBoxItem> list = new List<ListBoxItem>();
  571. List<int> sourceindex = new List<int>();
  572. List<int> pages = new List<int>();
  573. for (int i = 0; i < PageEditListBox.SelectedItems.Count; i++)
  574. {
  575. var pageindex = PageEditListBox.Items.IndexOf(PageEditListBox.SelectedItems[i] as ListBoxItem);
  576. pages.Add(pageindex);
  577. }
  578. pages.Sort();
  579. if (pages.Count <= 0)
  580. {
  581. MidLane.Visibility = Visibility.Collapsed;
  582. isDraging = false;
  583. return;
  584. }
  585. if (targetindex <= pages[0])
  586. {
  587. sourceindex.Add(-1);
  588. list = new List<ListBoxItem>();
  589. for (int i = 0; i < pages.Count; i++)
  590. {
  591. list.Add(PageEditListBox.Items[pages[i]] as ListBoxItem);
  592. sourceindex.Add(pages[i]);
  593. DragToSort(pages[i], targetindex + i);
  594. }
  595. }
  596. else if (targetindex > pages[pages.Count - 1])
  597. {
  598. sourceindex.Add(1);
  599. list = new List<ListBoxItem>();
  600. for (int i = 0; i < pages.Count; i++)
  601. {
  602. list.Add(PageEditListBox.Items[pages[pages.Count - 1 - i]] as ListBoxItem);
  603. sourceindex.Add(pages[pages.Count - 1 - i]);
  604. DragToSort(pages[pages.Count - 1 - i], targetindex - 1 - i);
  605. }
  606. }
  607. else
  608. {
  609. int i, j, k;
  610. for (k = 0; k < pages.Count - 1; k++)
  611. {
  612. if (pages[k] < targetindex && pages[k + 1] >= targetindex)
  613. break;
  614. }
  615. sourceindex.Add(0);
  616. list = new List<ListBoxItem>();
  617. for (i = 0; i <= k; i++)
  618. {
  619. list.Add(PageEditListBox.Items[pages[k - i]] as ListBoxItem);
  620. sourceindex.Add(pages[k - i]);
  621. DragToSort(pages[k - i], targetindex - 1 - i);
  622. }
  623. for (j = i; j < pages.Count; j++)
  624. {
  625. list.Add(PageEditListBox.Items[pages[j]] as ListBoxItem);
  626. sourceindex.Add(pages[j]);
  627. DragToSort(pages[j], targetindex);
  628. targetindex++;
  629. }
  630. sourceindex.Add(k);
  631. }
  632. isDraging = false;
  633. }
  634. private void MidLane_Drop(object sender, DragEventArgs e)
  635. { MidLane.Visibility = Visibility.Collapsed;
  636. this.PageEditListBox_Drop(sender, e);
  637. }
  638. private void PageEditListBox_PreviewMouseMove(object sender, MouseEventArgs e)
  639. {
  640. try
  641. {
  642. if (e.LeftButton == MouseButtonState.Pressed)
  643. {
  644. iskeyDown = false;
  645. if (startChoose)
  646. {
  647. var position = e.GetPosition(PageEditListBox);
  648. if (position.X < 5 || position.X > PageEditListBox.ActualWidth - 5 || position.Y < 5 || position.Y > PageEditListBox.ActualHeight - 5)
  649. {
  650. startChoose = false;
  651. ChooseRect.Visibility = Visibility.Collapsed;
  652. Mouse.Capture(null);
  653. return;
  654. }
  655. DoSelectItems();
  656. return;
  657. }
  658. var pos = e.GetPosition(PageEditListBox);
  659. if (pos.Y < 0 || pos.Y > PageEditListBox.ActualHeight)
  660. {
  661. MidLane.Visibility = Visibility.Collapsed;
  662. return;
  663. }
  664. HitTestResult result = VisualTreeHelper.HitTest(PageEditListBox, pos);
  665. if (result == null)
  666. {
  667. return;
  668. }
  669. var listBoxItem = Utils.FindVisualParent<ListBoxItem>(result.VisualHit);
  670. if (listBoxItem == null)
  671. {
  672. return;
  673. }
  674. isDragingEnter = false;
  675. tempItem = listBoxItem;
  676. var panel = GetPanel(tempItem);
  677. var item_pos = e.GetPosition(panel);
  678. if (item_pos != null)
  679. {
  680. item_x = item_pos.X;
  681. item_y = item_pos.Y;
  682. }
  683. var scroll = GetScrollHost(PageEditListBox);
  684. DataObject dataObj = new DataObject(listBoxItem.Content as StackPanel);
  685. DragDrop.DoDragDrop(PageEditListBox, dataObj, DragDropEffects.Move);
  686. Mouse.Capture(PageEditListBox);
  687. return;
  688. }
  689. ChooseRect.Visibility = Visibility.Collapsed;
  690. startChoose = false;
  691. Mouse.Capture(null);
  692. }
  693. catch (Exception ex)
  694. {
  695. MidLane.Visibility = Visibility.Collapsed;
  696. }
  697. }
  698. private void Grid_DragOver(object sender, DragEventArgs e)
  699. {
  700. try
  701. {
  702. if (e.KeyStates == (DragDropKeyStates.ControlKey | DragDropKeyStates.LeftMouseButton) || e.KeyStates == (DragDropKeyStates.ShiftKey | DragDropKeyStates.LeftMouseButton | DragDropKeyStates.ControlKey))
  703. return;
  704. var pos = e.GetPosition(PageEditListBox);
  705. var result = VisualTreeHelper.HitTest(PageEditListBox, pos);
  706. if (result == null)
  707. {
  708. }
  709. var listBoxItem = Utils.FindVisualParent<ListBoxItem>(result.VisualHit);
  710. if (listBoxItem == null)
  711. {
  712. }
  713. #region 计算虚影位置
  714. //xaml层 要设置 虚影控件为左上
  715. double xPos, yPos;
  716. if (!isDragingEnter)
  717. {
  718. Image image = GetImageElement(tempItem);//获取item 图片
  719. Viewbox viewBox = (tempItem.Content as StackPanel).Children[0] as Viewbox;//获取item宽度
  720. ShadowPicture.Width = viewBox.ActualWidth;
  721. ShadowPicture.Height = viewBox.ActualHeight;
  722. ShadowPicture.Source = image.Source;
  723. xPos = e.GetPosition(PageEditListBox).X - item_x;
  724. yPos = e.GetPosition(PageEditListBox).Y - item_y;
  725. }
  726. else
  727. {
  728. var pic = ToBitmapSource(dragingEnterPath);
  729. ShadowPicture.Width = pic.Width;
  730. ShadowPicture.Height = pic.Height;
  731. ShadowPicture.Source = pic;
  732. xPos = e.GetPosition(PageEditListBox).X - pic.Width / 2;
  733. yPos = e.GetPosition(PageEditListBox).Y - pic.Height / 2;
  734. }
  735. ShadowPicture.Margin = new Thickness(xPos, yPos, 0, 0);
  736. #endregion
  737. #region 计算插入标记位置
  738. var scroll = GetScrollHost(PageEditListBox);
  739. if (listBoxItem != null)
  740. {
  741. //虚拟化影响到该值计算
  742. var p = VisualTreeHelper.GetOffset(listBoxItem);//计算控件在容器中的偏移(位置)
  743. MidLane.Visibility = Visibility.Visible;
  744. var panel = GetWrapPanel(PageEditListBox);
  745. var item = (PageEditListBox.Items[0] as ListBoxItem).DesiredSize.Width;
  746. int count = (int)(panel.ViewportWidth / item);
  747. var gap = (panel.ViewportWidth - count * item) / (count + 1) * 1.0;
  748. MidLane.X2 = MidLane.X1 = p.X + gap / 2 + listBoxItem.DesiredSize.Width;
  749. if (pos.X < p.X + gap / 2 + listBoxItem.ActualWidth / 2)
  750. {
  751. MidLane.X2 = MidLane.X1 = p.X - gap / 2;
  752. InsertIndex = PageEditListBox.Items.IndexOf(listBoxItem);
  753. }
  754. else
  755. {
  756. InsertIndex = PageEditListBox.Items.IndexOf(listBoxItem) + 1;
  757. }
  758. //MidLane.Y1 = p.Y - scroll.VerticalOffset;//向下滑动后要减去滑动值
  759. MidLane.Y1 = p.Y;
  760. if (MidLane.Y1 < 0)//避免超出上边界
  761. MidLane.Y1 = 0;
  762. //MidLane.Y2 = p.Y + listBoxItem.ActualHeight - scroll.VerticalOffset;//仿智能滚动后可能会导致 垂直滚动偏量不准确
  763. MidLane.Y2 = p.Y + listBoxItem.ActualHeight;
  764. if (MidLane.Y2 < 0)
  765. {
  766. MidLane.Y2 = 0;
  767. }
  768. }
  769. #endregion
  770. if (pos.Y <= 30 || pos.Y >= PageEditListBox.ActualHeight - 10)
  771. {
  772. MidLane.Visibility = Visibility.Collapsed;
  773. }
  774. if (pos.X <= 40 || pos.X >= scroll.ViewportWidth - 50)
  775. {
  776. MidLane.Visibility = Visibility.Collapsed;
  777. }
  778. #region 靠近上下边界时,自动滚动,离边界越近,滚动速度越快
  779. speed = 0;
  780. if (pos.Y >= PageEditListBox.ActualHeight - 30)
  781. {
  782. speed = 30 - (int)(PageEditListBox.ActualHeight - pos.Y);
  783. }
  784. else if (pos.Y <= 30)
  785. {
  786. speed = (int)(pos.Y - 30);
  787. }
  788. var v = scroll.VerticalOffset;
  789. scroll.ScrollToVerticalOffset(v + speed);
  790. #endregion
  791. }
  792. catch (Exception ex)
  793. {
  794. }
  795. }
  796. private void ShadowPicture_Drop(object sender, DragEventArgs e)
  797. {
  798. this.PageEditListBox_Drop(sender, e);
  799. }
  800. private void ListBoxItem_DragLeave(object sender, DragEventArgs e)
  801. {
  802. isDraging = true;
  803. }
  804. public void Delete_Click(object sender, RoutedEventArgs e)
  805. {
  806. if (pdfViewer == null)
  807. return;
  808. var list = GetListFromSelectedItems();
  809. DoDelete(list, true);
  810. }
  811. public void Rotate_Click(object sender, RoutedEventArgs e)
  812. {
  813. var item = sender as MenuItem;
  814. double step = 90;
  815. if (item.Name == "LeftRotate")
  816. step = -90;
  817. else
  818. step = 90;
  819. DoRotate(step);
  820. PageEditListBox.Focus();
  821. }
  822. private void ListBoxItem_PreviewMouseDoubleClick(object sender, MouseButtonEventArgs e)
  823. {
  824. e.GetPosition(PageEditListBox);
  825. var pos = e.GetPosition(PageEditListBox);
  826. HitTestResult result = VisualTreeHelper.HitTest(PageEditListBox, pos);
  827. if (result == null)
  828. return;
  829. var listBoxItem = Utils.FindVisualParent<ListBoxItem>(result.VisualHit);
  830. if (listBoxItem != null)
  831. {
  832. pdfViewer.GoToPage((int)listBoxItem.Tag);
  833. }
  834. ExitPageEdit?.Invoke(this, new EventArgs());
  835. }
  836. public void Copy_Click(object sender, RoutedEventArgs e)
  837. {
  838. DoCopy();
  839. DoPaste();
  840. ViewportHelper.CopyDoc = null;
  841. }
  842. private void PageEditListBox_SizeChanged(object sender, SizeChangedEventArgs e)
  843. {
  844. PageEditListBox.ScrollIntoView(PageEditListBox.SelectedItem);
  845. }
  846. private void PageEditor_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
  847. {
  848. if (pdfViewer == null)
  849. return;
  850. if (isFirstLoad)
  851. {
  852. isFirstLoad = false;
  853. return;
  854. }
  855. if ((bool)e.NewValue == true && pdfViewer != null && pdfViewer.CurrentIndex >= 0)
  856. {
  857. RefreshThumbnail();
  858. }
  859. if (pdfViewer?.CurrentIndex >= PageEditListBox.Items.Count || PageEditListBox.Items.Count == 0)
  860. return;
  861. ListBoxItem item = PageEditListBox.Items[pdfViewer?.CurrentIndex == -1 ? 0 : pdfViewer.CurrentIndex] as ListBoxItem;
  862. PageEditListBox.ScrollIntoView(PageEditListBox.SelectedItem);
  863. PageEditListBox.SelectedItem = item;
  864. }
  865. private async void ListBoxItem_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
  866. {
  867. if (!Keyboard.IsKeyDown(Key.LeftCtrl) && !Keyboard.IsKeyDown(Key.LeftShift))
  868. {
  869. var item = sender as ListBoxItem;
  870. Image img = GetImageElement(item);
  871. int itemindex = PageEditListBox.Items.IndexOf(item);
  872. if (img.Source == null)
  873. {
  874. await pdfViewer.GetThumbnail(itemindex, (int)img.Width, (int)img.Height);
  875. }
  876. pdfViewer.GoToPage(itemindex);
  877. }
  878. }
  879. private void PageGrid_PreviewDragEnter(object sender, DragEventArgs e)
  880. {
  881. var file = (System.Array)e.Data.GetData(DataFormats.FileDrop);
  882. if (file == null || file.Length > 1)
  883. { return; }
  884. foreach (var f in file)
  885. {
  886. dragingEnterPath = f.ToString();
  887. if (dragingEnterPath != null)
  888. {
  889. isDragingEnter = true;
  890. }
  891. }
  892. }
  893. private void ContextMenu_Loaded(object sender, RoutedEventArgs e)
  894. {
  895. if (ViewportHelper.CopyDoc == null)
  896. {
  897. var s = sender as ContextMenu;
  898. foreach (var item in s.Items)
  899. {
  900. if ((item as MenuItem).Name == "Paste")
  901. {
  902. (item as MenuItem).IsEnabled = false;
  903. }
  904. }
  905. }
  906. else
  907. {
  908. var s = sender as ContextMenu;
  909. foreach (var item in s.Items)
  910. {
  911. if ((item as MenuItem).Name == "Paste")
  912. {
  913. (item as MenuItem).IsEnabled = true;
  914. }
  915. }
  916. }
  917. if (PageEditListBox.SelectedItems.Count < 2)
  918. {
  919. var s = sender as ContextMenu;
  920. foreach (var item in s.Items)
  921. {
  922. if ((item as MenuItem).Name == "Exchange")
  923. {
  924. (item as MenuItem).IsEnabled = false;
  925. }
  926. }
  927. }
  928. else
  929. {
  930. var s = sender as ContextMenu;
  931. foreach (var item in s.Items)
  932. {
  933. if ((item as MenuItem).Name == "Exchange")
  934. {
  935. (item as MenuItem).IsEnabled = true;
  936. }
  937. }
  938. }
  939. }
  940. private void UserControl_KeyDown(object sender, KeyEventArgs e)
  941. {
  942. if ((Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control && e.Key == Key.A)
  943. {
  944. if (PageEditListBox.SelectedItems.Count == PageEditListBox.Items.Count)
  945. {
  946. PageEditListBox.UnselectAll();
  947. e.Handled = true;
  948. }
  949. }
  950. }
  951. #endregion
  952. #region Method
  953. public void LoadThumbnails(CPDFViewer viewer)
  954. {
  955. if (viewer == null || viewer.Document == null)
  956. return;
  957. if (pdfViewer != null && viewer != pdfViewer)
  958. {
  959. pdfViewer = viewer;
  960. this.PopulateThumbnailList();
  961. pdfViewer.OnThumbnailGenerated -= _pdfviewer_OnThumbnailGenerated;
  962. pdfViewer.OnThumbnailGenerated += _pdfviewer_OnThumbnailGenerated;
  963. pdfViewer.RenderCompleted += PdfViewer_InfoChanged;
  964. pdfViewer.AnnotEditHandler += PdfViewer_AnnotEditHandler;
  965. }
  966. pdfViewer = viewer;
  967. if (!isThumbInitialized)
  968. {
  969. this.PopulateThumbnailList();
  970. isThumbInitialized = true;
  971. pdfViewer.OnThumbnailGenerated -= _pdfviewer_OnThumbnailGenerated;
  972. pdfViewer.OnThumbnailGenerated += _pdfviewer_OnThumbnailGenerated;
  973. }
  974. if (pdfViewer.CurrentIndex >= 0 && PageEditListBox.Items.Count > pdfViewer.CurrentIndex)
  975. {
  976. PageEditListBox.ScrollIntoView(PageEditListBox.Items[pdfViewer.CurrentIndex]);
  977. (PageEditListBox.Items[pdfViewer.CurrentIndex] as ListBoxItem).IsSelected = true;
  978. PageEditListBox.SelectedIndex = pdfViewer.CurrentIndex;
  979. }
  980. RefreshBookMarkList();
  981. }
  982. public void PopulateThumbnailList()
  983. {
  984. visiblePageIndexes.Clear();
  985. bindPageList.Clear();
  986. // GC.Collect();
  987. int thumbnailWidth = thumbnailSize[zoomLevel];
  988. for (int i = 0; i < pdfViewer.Document.PageCount; i++)
  989. {
  990. Size pageSize = pdfViewer.Document.GetPageSize(i);
  991. if (pageSize.Height == 0 || pageSize.Width == 0)
  992. continue;
  993. int imageWidth = pageSize.Width > pageSize.Height ? thumbnailWidth * 2 : (int)(pageSize.Width / pageSize.Height * thumbnailWidth * 2);
  994. int imageHeight = pageSize.Height > pageSize.Width ? thumbnailWidth * 2 : (int)(pageSize.Height / pageSize.Width * thumbnailWidth * 2);
  995. Image img = new Image()
  996. {
  997. //Margin = new Thickness(0, 0, 5, 0),
  998. Width = imageWidth,
  999. Height = imageHeight,
  1000. Stretch = Stretch.Uniform,
  1001. };
  1002. Grid grid = new Grid();
  1003. grid.Children.Add(img);
  1004. List<Point> points = new List<Point>()
  1005. {
  1006. new Point(16.75,1.25),
  1007. new Point(3.25,1.25 ),
  1008. new Point(3.25,19.4013878),
  1009. new Point(10,14.902),
  1010. new Point(16.75,19.4013878),
  1011. };
  1012. Polygon bookmark = new Polygon()
  1013. {
  1014. Points = new PointCollection(points),
  1015. Fill = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#FFBB00")),
  1016. Margin = new Thickness(0, 16, 16, 0),
  1017. VerticalAlignment = VerticalAlignment.Top,
  1018. HorizontalAlignment = HorizontalAlignment.Right,
  1019. Visibility = Visibility.Collapsed,
  1020. };
  1021. grid.Children.Add(bookmark);
  1022. Border border = new Border()
  1023. {
  1024. BorderThickness = new Thickness(2),
  1025. BorderBrush = new SolidColorBrush((System.Windows.Media.Color)System.Windows.Media.ColorConverter.ConvertFromString("#A0A2AE")),
  1026. Child = grid,
  1027. };
  1028. Viewbox viewBox = new Viewbox()
  1029. {
  1030. Margin = new Thickness(0, 8, 0, 0),
  1031. Stretch = System.Windows.Media.Stretch.Uniform,
  1032. Width = thumbnailWidth,
  1033. Height = thumbnailWidth,
  1034. Child = border,
  1035. };
  1036. TextBlock text = new TextBlock()
  1037. {
  1038. HorizontalAlignment = System.Windows.HorizontalAlignment.Center,
  1039. Text = (i + 1).ToString(),
  1040. Foreground = Brushes.Black,
  1041. Margin = new Thickness(0, 8, 0, 8),
  1042. };
  1043. StackPanel panel = new StackPanel();
  1044. panel.Children.Add(viewBox);
  1045. panel.Children.Add(text);
  1046. ListBoxItem item = new ListBoxItem();
  1047. item.Content = panel;
  1048. item.Tag = i;
  1049. item.Margin = new Thickness(6, 10, 6, 10);
  1050. bindPageList.Add(item);
  1051. }
  1052. PageEditListBox.ItemsSource = bindPageList;
  1053. }
  1054. public ListBoxItem GetNewItem(int ItemIndex)
  1055. {
  1056. int thumbnailWidth = thumbnailSize[zoomLevel];
  1057. Size pageSize = pdfViewer.Document.GetPageSize(ItemIndex);
  1058. if (pageSize.Width == 0 || pageSize.Height == 0)
  1059. {
  1060. pageSize = new Size(228, 300);
  1061. }
  1062. int imageWidth = pageSize.Width > pageSize.Height ? thumbnailWidth * 2 : (int)(pageSize.Width / pageSize.Height * thumbnailWidth * 2);
  1063. int imageHeight = pageSize.Height > pageSize.Width ? thumbnailWidth * 2 : (int)(pageSize.Height / pageSize.Width * thumbnailWidth * 2);
  1064. Image img = new Image()
  1065. {
  1066. Width = imageWidth,
  1067. Height = imageHeight,
  1068. Stretch = Stretch.Uniform,
  1069. };
  1070. Grid grid = new Grid();
  1071. grid.Children.Add(img);
  1072. List<Point> points = new List<Point>()
  1073. {
  1074. new Point(16.75,1.25),
  1075. new Point(3.25,1.25 ),
  1076. new Point(3.25,19.4013878),
  1077. new Point(10,14.902),
  1078. new Point(16.75,19.4013878),
  1079. };
  1080. Polygon bookmark = new Polygon()
  1081. {
  1082. Points = new PointCollection(points),
  1083. Fill = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#FFBB00")),
  1084. Margin = new Thickness(0, 8, 8, 0),
  1085. VerticalAlignment = VerticalAlignment.Top,
  1086. HorizontalAlignment = HorizontalAlignment.Right,
  1087. Visibility = Visibility.Collapsed,
  1088. };
  1089. grid.Children.Add(bookmark);
  1090. Border border = new Border()
  1091. {
  1092. BorderThickness = new Thickness(2),
  1093. BorderBrush = new SolidColorBrush((System.Windows.Media.Color)System.Windows.Media.ColorConverter.ConvertFromString("#A0A2AE")),
  1094. Child = grid,
  1095. };
  1096. Viewbox viewBox = new Viewbox()
  1097. {
  1098. Margin = new Thickness(0, 8, 0, 0),
  1099. Stretch = System.Windows.Media.Stretch.Uniform,
  1100. Width = thumbnailWidth,
  1101. Height = thumbnailWidth,
  1102. Child = border,
  1103. };
  1104. TextBlock text = new TextBlock()
  1105. {
  1106. HorizontalAlignment = System.Windows.HorizontalAlignment.Center,
  1107. Text = (ItemIndex + 1).ToString(),
  1108. Foreground = Brushes.Black,
  1109. Margin = new Thickness(0, 8, 0, 8),
  1110. };
  1111. StackPanel panel = new StackPanel();
  1112. panel.Children.Add(viewBox);
  1113. panel.Children.Add(text);
  1114. ListBoxItem item = new ListBoxItem();
  1115. item.Content = panel;
  1116. item.Tag = ItemIndex;
  1117. item.Margin = new Thickness(6, 10, 6, 10);
  1118. return item;
  1119. }
  1120. public void AddBlankPages(int pagecount, int insertindex)
  1121. {
  1122. for (int i = 0; i < pagecount; i++)
  1123. {
  1124. var item = GetNewItem(insertindex + i);
  1125. bindPageList.Insert(insertindex + i, item);
  1126. if (visiblePageIndexes.Contains(insertindex + i))
  1127. visiblePageIndexes.Remove(insertindex + i);
  1128. }
  1129. PageEditListBox.UpdateLayout();
  1130. }
  1131. private async void RenderPage(int pageindex)
  1132. {
  1133. var range = GetRoughViewportRange(PageEditListBox, (PageEditListBox.Items[0] as ListBoxItem).DesiredSize, new Thickness(6, 10, 6, 10));
  1134. if (pageindex < range.Item1 || pageindex > range.Item2)
  1135. return;
  1136. ListBoxItem item = PageEditListBox.Items[pageindex] as ListBoxItem;
  1137. Image img = GetImageElement(item);
  1138. await pdfViewer.GetThumbnail(pageindex, (int)img.Width, (int)img.Height);
  1139. }
  1140. private async void ItemsInViewHitTest()
  1141. {
  1142. if (pdfViewer == null || pdfViewer.Document == null)
  1143. return;
  1144. try
  1145. {
  1146. ScrollViewer sv = GetScrollHost(PageEditListBox);
  1147. if (sv == null) return;
  1148. if (VisualTreeHelper.GetParent(this) == null)
  1149. return;
  1150. var range = GetRoughViewportRange(PageEditListBox, (PageEditListBox.Items[0] as ListBoxItem).DesiredSize, new Thickness(6, 10, 6, 10));
  1151. for (int i = 0; i < PageEditListBox.Items.Count; ++i)
  1152. {
  1153. ListBoxItem item = PageEditListBox.Items[i] as ListBoxItem;
  1154. Image img = GetImageElement(item);
  1155. if (i >= (range.Item1 - 1) && i <= range.Item2 || ViewportHelper.IsInViewport(sv, item))
  1156. {
  1157. if (img.Source == null && !visiblePageIndexes.Contains(i))
  1158. {
  1159. visiblePageIndexes.Add(i);
  1160. await Task.Delay(1);
  1161. await pdfViewer.GetThumbnail(i, (int)img.Width, (int)img.Height);
  1162. Debug.WriteLine("Page {0} is visible, asking for thumb", (i + 1));
  1163. }
  1164. else if (img.Source == null)
  1165. {
  1166. await pdfViewer.GetThumbnail(i, (int)img.Width, (int)img.Height);
  1167. Debug.WriteLine("Page {0} is visible, asking for thumb", (i + 1));
  1168. }
  1169. }
  1170. else
  1171. {
  1172. if (visiblePageIndexes.Contains(i))
  1173. {
  1174. Image image = GetImageElement(PageEditListBox.Items[i] as ListBoxItem);
  1175. if (image.Source != null)
  1176. {
  1177. image.Source = null;
  1178. Debug.WriteLine("Page {0} is out of range, removed thumb", (i + 1));
  1179. }
  1180. else
  1181. {
  1182. Debug.WriteLine("Page {0} is out of range, but had no thumb", (i + 1));
  1183. }
  1184. visiblePageIndexes.Remove(i);
  1185. }
  1186. }
  1187. }
  1188. }
  1189. catch (Exception ex)
  1190. {
  1191. Debug.WriteLine(ex.ToString());
  1192. }
  1193. }
  1194. public void RefreshBookMarkList()
  1195. {
  1196. if (pdfViewer != null)
  1197. {
  1198. var booklist = pdfViewer.Document.GetBookmarkList();
  1199. if (booklist == null) return;
  1200. List<int> marks = new List<int>();
  1201. for (int i = 0; i < booklist.Count; i++)
  1202. {
  1203. marks.Add(booklist[i].PageIndex);
  1204. }
  1205. for (int k = 0; k < PageEditListBox.Items.Count; k++)
  1206. {
  1207. Polygon polygon = GetBookMarkIco(PageEditListBox.Items[k] as ListBoxItem);
  1208. if (marks.Contains(k))
  1209. polygon.Visibility = Visibility.Visible;
  1210. else
  1211. polygon.Visibility = Visibility.Collapsed;
  1212. }
  1213. }
  1214. }
  1215. private void UpdateSelectedIndex()
  1216. {
  1217. if (PageEditListBox.Items.Count == 0)
  1218. PageEditListBox.SelectedIndex = -1;
  1219. else if (PageEditListBox.Items.Count <= pdfViewer.CurrentIndex)
  1220. this.PageEditListBox.SelectedIndex = 0;
  1221. else if (PageEditListBox.SelectedIndex != pdfViewer.CurrentIndex)
  1222. PageEditListBox.SelectedIndex = pdfViewer.CurrentIndex;
  1223. PageEditListBox.ScrollIntoView(PageEditListBox.Items[PageEditListBox.SelectedIndex]);
  1224. }
  1225. private Image GetImageElement(ListBoxItem item)
  1226. {
  1227. Viewbox viewBox = (item.Content as StackPanel).Children[0] as Viewbox;
  1228. Image img = ((viewBox.Child as Border).Child as Grid).Children[0] as Image;
  1229. return img;
  1230. }
  1231. private Polygon GetBookMarkIco(ListBoxItem item)
  1232. {
  1233. Viewbox viewBox = (item.Content as StackPanel).Children[0] as Viewbox;
  1234. Polygon ico = ((viewBox.Child as Border).Child as Grid).Children[1] as Polygon;
  1235. return ico;
  1236. }
  1237. private StackPanel GetPanel(ListBoxItem item)
  1238. {
  1239. StackPanel panel = item.Content as StackPanel;
  1240. return panel;
  1241. }
  1242. private TextBlock GetPageNumTextBlock(ListBoxItem item)
  1243. {
  1244. TextBlock text = (item.Content as StackPanel).Children[1] as TextBlock;
  1245. return text;
  1246. }
  1247. public VirtualizingWrapPanel GetWrapPanel(ListBox listBox)
  1248. {
  1249. Border border = VisualTreeHelper.GetChild(listBox, 0) as Border;
  1250. var panel = Utils.FindVisualChild<VirtualizingWrapPanel>(border);
  1251. return panel;
  1252. }
  1253. private ScrollViewer GetScrollHost(ListBox listBox)
  1254. {
  1255. if (VisualTreeHelper.GetChildrenCount(listBox) > 0)
  1256. {
  1257. int s = VisualTreeHelper.GetChildrenCount(listBox);
  1258. Border border = VisualTreeHelper.GetChild(listBox, 0) as Border;
  1259. if (border != null)
  1260. {
  1261. return VisualTreeHelper.GetChild(border, 0) as ScrollViewer;
  1262. }
  1263. }
  1264. return null;
  1265. }
  1266. private void DragToSort(int sourceindex, int targetindex)
  1267. {
  1268. if (targetindex == sourceindex || targetindex < 0)
  1269. {
  1270. MidLane.Visibility = Visibility.Collapsed;
  1271. return;
  1272. }
  1273. var source = PageEditListBox.Items[sourceindex];
  1274. bindPageList.RemoveAt(sourceindex);
  1275. MidLane.Visibility = Visibility.Collapsed;
  1276. bindPageList.Insert(targetindex, source as ListBoxItem);
  1277. PageEditListBox.SelectedItems.Add(source);
  1278. var result = pdfViewer.Document.MovePage(sourceindex, targetindex);
  1279. if (!result)
  1280. {
  1281. MidLane.Visibility = Visibility.Collapsed;
  1282. return;
  1283. }
  1284. pdfViewer.ReloadDocument();
  1285. pdfViewer.GoToPage(PageEditListBox.SelectedIndex);
  1286. pdfViewer.UndoManager.ClearHistory();
  1287. pdfViewer.UndoManager.CanSave = true;
  1288. ItemsInViewHitTest();
  1289. this.PageMoved?.Invoke(this, new RoutedEventArgs());
  1290. UpdateSortedPageNum(sourceindex, targetindex);
  1291. }
  1292. private void UpdateSortedPageNum(int sourceIndex, int targetIndex)
  1293. {
  1294. int sum = sourceIndex + targetIndex;
  1295. targetIndex = targetIndex > sourceIndex ? targetIndex : sourceIndex;
  1296. sourceIndex = sum - targetIndex;
  1297. sourceIndex = sourceIndex <= 0 ? 0 : sourceIndex;
  1298. targetIndex = targetIndex + 1 > PageEditListBox.Items.Count ? PageEditListBox.Items.Count - 1 : targetIndex;
  1299. for (int i = sourceIndex; i <= targetIndex; i++)
  1300. {
  1301. var item = PageEditListBox.Items[i] as ListBoxItem;
  1302. item.Tag = i;
  1303. TextBlock pagenum = GetPageNumTextBlock(item);
  1304. pagenum.Text = (i + 1).ToString();
  1305. }
  1306. }
  1307. private void UpdateAllPageNum()
  1308. {
  1309. for (int i = 0; i < PageEditListBox.Items.Count; i++)
  1310. {
  1311. var pagenum = GetPageNumTextBlock(PageEditListBox.Items[i] as ListBoxItem);
  1312. pagenum.Text = (i + 1).ToString();
  1313. (PageEditListBox.Items[i] as ListBoxItem).Tag = i;
  1314. }
  1315. }
  1316. public void DoInsert(EventArgs e)
  1317. {
  1318. var data = e as InsertEventClass;
  1319. if (data.InsertType == InsertType.BlankPages)
  1320. {
  1321. var size = pdfViewer.Document.GetPageSize(data.InsertIndex - 1);
  1322. if (size.Width == 0 || size.Height == 0)
  1323. size = pdfViewer.Document.GetPageSize(data.InsertIndex);
  1324. pdfViewer.Document.InsertPage(data.InsertIndex, size.Width, size.Height, "");
  1325. RefreshThumbnail();
  1326. PageEditListBox.SelectedItems.Clear();
  1327. PageEditListBox.SelectedIndex = data.InsertIndex;
  1328. }
  1329. else if (data.InsertType == InsertType.CustomBlankPages)
  1330. {
  1331. pdfViewer.Document.InsertPage(data.InsertIndex, data.PageWidth, data.PageHeight, "");
  1332. RefreshThumbnail();
  1333. PageEditListBox.SelectedItems.Clear();
  1334. PageEditListBox.SelectedIndex = data.InsertIndex;
  1335. }
  1336. else
  1337. {
  1338. DoAddFromOtherPdf(data.FilePath, data.PageRange, data.InsertIndex, data.Password);
  1339. }
  1340. UpdateAllPageNum();
  1341. pdfViewer.UndoManager.ClearHistory();
  1342. pdfViewer.UndoManager.CanSave = true;
  1343. pdfViewer.ReloadDocument();
  1344. PageEditListBox.ScrollIntoView(PageEditListBox.SelectedItem as ListBoxItem);
  1345. ItemsInViewHitTest();
  1346. }
  1347. public void DoReplace()
  1348. {
  1349. if (PageEditListBox.SelectedItems.Count < 1)
  1350. {
  1351. ShowAlertWithTimeout(AlertType.EmptyPageAlert);
  1352. return;
  1353. }
  1354. OpenFileDialog dialog = new OpenFileDialog();
  1355. dialog.Multiselect = false;
  1356. dialog.Filter = "(*.pdf)|*.pdf";
  1357. if ((bool)dialog.ShowDialog())
  1358. {
  1359. CPDFDocument doc = CPDFDocument.InitWithFilePath(dialog.FileName);
  1360. int pagecount = doc.PageCount;
  1361. int insertindex = PageEditListBox.Items.IndexOf(PageEditListBox.SelectedItem);
  1362. if (insertindex == -1)
  1363. insertindex = 0;
  1364. var result = pdfViewer.Document.ImportPagesAtIndex(doc, "1-" + pagecount, insertindex);
  1365. doc.Release();
  1366. for (int i = 0; i < pagecount; i++)
  1367. {
  1368. var item = GetNewItem(insertindex + i);
  1369. bindPageList.Insert(insertindex + i, item);
  1370. if (visiblePageIndexes.Contains(insertindex + i))
  1371. visiblePageIndexes.Remove(insertindex + i);
  1372. }
  1373. pdfViewer.UndoManager.ClearHistory();
  1374. pdfViewer.UndoManager.CanSave = true;
  1375. var list = GetListFromSelectedItems();
  1376. for (int i = insertindex; i < (insertindex + pagecount); i++)
  1377. {
  1378. if (i < PageEditListBox.Items.Count)
  1379. {
  1380. ListBoxItem t = PageEditListBox.Items[i] as ListBoxItem;
  1381. PageEditListBox.SelectedItems.Add(t);
  1382. }
  1383. }
  1384. DoDelete(list, false);
  1385. UpdateAllPageNum();
  1386. RefreshBookMarkList();
  1387. ItemsInViewHitTest();
  1388. }
  1389. }
  1390. private void DoRotate(double angleStep)
  1391. {
  1392. if (pdfViewer == null) return;
  1393. if (PageEditListBox.SelectedItems.Count < 1)
  1394. {
  1395. ShowAlertWithTimeout(AlertType.EmptyPageAlert);
  1396. return;
  1397. }
  1398. List<ListBoxItem> pages = new List<ListBoxItem>();
  1399. for (int i = 0; i < PageEditListBox.SelectedItems.Count; i++)
  1400. {
  1401. var image = GetImageElement(PageEditListBox.SelectedItems[i] as ListBoxItem);
  1402. pages.Add(PageEditListBox.SelectedItems[i] as ListBoxItem);
  1403. double angle = (double)image.LayoutTransform.GetValue(RotateTransform.AngleProperty);
  1404. angle += angleStep;
  1405. angle = angle % 360;
  1406. image.LayoutTransform = new RotateTransform(angle, image.ActualWidth / 2, image.ActualHeight / 2);
  1407. var index = PageEditListBox.Items.IndexOf(PageEditListBox.SelectedItems[i]);
  1408. pdfViewer.Document.RotatePage(index, (int)angleStep / 90);
  1409. pdfViewer.Document.ReleasePages(index);
  1410. pdfViewer.ClearSelectPDFEdit(true);
  1411. pdfViewer.UndoManager.ClearHistory();
  1412. pdfViewer.UndoManager.CanSave = true;
  1413. if (visiblePageIndexes.Contains(index))
  1414. visiblePageIndexes.Remove(index);
  1415. }
  1416. pdfViewer.ReloadDocument();
  1417. ItemsInViewHitTest();
  1418. }
  1419. public static string CreateFilePath(string path)
  1420. {
  1421. int i = 1;
  1422. string oldDestName = path;
  1423. do
  1424. {
  1425. if (File.Exists(path))
  1426. {
  1427. int lastDot = oldDestName.LastIndexOf('.');
  1428. string fileExtension = string.Empty;
  1429. string fileName = oldDestName;
  1430. if (lastDot > 0)
  1431. {
  1432. fileExtension = fileName.Substring(lastDot);
  1433. fileName = fileName.Substring(0, lastDot);
  1434. }
  1435. path = fileName + string.Format(@"({0})", i) + fileExtension;
  1436. }
  1437. ++i;
  1438. } while (File.Exists(path));
  1439. return path;
  1440. }
  1441. public void DoExtract(EventArgs e)
  1442. {
  1443. var data = e as ExtractEventClass;
  1444. int pagecount = pdfViewer.Document.PageCount;
  1445. string pageName = "";
  1446. List<int> pagenums = new List<int>();
  1447. pagenums.Clear();
  1448. switch (data.PageMode)
  1449. {
  1450. case 1:
  1451. for (int i = 0; i < pagecount; i++)
  1452. {
  1453. pagenums.Add(i + 1);
  1454. }
  1455. pageName = "1-" + pagecount;
  1456. break;
  1457. case 2:
  1458. int count = (pagecount + 1) / 2;
  1459. for (int i = 0; i < count; i++)
  1460. {
  1461. pagenums.Add(i * 2 + 1);
  1462. }
  1463. pageName = "OddPages";
  1464. break;
  1465. case 3:
  1466. if (pagecount == 1)
  1467. return;
  1468. count = pagecount / 2;
  1469. for (int i = 0; i < count; i++)
  1470. {
  1471. pagenums.Add(i * 2 + 2);
  1472. }
  1473. pageName = "EvenPages";
  1474. break;
  1475. case 4:
  1476. pagenums = data.PageParm;
  1477. pageName = data.PageName;
  1478. break;
  1479. default:
  1480. break;
  1481. }
  1482. System.Windows.Forms.FolderBrowserDialog dialog = new System.Windows.Forms.FolderBrowserDialog();
  1483. if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
  1484. {
  1485. if (string.IsNullOrEmpty(dialog.SelectedPath))
  1486. {
  1487. return;
  1488. }
  1489. }
  1490. else
  1491. return;
  1492. string selectedfile = "";
  1493. if (data.ExtractToSingleFile)
  1494. {
  1495. for (int i = 0; i < pagenums.Count; i++)
  1496. {
  1497. string filename = pdfViewer.Document.FileName + " " + (pagenums[i]) + ".pdf";
  1498. string path = System.IO.Path.Combine(dialog.SelectedPath, filename);
  1499. path = CreateFilePath(path);
  1500. selectedfile = path;
  1501. CPDFDocument savedoc = CPDFDocument.CreateDocument();
  1502. bool result = savedoc.ImportPages(pdfViewer.Document, (pagenums[i]).ToString());
  1503. if (!result)
  1504. {
  1505. savedoc.Release();
  1506. continue;
  1507. }
  1508. result = savedoc.WriteToFilePath(path);
  1509. if (!result)
  1510. {
  1511. savedoc.Release();
  1512. continue;
  1513. }
  1514. savedoc.Release();
  1515. }
  1516. }
  1517. else
  1518. {
  1519. string filename = pdfViewer.Document.FileName + " " + pageName + ".pdf";
  1520. string path = System.IO.Path.Combine(dialog.SelectedPath, filename);
  1521. path = CreateFilePath(path);
  1522. selectedfile = path;
  1523. CPDFDocument savedoc = CPDFDocument.CreateDocument();
  1524. string range = (data.PageMode == 1 || data.PageMode == 4) ? pageName : String.Join(",", pagenums);
  1525. bool result = savedoc.ImportPages(pdfViewer.Document, range);
  1526. if (!result)
  1527. {
  1528. return;
  1529. }
  1530. result = savedoc.WriteToFilePath(path);
  1531. if (!result)
  1532. {
  1533. }
  1534. savedoc.Release();
  1535. }
  1536. if (data.DeleteAfterExtract)
  1537. {
  1538. List<ListBoxItem> items = new List<ListBoxItem>();
  1539. for (int i = 0; i < pagenums.Count; i++)
  1540. {
  1541. ListBoxItem item = PageEditListBox.Items[pagenums[i]-1] as ListBoxItem;
  1542. items.Add(item);
  1543. }
  1544. DoDelete(items, false);
  1545. pdfViewer.UndoManager.ClearHistory();
  1546. pdfViewer.UndoManager.CanSave = true;
  1547. ItemsInViewHitTest();
  1548. }
  1549. Process.Start(@"explorer.exe", "/select,\"" + selectedfile + "\"");
  1550. }
  1551. private void DoPaste()
  1552. {
  1553. if (pdfViewer == null) return;
  1554. if (ViewportHelper.CopyDoc == null)
  1555. {
  1556. return;
  1557. }
  1558. int insertIndex = 0;
  1559. for (int k = 0; k < PageEditListBox.SelectedItems.Count; k++)
  1560. {
  1561. if (insertIndex < PageEditListBox.Items.IndexOf(PageEditListBox.SelectedItems[k] as ListBoxItem))
  1562. insertIndex = PageEditListBox.Items.IndexOf(PageEditListBox.SelectedItems[k] as ListBoxItem);
  1563. }
  1564. insertIndex++;
  1565. int pagecount = ViewportHelper.CopyDoc.PageCount;
  1566. bool result = pdfViewer.Document.ImportPagesAtIndex(ViewportHelper.CopyDoc, "1-" + pagecount, insertIndex);
  1567. if (!result)
  1568. {
  1569. return;
  1570. }
  1571. pdfViewer.ReloadDocument();
  1572. AddBlankPages(pagecount, insertIndex);
  1573. ItemsInViewHitTest();
  1574. pdfViewer.UndoManager.ClearHistory();
  1575. pdfViewer.UndoManager.CanSave = true;
  1576. RefreshBookMarkList();
  1577. List<ListBoxItem> pageList = new List<ListBoxItem>();
  1578. PageEditListBox.SelectedItems.Clear();
  1579. for (int i = 0; i < pagecount; i++)
  1580. {
  1581. pageList.Add(PageEditListBox.Items[insertIndex + i] as ListBoxItem);
  1582. PageEditListBox.SelectedItems.Add(PageEditListBox.Items[insertIndex + i] as ListBoxItem);
  1583. }
  1584. UpdateAllPageNum();
  1585. }
  1586. private void DoCopy()
  1587. {
  1588. if (pdfViewer == null) return;
  1589. if (PageEditListBox.SelectedItems.Count < 1)
  1590. {
  1591. ShowAlertWithTimeout(AlertType.EmptyPageAlert);
  1592. return;
  1593. }
  1594. ViewportHelper.CopyDoc = null;
  1595. ViewportHelper.CopyDoc = CPDFDocument.CreateDocument();
  1596. string pageParam = GetPageParam();
  1597. bool result = ViewportHelper.CopyDoc.ImportPages(pdfViewer.Document, pageParam);
  1598. if (!result)
  1599. {
  1600. return;
  1601. }
  1602. }
  1603. private void DoExchange(List<ListBoxItem> pageLists)
  1604. {
  1605. if (pageLists.Count <= 1)
  1606. {
  1607. return;
  1608. }
  1609. List<int> pages = new List<int>();
  1610. for (int i = 0; i < pageLists.Count; i++)
  1611. {
  1612. int pageIndex = PageEditListBox.Items.IndexOf(pageLists[i] as ListBoxItem);
  1613. pages.Add(pageIndex);
  1614. }
  1615. pages.Sort();
  1616. for (int i = 0; i < pages.Count; i++)
  1617. {
  1618. int preindex = pages[i];
  1619. int laterIndex = pages[pages.Count - i - 1];
  1620. if (laterIndex <= preindex)
  1621. return;
  1622. var sourceitem = PageEditListBox.Items[preindex] as ListBoxItem;
  1623. var targetitem = PageEditListBox.Items[laterIndex] as ListBoxItem;
  1624. bindPageList.Remove(sourceitem);
  1625. bindPageList.Remove(targetitem);
  1626. bindPageList.Insert(preindex, targetitem);
  1627. bindPageList.Insert(laterIndex, sourceitem);
  1628. pdfViewer.Document.ExchangePage(preindex, laterIndex);
  1629. pdfViewer.UndoManager.ClearHistory();
  1630. pdfViewer.UndoManager.CanSave = true;
  1631. PageEditListBox.SelectedItems.Add(targetitem);
  1632. PageEditListBox.SelectedItems.Add(sourceitem);
  1633. }
  1634. }
  1635. private void DoDelete(List<ListBoxItem> pageLists, bool tip)
  1636. {
  1637. if (pageLists.Count == 0)
  1638. {
  1639. ShowAlertWithTimeout(AlertType.EmptyPageAlert);
  1640. return;
  1641. }
  1642. if (pageLists.Count == PageEditListBox.Items.Count)
  1643. {
  1644. ShowAlertWithTimeout(AlertType.AllPageAlert);
  1645. return;
  1646. }
  1647. Winform.DialogResult result = Winform.DialogResult.OK;
  1648. if (tip)
  1649. {
  1650. result = Winform.MessageBox.Show(string.Format("Do you want to delete page {0}", GetPageParam()), "Delete", Winform.MessageBoxButtons.OKCancel, Winform.MessageBoxIcon.Warning);
  1651. }
  1652. if (result == Winform.DialogResult.OK || !tip)
  1653. {
  1654. List<int> pages = new List<int>();
  1655. for (int i = 0; i < pageLists.Count; i++)
  1656. {
  1657. var index = PageEditListBox.Items.IndexOf(pageLists[i]);
  1658. pages.Add(index);
  1659. }
  1660. pages.Sort();
  1661. if (pages.Count == 0) return;
  1662. for (int i = pages.Count - 1; i >= 0; i--)
  1663. {
  1664. bindPageList.RemoveAt(pages[i]);
  1665. }
  1666. var r = pdfViewer.Document.RemovePages(pages.ToArray());
  1667. if (!r)
  1668. {
  1669. return;
  1670. }
  1671. pdfViewer.UndoManager.ClearHistory();
  1672. pdfViewer.UndoManager.CanSave = true;
  1673. UpdateAllPageNum();
  1674. pdfViewer.ReloadDocument();
  1675. }
  1676. }
  1677. private List<ListBoxItem> GetListFromSelectedItems()
  1678. {
  1679. List<ListBoxItem> itemlists = new List<ListBoxItem>();
  1680. for (int i = 0; i < PageEditListBox.SelectedItems.Count; i++)
  1681. {
  1682. itemlists.Add(PageEditListBox.SelectedItems[i] as ListBoxItem);
  1683. }
  1684. return itemlists;
  1685. }
  1686. public static bool GetPagesInRange(ref List<int> pageList, string pageRange, int count, char[] enumerationSeparator, char[] rangeSeparator, bool inittag = false)
  1687. {
  1688. string[] rangeSplit = pageRange.Split(enumerationSeparator);
  1689. pageList.Clear();
  1690. foreach (string range in rangeSplit)
  1691. {
  1692. int starttag = 1;
  1693. if (inittag)
  1694. {
  1695. starttag = 0;
  1696. }
  1697. if (range.Contains("-"))
  1698. {
  1699. try
  1700. {
  1701. string[] limits = range.Split(rangeSeparator);
  1702. if (limits.Length >= 2 && !string.IsNullOrWhiteSpace(limits[0]) && !string.IsNullOrWhiteSpace(limits[1]))
  1703. {
  1704. int start = int.Parse(limits[0]);
  1705. int end = int.Parse(limits[1]);
  1706. if ((start < starttag) || (end > count) || (start > end))
  1707. {
  1708. return false;
  1709. }
  1710. for (int i = start; i <= end; ++i)
  1711. {
  1712. if (pageList.Contains(i))
  1713. {
  1714. return false;
  1715. }
  1716. pageList.Add(i - 1);
  1717. }
  1718. continue;
  1719. }
  1720. }
  1721. catch (Exception ex)
  1722. {
  1723. return false;
  1724. }
  1725. }
  1726. int pageNr;
  1727. try
  1728. {
  1729. pageNr = int.Parse(range);
  1730. }
  1731. catch (Exception)
  1732. {
  1733. return false;
  1734. }
  1735. if (pageNr < starttag || pageNr > count)
  1736. {
  1737. return false;
  1738. }
  1739. if (pageList.Contains(pageNr))
  1740. {
  1741. return false;
  1742. }
  1743. pageList.Add(pageNr - 1);
  1744. }
  1745. return true;
  1746. }
  1747. private void DoAddFromOtherPdf(string filepath, string pagerange, int insertindex, string password)
  1748. {
  1749. CPDFDocument doc = CPDFDocument.InitWithFilePath(filepath);
  1750. if(doc.IsLocked && password != string.Empty)
  1751. {
  1752. if(!doc.UnlockWithPassword(password))
  1753. {
  1754. return;
  1755. }
  1756. }
  1757. int pagecount = 0;
  1758. string insertRange = "";
  1759. if (pagerange == "AllPages")
  1760. {
  1761. pagecount = doc.PageCount;
  1762. insertRange = "1-" + pagecount;
  1763. }
  1764. else if (pagerange == "OddPages")
  1765. {
  1766. pagecount = (doc.PageCount + 1) / 2;
  1767. int[] page = new int[(doc.PageCount + 1) / 2];
  1768. for (int i = 0; i < page.Length; i++)
  1769. {
  1770. page[i] = i * 2 + 1;
  1771. }
  1772. insertRange = string.Join(",", page);
  1773. }
  1774. else if (pagerange == "EvenPages")
  1775. {
  1776. if (doc.PageCount == 1)
  1777. {
  1778. insertRange = "1";
  1779. pagecount = 1;
  1780. }
  1781. else
  1782. {
  1783. pagecount = doc.PageCount / 2;
  1784. int[] page = new int[doc.PageCount / 2];
  1785. for (int i = 0; i < page.Length; i++)
  1786. {
  1787. page[i] = i * 2 + 2;
  1788. }
  1789. insertRange = string.Join(",", page);
  1790. }
  1791. }
  1792. else
  1793. {
  1794. List<int> page = new List<int>();
  1795. GetPagesInRange(ref page, pagerange, doc.PageCount, new char[] { ',' }, new char[] { '-' });
  1796. insertRange = pagerange;
  1797. pagecount = page.Count;
  1798. }
  1799. var result = pdfViewer.Document.ImportPagesAtIndex(doc, insertRange, insertindex);
  1800. if (!result)
  1801. {
  1802. return;
  1803. }
  1804. doc.Release();
  1805. RefreshThumbnail();
  1806. PageEditListBox.SelectedItems.Clear();
  1807. for (int i = insertindex; i < insertindex + pagecount; i++)
  1808. {
  1809. PageEditListBox.SelectedItems.Add(PageEditListBox.Items[i] as ListBoxItem);
  1810. }
  1811. }
  1812. private string GetPageParam()
  1813. {
  1814. string pageParam = "";
  1815. List<int> pagesList = new List<int>();
  1816. for (int i = 0; i < PageEditListBox.SelectedItems.Count; i++)
  1817. {
  1818. var item = PageEditListBox.SelectedItems[i] as ListBoxItem;
  1819. var page = GetPageNumTextBlock(item);
  1820. if (page != null)
  1821. {
  1822. pagesList.Add(int.Parse(page.Text));
  1823. }
  1824. }
  1825. if (pagesList.Count != 0)
  1826. {
  1827. pagesList.Sort();
  1828. for (int i = 0; i < pagesList.Count; i++)
  1829. {
  1830. if (i == 0)
  1831. {
  1832. pageParam += pagesList[0].ToString();
  1833. }
  1834. else
  1835. {
  1836. if (pagesList[i] == pagesList[i - 1] + 1)
  1837. {
  1838. if (i >= 2)
  1839. {
  1840. if (pagesList[i - 1] != pagesList[i - 2] + 1)
  1841. pageParam += "-";
  1842. }
  1843. else
  1844. pageParam += "-";
  1845. if (i == pagesList.Count - 1)
  1846. {
  1847. pageParam += pagesList[i].ToString();
  1848. }
  1849. }
  1850. else
  1851. {
  1852. if (i >= 2)
  1853. {
  1854. if (pagesList[i - 1] == pagesList[i - 2] + 1)
  1855. pageParam += pagesList[i - 1].ToString();
  1856. }
  1857. pageParam += "," + pagesList[i].ToString();
  1858. }
  1859. }
  1860. }
  1861. }
  1862. return pageParam;
  1863. }
  1864. public static BitmapSource ToBitmapSource(string path)
  1865. {
  1866. System.Drawing.Icon ico = System.Drawing.Icon.ExtractAssociatedIcon(path);
  1867. System.Drawing.Bitmap bitmap = ico.ToBitmap();
  1868. BitmapSource returnSource;
  1869. try
  1870. {
  1871. returnSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(bitmap.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
  1872. }
  1873. catch
  1874. {
  1875. returnSource = null;
  1876. }
  1877. return returnSource;
  1878. }
  1879. private Tuple<int, int, int> GetRoughViewportRange(ListBox view, Size itemSize, Thickness itemMargin)
  1880. {
  1881. var scrollViewer = GetScrollHost(view);
  1882. if (pdfViewer == null || pdfViewer.Document == null || scrollViewer == null || scrollViewer.ActualHeight == 0 || scrollViewer.ActualWidth == 0)//视图展开
  1883. return new Tuple<int, int, int>(0, 0, 0);
  1884. try
  1885. {
  1886. var currentHeight = scrollViewer.ActualHeight - view.Padding.Top;
  1887. var currentWidth = scrollViewer.ActualWidth;
  1888. var columnCount = (int)(currentWidth / (itemSize.Width + itemMargin.Left));
  1889. var rowCount = (int)Math.Ceiling(currentHeight / (itemSize.Height + itemMargin.Bottom));
  1890. var preItemCount = (int)((scrollViewer.VerticalOffset / scrollViewer.ExtentHeight) * ((pdfViewer.Document.PageCount + columnCount - 1) / columnCount));//滑动百分比*行数 = 大概的垂直位置
  1891. preItemCount = preItemCount * columnCount;
  1892. var preEnd = (int)(((scrollViewer.VerticalOffset + scrollViewer.ActualHeight) / scrollViewer.ExtentHeight) * ((pdfViewer.Document.PageCount + columnCount - 1) / columnCount));
  1893. preEnd = preEnd * columnCount + columnCount - 1;
  1894. var middle = (int)Math.Ceiling(preItemCount + preEnd / 2d);
  1895. return new Tuple<int, int, int>(
  1896. Math.Max(preItemCount, 0),
  1897. Math.Min(view.Items.Count, preEnd),
  1898. middle);
  1899. }
  1900. catch (Exception ex)
  1901. {
  1902. }
  1903. return new Tuple<int, int, int>(0, 0, 0);
  1904. }
  1905. private void ShowAlertWithTimeout(AlertType alertType)
  1906. {
  1907. AlertBorder.Visibility = Visibility.Visible;
  1908. AlertBorder.Opacity = 1.0;
  1909. if (alertType == AlertType.EmptyPageAlert)
  1910. {
  1911. AlertTextBlock.Text = "Please select at least one page.";
  1912. }
  1913. else if (alertType == AlertType.SinglePageALert)
  1914. {
  1915. AlertTextBlock.Text = "Please select above two pages.";
  1916. }
  1917. else if (alertType == AlertType.AllPageAlert)
  1918. {
  1919. AlertTextBlock.Text = "Please don't select all pages";
  1920. }
  1921. DoubleAnimation animation = new DoubleAnimation();
  1922. animation.From = 1.0;
  1923. animation.To = 0.0;
  1924. animation.Duration = TimeSpan.FromSeconds(3);
  1925. AlertBorder.BeginAnimation(OpacityProperty, animation);
  1926. }
  1927. #endregion
  1928. private void UserControl_MouseEnter(object sender, MouseEventArgs e)
  1929. {
  1930. MidLane.Visibility = Visibility.Collapsed;
  1931. }
  1932. private void UserControl_SizeChanged(object sender, SizeChangedEventArgs e)
  1933. {
  1934. ItemsInViewHitTest();
  1935. }
  1936. }
  1937. public class InsertEventClass : EventArgs
  1938. {
  1939. public InsertType InsertType = InsertType.BlankPages;
  1940. public string FilePath = string.Empty;
  1941. public double PageWidth = 210 * 2.54;
  1942. public double PageHeight = 297 * 2.54;
  1943. public string PageRange = "0";
  1944. public int InsertIndex = 0;
  1945. public string Password = string.Empty;
  1946. }
  1947. public enum InsertType
  1948. {
  1949. BlankPages,
  1950. CustomBlankPages,
  1951. FromOtherPDF
  1952. }
  1953. /// <summary>
  1954. /// The parameter class used for extraction
  1955. /// </summary>
  1956. public class ExtractEventClass : EventArgs
  1957. {
  1958. /// <summary>
  1959. /// 1- All pages 2 - Odd pages 3 - Even pages 4 - Custom ranges
  1960. /// </summary>
  1961. public int PageMode;
  1962. /// <summary>
  1963. /// PageMode = 1,2,3 PageParm = null;
  1964. /// </summary>
  1965. public List<int> PageParm;
  1966. /// <summary>
  1967. /// In custom mode, the text content is passed over
  1968. /// </summary>
  1969. public string PageName = "";
  1970. /// <summary>
  1971. /// Whether to split into a single file
  1972. /// </summary>
  1973. public bool ExtractToSingleFile;
  1974. /// <summary>
  1975. /// Delete the page after extraction
  1976. /// </summary>
  1977. public bool DeleteAfterExtract;
  1978. }
  1979. public enum AlertType
  1980. {
  1981. EmptyPageAlert,
  1982. SinglePageALert,
  1983. AllPageAlert,
  1984. }
  1985. }