CPDFPageEditControl.xaml.cs 81 KB

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