CPDFPageEditControl.xaml.cs 81 KB

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