CPDFPageEditControl.xaml.cs 80 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208
  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. private void InsertBlank_Click(object sender, RoutedEventArgs e)
  837. {
  838. var send = sender as MenuItem;
  839. }
  840. private void Replace_Click(object sender, RoutedEventArgs e)
  841. {
  842. DoReplace();
  843. }
  844. public void Copy_Click(object sender, RoutedEventArgs e)
  845. {
  846. DoCopy();
  847. DoPaste();
  848. ViewportHelper.CopyDoc = null;
  849. }
  850. private void PageEditListBox_SizeChanged(object sender, SizeChangedEventArgs e)
  851. {
  852. PageEditListBox.ScrollIntoView(PageEditListBox.SelectedItem);
  853. }
  854. private void PageEditor_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
  855. {
  856. if (pdfViewer == null)
  857. return;
  858. if (isFirstLoad)
  859. {
  860. isFirstLoad = false;
  861. return;
  862. }
  863. if ((bool)e.NewValue == true && pdfViewer != null && pdfViewer.CurrentIndex >= 0)
  864. {
  865. RefreshThumbnail();
  866. }
  867. if (pdfViewer?.CurrentIndex >= PageEditListBox.Items.Count || PageEditListBox.Items.Count == 0)
  868. return;
  869. ListBoxItem item = PageEditListBox.Items[pdfViewer?.CurrentIndex == -1 ? 0 : pdfViewer.CurrentIndex] as ListBoxItem;
  870. PageEditListBox.ScrollIntoView(PageEditListBox.SelectedItem);
  871. PageEditListBox.SelectedItem = item;
  872. }
  873. private async void ListBoxItem_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
  874. {
  875. if (!Keyboard.IsKeyDown(Key.LeftCtrl) && !Keyboard.IsKeyDown(Key.LeftShift))
  876. {
  877. var item = sender as ListBoxItem;
  878. Image img = GetImageElement(item);
  879. int itemindex = PageEditListBox.Items.IndexOf(item);
  880. if (img.Source == null)
  881. {
  882. await pdfViewer.GetThumbnail(itemindex, (int)img.Width, (int)img.Height);
  883. }
  884. pdfViewer.GoToPage(itemindex);
  885. }
  886. }
  887. private void PageGrid_PreviewDragEnter(object sender, DragEventArgs e)
  888. {
  889. var file = (System.Array)e.Data.GetData(DataFormats.FileDrop);
  890. if (file == null || file.Length > 1)
  891. { return; }
  892. foreach (var f in file)
  893. {
  894. dragingEnterPath = f.ToString();
  895. if (dragingEnterPath != null)
  896. {
  897. isDragingEnter = true;
  898. }
  899. }
  900. }
  901. private void ContextMenu_Loaded(object sender, RoutedEventArgs e)
  902. {
  903. if (ViewportHelper.CopyDoc == null)
  904. {
  905. var s = sender as ContextMenu;
  906. foreach (var item in s.Items)
  907. {
  908. if ((item as MenuItem).Name == "Paste")
  909. {
  910. (item as MenuItem).IsEnabled = false;
  911. }
  912. }
  913. }
  914. else
  915. {
  916. var s = sender as ContextMenu;
  917. foreach (var item in s.Items)
  918. {
  919. if ((item as MenuItem).Name == "Paste")
  920. {
  921. (item as MenuItem).IsEnabled = true;
  922. }
  923. }
  924. }
  925. if (PageEditListBox.SelectedItems.Count < 2)
  926. {
  927. var s = sender as ContextMenu;
  928. foreach (var item in s.Items)
  929. {
  930. if ((item as MenuItem).Name == "Exchange")
  931. {
  932. (item as MenuItem).IsEnabled = false;
  933. }
  934. }
  935. }
  936. else
  937. {
  938. var s = sender as ContextMenu;
  939. foreach (var item in s.Items)
  940. {
  941. if ((item as MenuItem).Name == "Exchange")
  942. {
  943. (item as MenuItem).IsEnabled = true;
  944. }
  945. }
  946. }
  947. }
  948. private void UserControl_KeyDown(object sender, KeyEventArgs e)
  949. {
  950. if ((Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control && e.Key == Key.A)
  951. {
  952. if (PageEditListBox.SelectedItems.Count == PageEditListBox.Items.Count)
  953. {
  954. PageEditListBox.UnselectAll();
  955. e.Handled = true;
  956. }
  957. }
  958. }
  959. #endregion
  960. #region Method
  961. public void LoadThumbnails(CPDFViewer viewer)
  962. {
  963. if (viewer == null || viewer.Document == null)
  964. return;
  965. if (pdfViewer != null && viewer != pdfViewer)
  966. {
  967. pdfViewer = viewer;
  968. this.PopulateThumbnailList();
  969. pdfViewer.OnThumbnailGenerated += _pdfviewer_OnThumbnailGenerated;
  970. pdfViewer.RenderCompleted += PdfViewer_InfoChanged;
  971. pdfViewer.AnnotEditHandler += PdfViewer_AnnotEditHandler;
  972. }
  973. pdfViewer = viewer;
  974. if (!isThumbInitialized)
  975. {
  976. this.PopulateThumbnailList();
  977. isThumbInitialized = true;
  978. pdfViewer.OnThumbnailGenerated += _pdfviewer_OnThumbnailGenerated;
  979. }
  980. if (pdfViewer.CurrentIndex >= 0 && PageEditListBox.Items.Count > pdfViewer.CurrentIndex)
  981. {
  982. PageEditListBox.ScrollIntoView(PageEditListBox.Items[pdfViewer.CurrentIndex]);
  983. (PageEditListBox.Items[pdfViewer.CurrentIndex] as ListBoxItem).IsSelected = true;
  984. PageEditListBox.SelectedIndex = pdfViewer.CurrentIndex;
  985. }
  986. RefreshBookMarkList();
  987. }
  988. public void PopulateThumbnailList()
  989. {
  990. visiblePageIndexes.Clear();
  991. bindPageList.Clear();
  992. // GC.Collect();
  993. int thumbnailWidth = thumbnailSize[zoomLevel];
  994. for (int i = 0; i < pdfViewer.Document.PageCount; i++)
  995. {
  996. Size pageSize = pdfViewer.Document.GetPageSize(i);
  997. if (pageSize.Height == 0 || pageSize.Width == 0)
  998. continue;
  999. int imageWidth = pageSize.Width > pageSize.Height ? thumbnailWidth * 2 : (int)(pageSize.Width / pageSize.Height * thumbnailWidth * 2);
  1000. int imageHeight = pageSize.Height > pageSize.Width ? thumbnailWidth * 2 : (int)(pageSize.Height / pageSize.Width * thumbnailWidth * 2);
  1001. Image img = new Image()
  1002. {
  1003. //Margin = new Thickness(0, 0, 5, 0),
  1004. Width = imageWidth,
  1005. Height = imageHeight,
  1006. Stretch = Stretch.Uniform,
  1007. };
  1008. Grid grid = new Grid();
  1009. grid.Children.Add(img);
  1010. List<Point> points = new List<Point>()
  1011. {
  1012. new Point(16.75,1.25),
  1013. new Point(3.25,1.25 ),
  1014. new Point(3.25,19.4013878),
  1015. new Point(10,14.902),
  1016. new Point(16.75,19.4013878),
  1017. };
  1018. Polygon bookmark = new Polygon()
  1019. {
  1020. Points = new PointCollection(points),
  1021. Fill = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#FFBB00")),
  1022. Margin = new Thickness(0, 16, 16, 0),
  1023. VerticalAlignment = VerticalAlignment.Top,
  1024. HorizontalAlignment = HorizontalAlignment.Right,
  1025. Visibility = Visibility.Collapsed,
  1026. };
  1027. grid.Children.Add(bookmark);
  1028. Border border = new Border()
  1029. {
  1030. BorderThickness = new Thickness(2),
  1031. BorderBrush = new SolidColorBrush((System.Windows.Media.Color)System.Windows.Media.ColorConverter.ConvertFromString("#A0A2AE")),
  1032. Child = grid,
  1033. };
  1034. Viewbox viewBox = new Viewbox()
  1035. {
  1036. Margin = new Thickness(0, 8, 0, 0),
  1037. Stretch = System.Windows.Media.Stretch.Uniform,
  1038. Width = thumbnailWidth,
  1039. Height = thumbnailWidth,
  1040. Child = border,
  1041. };
  1042. TextBlock text = new TextBlock()
  1043. {
  1044. HorizontalAlignment = System.Windows.HorizontalAlignment.Center,
  1045. Text = (i + 1).ToString(),
  1046. Foreground = Brushes.Black,
  1047. Margin = new Thickness(0, 8, 0, 8),
  1048. };
  1049. StackPanel panel = new StackPanel();
  1050. panel.Children.Add(viewBox);
  1051. panel.Children.Add(text);
  1052. ListBoxItem item = new ListBoxItem();
  1053. item.Content = panel;
  1054. item.Tag = i;
  1055. item.Margin = new Thickness(6, 10, 6, 10);
  1056. bindPageList.Add(item);
  1057. }
  1058. PageEditListBox.ItemsSource = bindPageList;
  1059. }
  1060. public ListBoxItem GetNewItem(int ItemIndex)
  1061. {
  1062. int thumbnailWidth = thumbnailSize[zoomLevel];
  1063. Size pageSize = pdfViewer.Document.GetPageSize(ItemIndex);
  1064. if (pageSize.Width == 0 || pageSize.Height == 0)
  1065. {
  1066. pageSize = new Size(228, 300);
  1067. }
  1068. int imageWidth = pageSize.Width > pageSize.Height ? thumbnailWidth * 2 : (int)(pageSize.Width / pageSize.Height * thumbnailWidth * 2);
  1069. int imageHeight = pageSize.Height > pageSize.Width ? thumbnailWidth * 2 : (int)(pageSize.Height / pageSize.Width * thumbnailWidth * 2);
  1070. Image img = new Image()
  1071. {
  1072. Width = imageWidth,
  1073. Height = imageHeight,
  1074. Stretch = Stretch.Uniform,
  1075. };
  1076. Grid grid = new Grid();
  1077. grid.Children.Add(img);
  1078. List<Point> points = new List<Point>()
  1079. {
  1080. new Point(16.75,1.25),
  1081. new Point(3.25,1.25 ),
  1082. new Point(3.25,19.4013878),
  1083. new Point(10,14.902),
  1084. new Point(16.75,19.4013878),
  1085. };
  1086. Polygon bookmark = new Polygon()
  1087. {
  1088. Points = new PointCollection(points),
  1089. Fill = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#FFBB00")),
  1090. Margin = new Thickness(0, 8, 8, 0),
  1091. VerticalAlignment = VerticalAlignment.Top,
  1092. HorizontalAlignment = HorizontalAlignment.Right,
  1093. Visibility = Visibility.Collapsed,
  1094. };
  1095. grid.Children.Add(bookmark);
  1096. Border border = new Border()
  1097. {
  1098. BorderThickness = new Thickness(2),
  1099. BorderBrush = new SolidColorBrush((System.Windows.Media.Color)System.Windows.Media.ColorConverter.ConvertFromString("#A0A2AE")),
  1100. Child = grid,
  1101. };
  1102. Viewbox viewBox = new Viewbox()
  1103. {
  1104. Margin = new Thickness(0, 8, 0, 0),
  1105. Stretch = System.Windows.Media.Stretch.Uniform,
  1106. Width = thumbnailWidth,
  1107. Height = thumbnailWidth,
  1108. Child = border,
  1109. };
  1110. TextBlock text = new TextBlock()
  1111. {
  1112. HorizontalAlignment = System.Windows.HorizontalAlignment.Center,
  1113. Text = (ItemIndex + 1).ToString(),
  1114. Foreground = Brushes.Black,
  1115. Margin = new Thickness(0, 8, 0, 8),
  1116. };
  1117. StackPanel panel = new StackPanel();
  1118. panel.Children.Add(viewBox);
  1119. panel.Children.Add(text);
  1120. ListBoxItem item = new ListBoxItem();
  1121. item.Content = panel;
  1122. item.Tag = ItemIndex;
  1123. item.Margin = new Thickness(6, 10, 6, 10);
  1124. return item;
  1125. }
  1126. public void AddBlankPages(int pagecount, int insertindex)
  1127. {
  1128. for (int i = 0; i < pagecount; i++)
  1129. {
  1130. var item = GetNewItem(insertindex + i);
  1131. bindPageList.Insert(insertindex + i, item);
  1132. if (visiblePageIndexes.Contains(insertindex + i))
  1133. visiblePageIndexes.Remove(insertindex + i);
  1134. }
  1135. PageEditListBox.UpdateLayout();
  1136. }
  1137. private async void RenderPage(int pageindex)
  1138. {
  1139. var range = GetRoughViewportRange(PageEditListBox, (PageEditListBox.Items[0] as ListBoxItem).DesiredSize, new Thickness(6, 10, 6, 10));
  1140. if (pageindex < range.Item1 || pageindex > range.Item2)
  1141. return;
  1142. ListBoxItem item = PageEditListBox.Items[pageindex] as ListBoxItem;
  1143. Image img = GetImageElement(item);
  1144. await pdfViewer.GetThumbnail(pageindex, (int)img.Width, (int)img.Height);
  1145. }
  1146. private async void ItemsInViewHitTest()
  1147. {
  1148. if (pdfViewer == null || pdfViewer.Document == null)
  1149. return;
  1150. try
  1151. {
  1152. ScrollViewer sv = GetScrollHost(PageEditListBox);
  1153. if (sv == null) return;
  1154. if (VisualTreeHelper.GetParent(this) == null)
  1155. return;
  1156. var range = GetRoughViewportRange(PageEditListBox, (PageEditListBox.Items[0] as ListBoxItem).DesiredSize, new Thickness(6, 10, 6, 10));
  1157. for (int i = 0; i < PageEditListBox.Items.Count; ++i)
  1158. {
  1159. ListBoxItem item = PageEditListBox.Items[i] as ListBoxItem;
  1160. Image img = GetImageElement(item);
  1161. if (i >= (range.Item1 - 1) && i <= range.Item2 || ViewportHelper.IsInViewport(sv, item))
  1162. {
  1163. if (img.Source == null && !visiblePageIndexes.Contains(i))
  1164. {
  1165. visiblePageIndexes.Add(i);
  1166. await Task.Delay(1);
  1167. await pdfViewer.GetThumbnail(i, (int)img.Width, (int)img.Height);
  1168. Debug.WriteLine("Page {0} is visible, asking for thumb", (i + 1));
  1169. }
  1170. else if (img.Source == null)
  1171. {
  1172. await pdfViewer.GetThumbnail(i, (int)img.Width, (int)img.Height);
  1173. Debug.WriteLine("Page {0} is visible, asking for thumb", (i + 1));
  1174. }
  1175. }
  1176. else
  1177. {
  1178. if (visiblePageIndexes.Contains(i))
  1179. {
  1180. Image image = GetImageElement(PageEditListBox.Items[i] as ListBoxItem);
  1181. if (image.Source != null)
  1182. {
  1183. image.Source = null;
  1184. Debug.WriteLine("Page {0} is out of range, removed thumb", (i + 1));
  1185. }
  1186. else
  1187. {
  1188. Debug.WriteLine("Page {0} is out of range, but had no thumb", (i + 1));
  1189. }
  1190. visiblePageIndexes.Remove(i);
  1191. }
  1192. }
  1193. }
  1194. }
  1195. catch (Exception ex)
  1196. {
  1197. Debug.WriteLine(ex.ToString());
  1198. }
  1199. }
  1200. public void RefreshBookMarkList()
  1201. {
  1202. if (pdfViewer != null)
  1203. {
  1204. var booklist = pdfViewer.Document.GetBookmarkList();
  1205. if (booklist == null) return;
  1206. List<int> marks = new List<int>();
  1207. for (int i = 0; i < booklist.Count; i++)
  1208. {
  1209. marks.Add(booklist[i].PageIndex);
  1210. }
  1211. for (int k = 0; k < PageEditListBox.Items.Count; k++)
  1212. {
  1213. Polygon polygon = GetBookMarkIco(PageEditListBox.Items[k] as ListBoxItem);
  1214. if (marks.Contains(k))
  1215. polygon.Visibility = Visibility.Visible;
  1216. else
  1217. polygon.Visibility = Visibility.Collapsed;
  1218. }
  1219. }
  1220. }
  1221. private void UpdateSelectedIndex()
  1222. {
  1223. if (PageEditListBox.Items.Count == 0)
  1224. PageEditListBox.SelectedIndex = -1;
  1225. else if (PageEditListBox.Items.Count <= pdfViewer.CurrentIndex)
  1226. this.PageEditListBox.SelectedIndex = 0;
  1227. else if (PageEditListBox.SelectedIndex != pdfViewer.CurrentIndex)
  1228. PageEditListBox.SelectedIndex = pdfViewer.CurrentIndex;
  1229. PageEditListBox.ScrollIntoView(PageEditListBox.Items[PageEditListBox.SelectedIndex]);
  1230. }
  1231. private Image GetImageElement(ListBoxItem item)
  1232. {
  1233. Viewbox viewBox = (item.Content as StackPanel).Children[0] as Viewbox;
  1234. Image img = ((viewBox.Child as Border).Child as Grid).Children[0] as Image;
  1235. return img;
  1236. }
  1237. private Polygon GetBookMarkIco(ListBoxItem item)
  1238. {
  1239. Viewbox viewBox = (item.Content as StackPanel).Children[0] as Viewbox;
  1240. Polygon ico = ((viewBox.Child as Border).Child as Grid).Children[1] as Polygon;
  1241. return ico;
  1242. }
  1243. private StackPanel GetPanel(ListBoxItem item)
  1244. {
  1245. StackPanel panel = item.Content as StackPanel;
  1246. return panel;
  1247. }
  1248. private TextBlock GetPageNumTextBlock(ListBoxItem item)
  1249. {
  1250. TextBlock text = (item.Content as StackPanel).Children[1] as TextBlock;
  1251. return text;
  1252. }
  1253. public VirtualizingWrapPanel GetWrapPanel(ListBox listBox)
  1254. {
  1255. Border border = VisualTreeHelper.GetChild(listBox, 0) as Border;
  1256. var panel = Utils.FindVisualChild<VirtualizingWrapPanel>(border);
  1257. return panel;
  1258. }
  1259. private ScrollViewer GetScrollHost(ListBox listBox)
  1260. {
  1261. if (VisualTreeHelper.GetChildrenCount(listBox) > 0)
  1262. {
  1263. int s = VisualTreeHelper.GetChildrenCount(listBox);
  1264. Border border = VisualTreeHelper.GetChild(listBox, 0) as Border;
  1265. if (border != null)
  1266. {
  1267. return VisualTreeHelper.GetChild(border, 0) as ScrollViewer;
  1268. }
  1269. }
  1270. return null;
  1271. }
  1272. private void DragToSort(int sourceindex, int targetindex)
  1273. {
  1274. if (targetindex == sourceindex || targetindex < 0)
  1275. {
  1276. MidLane.Visibility = Visibility.Collapsed;
  1277. return;
  1278. }
  1279. var source = PageEditListBox.Items[sourceindex];
  1280. bindPageList.RemoveAt(sourceindex);
  1281. MidLane.Visibility = Visibility.Collapsed;
  1282. bindPageList.Insert(targetindex, source as ListBoxItem);
  1283. PageEditListBox.SelectedItems.Add(source);
  1284. var result = pdfViewer.Document.MovePage(sourceindex, targetindex);
  1285. if (!result)
  1286. {
  1287. MidLane.Visibility = Visibility.Collapsed;
  1288. return;
  1289. }
  1290. pdfViewer.ReloadDocument();
  1291. pdfViewer.GoToPage(PageEditListBox.SelectedIndex);
  1292. pdfViewer.UndoManager.ClearHistory();
  1293. pdfViewer.UndoManager.CanSave = true;
  1294. ItemsInViewHitTest();
  1295. this.PageMoved.Invoke(this, new RoutedEventArgs());
  1296. UpdateSortedPageNum(sourceindex, targetindex);
  1297. }
  1298. private void UpdateSortedPageNum(int sourceIndex, int targetIndex)
  1299. {
  1300. int sum = sourceIndex + targetIndex;
  1301. targetIndex = targetIndex > sourceIndex ? targetIndex : sourceIndex;
  1302. sourceIndex = sum - targetIndex;
  1303. sourceIndex = sourceIndex <= 0 ? 0 : sourceIndex;
  1304. targetIndex = targetIndex + 1 > PageEditListBox.Items.Count ? PageEditListBox.Items.Count - 1 : targetIndex;
  1305. for (int i = sourceIndex; i <= targetIndex; i++)
  1306. {
  1307. var item = PageEditListBox.Items[i] as ListBoxItem;
  1308. item.Tag = i;
  1309. TextBlock pagenum = GetPageNumTextBlock(item);
  1310. pagenum.Text = (i + 1).ToString();
  1311. }
  1312. }
  1313. private void UpdateAllPageNum()
  1314. {
  1315. for (int i = 0; i < PageEditListBox.Items.Count; i++)
  1316. {
  1317. var pagenum = GetPageNumTextBlock(PageEditListBox.Items[i] as ListBoxItem);
  1318. pagenum.Text = (i + 1).ToString();
  1319. (PageEditListBox.Items[i] as ListBoxItem).Tag = i;
  1320. }
  1321. }
  1322. public void DoInsert(EventArgs e)
  1323. {
  1324. var data = e as InsertEventClass;
  1325. if (data.InsertType == InsertType.BlankPages)
  1326. {
  1327. var size = pdfViewer.Document.GetPageSize(data.InsertIndex - 1);
  1328. if (size.Width == 0 || size.Height == 0)
  1329. size = pdfViewer.Document.GetPageSize(data.InsertIndex);
  1330. pdfViewer.Document.InsertPage(data.InsertIndex, size.Width, size.Height, null);
  1331. RefreshThumbnail();
  1332. PageEditListBox.SelectedItems.Clear();
  1333. PageEditListBox.SelectedIndex = data.InsertIndex;
  1334. }
  1335. else if (data.InsertType == InsertType.CustomBlankPages)
  1336. {
  1337. pdfViewer.Document.InsertPage(data.InsertIndex, data.PageWidth, data.PageHeight, null);
  1338. RefreshThumbnail();
  1339. PageEditListBox.SelectedItems.Clear();
  1340. PageEditListBox.SelectedIndex = data.InsertIndex;
  1341. }
  1342. else
  1343. {
  1344. DoAddFromOtherPdf(data.FilePath, data.PageRange, data.InsertIndex, data.Password);
  1345. }
  1346. UpdateAllPageNum();
  1347. pdfViewer.UndoManager.ClearHistory();
  1348. pdfViewer.UndoManager.CanSave = true;
  1349. pdfViewer.ReloadDocument();
  1350. PageEditListBox.ScrollIntoView(PageEditListBox.SelectedItem as ListBoxItem);
  1351. ItemsInViewHitTest();
  1352. }
  1353. public void DoReplace()
  1354. {
  1355. if (PageEditListBox.SelectedItems.Count < 1)
  1356. {
  1357. ShowAlertWithTimeout(AlertType.EmptyPageAlert);
  1358. return;
  1359. }
  1360. OpenFileDialog dialog = new OpenFileDialog();
  1361. dialog.Multiselect = false;
  1362. dialog.Filter = "(*.pdf)|*.pdf";
  1363. if ((bool)dialog.ShowDialog())
  1364. {
  1365. CPDFDocument doc = CPDFDocument.InitWithFilePath(dialog.FileName);
  1366. int pagecount = doc.PageCount;
  1367. int insertindex = PageEditListBox.Items.IndexOf(PageEditListBox.SelectedItem);
  1368. if (insertindex == -1)
  1369. insertindex = 0;
  1370. var result = pdfViewer.Document.ImportPagesAtIndex(doc, "1-" + pagecount, insertindex);
  1371. doc.Release();
  1372. for (int i = 0; i < pagecount; i++)
  1373. {
  1374. var item = GetNewItem(insertindex + i);
  1375. bindPageList.Insert(insertindex + i, item);
  1376. if (visiblePageIndexes.Contains(insertindex + i))
  1377. visiblePageIndexes.Remove(insertindex + i);
  1378. }
  1379. pdfViewer.UndoManager.ClearHistory();
  1380. pdfViewer.UndoManager.CanSave = true;
  1381. var list = GetListFromSelectedItems();
  1382. for (int i = insertindex; i < (insertindex + pagecount); i++)
  1383. {
  1384. if (i < PageEditListBox.Items.Count)
  1385. {
  1386. ListBoxItem t = PageEditListBox.Items[i] as ListBoxItem;
  1387. PageEditListBox.SelectedItems.Add(t);
  1388. }
  1389. }
  1390. DoDelete(list, false);
  1391. UpdateAllPageNum();
  1392. RefreshBookMarkList();
  1393. ItemsInViewHitTest();
  1394. }
  1395. }
  1396. private void DoRotate(double angleStep)
  1397. {
  1398. if (pdfViewer == null) return;
  1399. if (PageEditListBox.SelectedItems.Count < 1)
  1400. {
  1401. ShowAlertWithTimeout(AlertType.EmptyPageAlert);
  1402. return;
  1403. }
  1404. List<ListBoxItem> pages = new List<ListBoxItem>();
  1405. for (int i = 0; i < PageEditListBox.SelectedItems.Count; i++)
  1406. {
  1407. var image = GetImageElement(PageEditListBox.SelectedItems[i] as ListBoxItem);
  1408. pages.Add(PageEditListBox.SelectedItems[i] as ListBoxItem);
  1409. double angle = (double)image.LayoutTransform.GetValue(RotateTransform.AngleProperty);
  1410. angle += angleStep;
  1411. angle = angle % 360;
  1412. image.LayoutTransform = new RotateTransform(angle, image.ActualWidth / 2, image.ActualHeight / 2);
  1413. var index = PageEditListBox.Items.IndexOf(PageEditListBox.SelectedItems[i]);
  1414. pdfViewer.Document.RotatePage(index, (int)angleStep / 90);
  1415. pdfViewer.Document.ReleasePages(index);
  1416. pdfViewer.ClearSelectPDFEdit(true);
  1417. pdfViewer.UndoManager.ClearHistory();
  1418. pdfViewer.UndoManager.CanSave = true;
  1419. if (visiblePageIndexes.Contains(index))
  1420. visiblePageIndexes.Remove(index);
  1421. }
  1422. pdfViewer.ReloadDocument();
  1423. ItemsInViewHitTest();
  1424. }
  1425. public static string CreateFilePath(string path)
  1426. {
  1427. int i = 1;
  1428. string oldDestName = path;
  1429. do
  1430. {
  1431. if (File.Exists(path))
  1432. {
  1433. int lastDot = oldDestName.LastIndexOf('.');
  1434. string fileExtension = string.Empty;
  1435. string fileName = oldDestName;
  1436. if (lastDot > 0)
  1437. {
  1438. fileExtension = fileName.Substring(lastDot);
  1439. fileName = fileName.Substring(0, lastDot);
  1440. }
  1441. path = fileName + string.Format(@"({0})", i) + fileExtension;
  1442. }
  1443. ++i;
  1444. } while (File.Exists(path));
  1445. return path;
  1446. }
  1447. public void DoExtract(EventArgs e)
  1448. {
  1449. var data = e as ExtractEventClass;
  1450. int pagecount = pdfViewer.Document.PageCount;
  1451. string pageName = "";
  1452. List<int> pagenums = new List<int>();
  1453. pagenums.Clear();
  1454. switch (data.PageMode)
  1455. {
  1456. case 1:
  1457. for (int i = 0; i < pagecount; i++)
  1458. {
  1459. pagenums.Add(i + 1);
  1460. }
  1461. pageName = "1-" + pagecount;
  1462. break;
  1463. case 2:
  1464. int count = (pagecount + 1) / 2;
  1465. for (int i = 0; i < count; i++)
  1466. {
  1467. pagenums.Add(i * 2 + 1);
  1468. }
  1469. pageName = "OddPages";
  1470. break;
  1471. case 3:
  1472. if (pagecount == 1)
  1473. return;
  1474. count = pagecount / 2;
  1475. for (int i = 0; i < count; i++)
  1476. {
  1477. pagenums.Add(i * 2 + 2);
  1478. }
  1479. pageName = "EvenPages";
  1480. break;
  1481. case 4:
  1482. pagenums = data.PageParm;
  1483. pageName = data.PageName;
  1484. break;
  1485. default:
  1486. break;
  1487. }
  1488. System.Windows.Forms.FolderBrowserDialog dialog = new System.Windows.Forms.FolderBrowserDialog();
  1489. if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
  1490. {
  1491. if (string.IsNullOrEmpty(dialog.SelectedPath))
  1492. {
  1493. return;
  1494. }
  1495. }
  1496. else
  1497. return;
  1498. string selectedfile = "";
  1499. if (data.ExtractToSingleFile)
  1500. {
  1501. for (int i = 0; i < pagenums.Count; i++)
  1502. {
  1503. string filename = pdfViewer.Document.FileName + " " + (pagenums[i]) + ".pdf";
  1504. string path = System.IO.Path.Combine(dialog.SelectedPath, filename);
  1505. path = CreateFilePath(path);
  1506. selectedfile = path;
  1507. CPDFDocument savedoc = CPDFDocument.CreateDocument();
  1508. bool result = savedoc.ImportPages(pdfViewer.Document, (pagenums[i]).ToString());
  1509. if (!result)
  1510. {
  1511. savedoc.Release();
  1512. continue;
  1513. }
  1514. result = savedoc.WriteToFilePath(path);
  1515. if (!result)
  1516. {
  1517. savedoc.Release();
  1518. continue;
  1519. }
  1520. savedoc.Release();
  1521. }
  1522. }
  1523. else
  1524. {
  1525. string filename = pdfViewer.Document.FileName + " " + pageName + ".pdf";
  1526. string path = System.IO.Path.Combine(dialog.SelectedPath, filename);
  1527. path = CreateFilePath(path);
  1528. selectedfile = path;
  1529. CPDFDocument savedoc = CPDFDocument.CreateDocument();
  1530. string range = (data.PageMode == 1 || data.PageMode == 4) ? pageName : String.Join(",", pagenums);
  1531. bool result = savedoc.ImportPages(pdfViewer.Document, range);
  1532. if (!result)
  1533. {
  1534. return;
  1535. }
  1536. result = savedoc.WriteToFilePath(path);
  1537. if (!result)
  1538. {
  1539. }
  1540. savedoc.Release();
  1541. }
  1542. if (data.DeleteAfterExtract)
  1543. {
  1544. List<ListBoxItem> items = new List<ListBoxItem>();
  1545. for (int i = 0; i < pagenums.Count; i++)
  1546. {
  1547. ListBoxItem item = PageEditListBox.Items[pagenums[i]-1] as ListBoxItem;
  1548. items.Add(item);
  1549. }
  1550. DoDelete(items, false);
  1551. pdfViewer.UndoManager.ClearHistory();
  1552. pdfViewer.UndoManager.CanSave = true;
  1553. ItemsInViewHitTest();
  1554. }
  1555. Process.Start(@"explorer.exe", "/select,\"" + selectedfile + "\"");
  1556. }
  1557. private void DoPaste()
  1558. {
  1559. if (pdfViewer == null) return;
  1560. if (ViewportHelper.CopyDoc == null)
  1561. {
  1562. return;
  1563. }
  1564. int insertIndex = 0;
  1565. for (int k = 0; k < PageEditListBox.SelectedItems.Count; k++)
  1566. {
  1567. if (insertIndex < PageEditListBox.Items.IndexOf(PageEditListBox.SelectedItems[k] as ListBoxItem))
  1568. insertIndex = PageEditListBox.Items.IndexOf(PageEditListBox.SelectedItems[k] as ListBoxItem);
  1569. }
  1570. insertIndex++;
  1571. int pagecount = ViewportHelper.CopyDoc.PageCount;
  1572. bool result = pdfViewer.Document.ImportPagesAtIndex(ViewportHelper.CopyDoc, "1-" + pagecount, insertIndex);
  1573. if (!result)
  1574. {
  1575. return;
  1576. }
  1577. pdfViewer.ReloadDocument();
  1578. AddBlankPages(pagecount, insertIndex);
  1579. ItemsInViewHitTest();
  1580. pdfViewer.UndoManager.ClearHistory();
  1581. pdfViewer.UndoManager.CanSave = true;
  1582. RefreshBookMarkList();
  1583. List<ListBoxItem> pageList = new List<ListBoxItem>();
  1584. PageEditListBox.SelectedItems.Clear();
  1585. for (int i = 0; i < pagecount; i++)
  1586. {
  1587. pageList.Add(PageEditListBox.Items[insertIndex + i] as ListBoxItem);
  1588. PageEditListBox.SelectedItems.Add(PageEditListBox.Items[insertIndex + i] as ListBoxItem);
  1589. }
  1590. UpdateAllPageNum();
  1591. }
  1592. private void DoCopy()
  1593. {
  1594. if (pdfViewer == null) return;
  1595. if (PageEditListBox.SelectedItems.Count < 1)
  1596. {
  1597. ShowAlertWithTimeout(AlertType.EmptyPageAlert);
  1598. return;
  1599. }
  1600. ViewportHelper.CopyDoc = null;
  1601. ViewportHelper.CopyDoc = CPDFDocument.CreateDocument();
  1602. string pageParam = GetPageParam();
  1603. bool result = ViewportHelper.CopyDoc.ImportPages(pdfViewer.Document, pageParam);
  1604. if (!result)
  1605. {
  1606. return;
  1607. }
  1608. }
  1609. private void DoExchange(List<ListBoxItem> pageLists)
  1610. {
  1611. if (pageLists.Count <= 1)
  1612. {
  1613. return;
  1614. }
  1615. List<int> pages = new List<int>();
  1616. for (int i = 0; i < pageLists.Count; i++)
  1617. {
  1618. int pageIndex = PageEditListBox.Items.IndexOf(pageLists[i] as ListBoxItem);
  1619. pages.Add(pageIndex);
  1620. }
  1621. pages.Sort();
  1622. for (int i = 0; i < pages.Count; i++)
  1623. {
  1624. int preindex = pages[i];
  1625. int laterIndex = pages[pages.Count - i - 1];
  1626. if (laterIndex <= preindex)
  1627. return;
  1628. var sourceitem = PageEditListBox.Items[preindex] as ListBoxItem;
  1629. var targetitem = PageEditListBox.Items[laterIndex] as ListBoxItem;
  1630. bindPageList.Remove(sourceitem);
  1631. bindPageList.Remove(targetitem);
  1632. bindPageList.Insert(preindex, targetitem);
  1633. bindPageList.Insert(laterIndex, sourceitem);
  1634. pdfViewer.Document.ExchangePage(preindex, laterIndex);
  1635. pdfViewer.UndoManager.ClearHistory();
  1636. pdfViewer.UndoManager.CanSave = true;
  1637. PageEditListBox.SelectedItems.Add(targetitem);
  1638. PageEditListBox.SelectedItems.Add(sourceitem);
  1639. }
  1640. }
  1641. private void DoDelete(List<ListBoxItem> pageLists, bool tip)
  1642. {
  1643. if (pageLists.Count == 0)
  1644. {
  1645. ShowAlertWithTimeout(AlertType.EmptyPageAlert);
  1646. return;
  1647. }
  1648. if (pageLists.Count == PageEditListBox.Items.Count)
  1649. {
  1650. ShowAlertWithTimeout(AlertType.AllPageAlert);
  1651. return;
  1652. }
  1653. Winform.DialogResult result = Winform.DialogResult.OK;
  1654. if (tip)
  1655. {
  1656. result = Winform.MessageBox.Show(string.Format("Do you want to delete page {0}", GetPageParam()), "Delete", Winform.MessageBoxButtons.OKCancel, Winform.MessageBoxIcon.Warning);
  1657. }
  1658. if (result == Winform.DialogResult.OK || !tip)
  1659. {
  1660. List<int> pages = new List<int>();
  1661. for (int i = 0; i < pageLists.Count; i++)
  1662. {
  1663. var index = PageEditListBox.Items.IndexOf(pageLists[i]);
  1664. pages.Add(index);
  1665. }
  1666. pages.Sort();
  1667. if (pages.Count == 0) return;
  1668. for (int i = pages.Count - 1; i >= 0; i--)
  1669. {
  1670. bindPageList.RemoveAt(pages[i]);
  1671. }
  1672. var r = pdfViewer.Document.RemovePages(pages.ToArray());
  1673. if (!r)
  1674. {
  1675. return;
  1676. }
  1677. pdfViewer.UndoManager.ClearHistory();
  1678. pdfViewer.UndoManager.CanSave = true;
  1679. UpdateAllPageNum();
  1680. pdfViewer.ReloadDocument();
  1681. }
  1682. }
  1683. private List<ListBoxItem> GetListFromSelectedItems()
  1684. {
  1685. List<ListBoxItem> itemlists = new List<ListBoxItem>();
  1686. for (int i = 0; i < PageEditListBox.SelectedItems.Count; i++)
  1687. {
  1688. itemlists.Add(PageEditListBox.SelectedItems[i] as ListBoxItem);
  1689. }
  1690. return itemlists;
  1691. }
  1692. public static bool GetPagesInRange(ref List<int> pageList, string pageRange, int count, char[] enumerationSeparator, char[] rangeSeparator, bool inittag = false)
  1693. {
  1694. string[] rangeSplit = pageRange.Split(enumerationSeparator);
  1695. pageList.Clear();
  1696. foreach (string range in rangeSplit)
  1697. {
  1698. int starttag = 1;
  1699. if (inittag)
  1700. {
  1701. starttag = 0;
  1702. }
  1703. if (range.Contains("-"))
  1704. {
  1705. try
  1706. {
  1707. string[] limits = range.Split(rangeSeparator);
  1708. if (limits.Length >= 2 && !string.IsNullOrWhiteSpace(limits[0]) && !string.IsNullOrWhiteSpace(limits[1]))
  1709. {
  1710. int start = int.Parse(limits[0]);
  1711. int end = int.Parse(limits[1]);
  1712. if ((start < starttag) || (end > count) || (start > end))
  1713. {
  1714. return false;
  1715. }
  1716. for (int i = start; i <= end; ++i)
  1717. {
  1718. if (pageList.Contains(i))
  1719. {
  1720. return false;
  1721. }
  1722. pageList.Add(i - 1);
  1723. }
  1724. continue;
  1725. }
  1726. }
  1727. catch (Exception ex)
  1728. {
  1729. return false;
  1730. }
  1731. }
  1732. int pageNr;
  1733. try
  1734. {
  1735. pageNr = int.Parse(range);
  1736. }
  1737. catch (Exception)
  1738. {
  1739. return false;
  1740. }
  1741. if (pageNr < starttag || pageNr > count)
  1742. {
  1743. return false;
  1744. }
  1745. if (pageList.Contains(pageNr))
  1746. {
  1747. return false;
  1748. }
  1749. pageList.Add(pageNr - 1);
  1750. }
  1751. return true;
  1752. }
  1753. private void DoAddFromOtherPdf(string filepath, string pagerange, int insertindex, string password)
  1754. {
  1755. CPDFDocument doc = CPDFDocument.InitWithFilePath(filepath);
  1756. if(doc.IsLocked && password != string.Empty)
  1757. {
  1758. if(!doc.UnlockWithPassword(password))
  1759. {
  1760. return;
  1761. }
  1762. }
  1763. int pagecount = 0;
  1764. string insertRange = "";
  1765. if (pagerange == "AllPages")
  1766. {
  1767. pagecount = doc.PageCount;
  1768. insertRange = "1-" + pagecount;
  1769. }
  1770. else if (pagerange == "OddPages")
  1771. {
  1772. pagecount = (doc.PageCount + 1) / 2;
  1773. int[] page = new int[(doc.PageCount + 1) / 2];
  1774. for (int i = 0; i < page.Length; i++)
  1775. {
  1776. page[i] = i * 2 + 1;
  1777. }
  1778. insertRange = string.Join(",", page);
  1779. }
  1780. else if (pagerange == "EvenPages")
  1781. {
  1782. if (doc.PageCount == 1)
  1783. {
  1784. insertRange = "1";
  1785. pagecount = 1;
  1786. }
  1787. else
  1788. {
  1789. pagecount = doc.PageCount / 2;
  1790. int[] page = new int[doc.PageCount / 2];
  1791. for (int i = 0; i < page.Length; i++)
  1792. {
  1793. page[i] = i * 2 + 2;
  1794. }
  1795. insertRange = string.Join(",", page);
  1796. }
  1797. }
  1798. else
  1799. {
  1800. List<int> page = new List<int>();
  1801. GetPagesInRange(ref page, pagerange, doc.PageCount, new char[] { ',' }, new char[] { '-' });
  1802. insertRange = pagerange;
  1803. pagecount = page.Count;
  1804. }
  1805. var result = pdfViewer.Document.ImportPagesAtIndex(doc, insertRange, insertindex);
  1806. if (!result)
  1807. {
  1808. return;
  1809. }
  1810. doc.Release();
  1811. RefreshThumbnail();
  1812. PageEditListBox.SelectedItems.Clear();
  1813. for (int i = insertindex; i < insertindex + pagecount; i++)
  1814. {
  1815. PageEditListBox.SelectedItems.Add(PageEditListBox.Items[i] as ListBoxItem);
  1816. }
  1817. }
  1818. private string GetPageParam()
  1819. {
  1820. string pageParam = "";
  1821. List<int> pagesList = new List<int>();
  1822. for (int i = 0; i < PageEditListBox.SelectedItems.Count; i++)
  1823. {
  1824. var item = PageEditListBox.SelectedItems[i] as ListBoxItem;
  1825. var page = GetPageNumTextBlock(item);
  1826. if (page != null)
  1827. {
  1828. pagesList.Add(int.Parse(page.Text));
  1829. }
  1830. }
  1831. if (pagesList.Count != 0)
  1832. {
  1833. pagesList.Sort();
  1834. for (int i = 0; i < pagesList.Count; i++)
  1835. {
  1836. if (i == 0)
  1837. {
  1838. pageParam += pagesList[0].ToString();
  1839. }
  1840. else
  1841. {
  1842. if (pagesList[i] == pagesList[i - 1] + 1)
  1843. {
  1844. if (i >= 2)
  1845. {
  1846. if (pagesList[i - 1] != pagesList[i - 2] + 1)
  1847. pageParam += "-";
  1848. }
  1849. else
  1850. pageParam += "-";
  1851. if (i == pagesList.Count - 1)
  1852. {
  1853. pageParam += pagesList[i].ToString();
  1854. }
  1855. }
  1856. else
  1857. {
  1858. if (i >= 2)
  1859. {
  1860. if (pagesList[i - 1] == pagesList[i - 2] + 1)
  1861. pageParam += pagesList[i - 1].ToString();
  1862. }
  1863. pageParam += "," + pagesList[i].ToString();
  1864. }
  1865. }
  1866. }
  1867. }
  1868. return pageParam;
  1869. }
  1870. public static BitmapSource ToBitmapSource(string path)
  1871. {
  1872. System.Drawing.Icon ico = System.Drawing.Icon.ExtractAssociatedIcon(path);
  1873. System.Drawing.Bitmap bitmap = ico.ToBitmap();
  1874. BitmapSource returnSource;
  1875. try
  1876. {
  1877. returnSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(bitmap.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
  1878. }
  1879. catch
  1880. {
  1881. returnSource = null;
  1882. }
  1883. return returnSource;
  1884. }
  1885. private Tuple<int, int, int> GetRoughViewportRange(ListBox view, Size itemSize, Thickness itemMargin)
  1886. {
  1887. var scrollViewer = GetScrollHost(view);
  1888. if (pdfViewer == null || pdfViewer.Document == null || scrollViewer == null || scrollViewer.ActualHeight == 0 || scrollViewer.ActualWidth == 0)//视图展开
  1889. return new Tuple<int, int, int>(0, 0, 0);
  1890. try
  1891. {
  1892. var currentHeight = scrollViewer.ActualHeight - view.Padding.Top;
  1893. var currentWidth = scrollViewer.ActualWidth;
  1894. var columnCount = (int)(currentWidth / (itemSize.Width + itemMargin.Left));
  1895. var rowCount = (int)Math.Ceiling(currentHeight / (itemSize.Height + itemMargin.Bottom));
  1896. var preItemCount = (int)((scrollViewer.VerticalOffset / scrollViewer.ExtentHeight) * ((pdfViewer.Document.PageCount + columnCount - 1) / columnCount));//滑动百分比*行数 = 大概的垂直位置
  1897. preItemCount = preItemCount * columnCount;
  1898. var preEnd = (int)(((scrollViewer.VerticalOffset + scrollViewer.ActualHeight) / scrollViewer.ExtentHeight) * ((pdfViewer.Document.PageCount + columnCount - 1) / columnCount));
  1899. preEnd = preEnd * columnCount + columnCount - 1;
  1900. var middle = (int)Math.Ceiling(preItemCount + preEnd / 2d);
  1901. return new Tuple<int, int, int>(
  1902. Math.Max(preItemCount, 0),
  1903. Math.Min(view.Items.Count, preEnd),
  1904. middle);
  1905. }
  1906. catch (Exception ex)
  1907. {
  1908. }
  1909. return new Tuple<int, int, int>(0, 0, 0);
  1910. }
  1911. private void ShowAlertWithTimeout(AlertType alertType)
  1912. {
  1913. AlertBorder.Visibility = Visibility.Visible;
  1914. AlertBorder.Opacity = 1.0;
  1915. if (alertType == AlertType.EmptyPageAlert)
  1916. {
  1917. AlertTextBlock.Text = "Please select at least one page.";
  1918. }
  1919. else if (alertType == AlertType.SinglePageALert)
  1920. {
  1921. AlertTextBlock.Text = "Please select above two pages.";
  1922. }
  1923. else if (alertType == AlertType.AllPageAlert)
  1924. {
  1925. AlertTextBlock.Text = "Please don't select all pages";
  1926. }
  1927. DoubleAnimation animation = new DoubleAnimation();
  1928. animation.From = 1.0;
  1929. animation.To = 0.0;
  1930. animation.Duration = TimeSpan.FromSeconds(3);
  1931. AlertBorder.BeginAnimation(OpacityProperty, animation);
  1932. }
  1933. #endregion
  1934. private void UserControl_MouseEnter(object sender, MouseEventArgs e)
  1935. {
  1936. MidLane.Visibility = Visibility.Collapsed;
  1937. }
  1938. private void UserControl_SizeChanged(object sender, SizeChangedEventArgs e)
  1939. {
  1940. ItemsInViewHitTest();
  1941. }
  1942. }
  1943. public class InsertEventClass : EventArgs
  1944. {
  1945. public InsertType InsertType = InsertType.BlankPages;
  1946. public string FilePath = string.Empty;
  1947. public double PageWidth = 210 * 2.54;
  1948. public double PageHeight = 297 * 2.54;
  1949. public string PageRange = "0";
  1950. public int InsertIndex = 0;
  1951. public string Password = string.Empty;
  1952. }
  1953. public enum InsertType
  1954. {
  1955. BlankPages,
  1956. CustomBlankPages,
  1957. FromOtherPDF
  1958. }
  1959. /// <summary>
  1960. /// The parameter class used for extraction
  1961. /// </summary>
  1962. public class ExtractEventClass : EventArgs
  1963. {
  1964. /// <summary>
  1965. /// 1- All pages 2 - Odd pages 3 - Even pages 4 - Custom ranges
  1966. /// </summary>
  1967. public int PageMode;
  1968. /// <summary>
  1969. /// PageMode = 1,2,3 PageParm = null;
  1970. /// </summary>
  1971. public List<int> PageParm;
  1972. /// <summary>
  1973. /// In custom mode, the text content is passed over
  1974. /// </summary>
  1975. public string PageName = "";
  1976. /// <summary>
  1977. /// Whether to split into a single file
  1978. /// </summary>
  1979. public bool ExtractToSingleFile;
  1980. /// <summary>
  1981. /// Delete the page after extraction
  1982. /// </summary>
  1983. public bool DeleteAfterExtract;
  1984. }
  1985. public enum AlertType
  1986. {
  1987. EmptyPageAlert,
  1988. SinglePageALert,
  1989. AllPageAlert,
  1990. }
  1991. }