CPDFPageEditControl.xaml.cs 80 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200
  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(string.Format("Do you want to delete page {0}", GetPageParam()), "Delete", Winform.MessageBoxButtons.OKCancel, Winform.MessageBoxIcon.Warning);
  1652. }
  1653. if (result == Winform.DialogResult.OK || !tip)
  1654. {
  1655. List<int> pages = new List<int>();
  1656. for (int i = 0; i < pageLists.Count; i++)
  1657. {
  1658. var index = PageEditListBox.Items.IndexOf(pageLists[i]);
  1659. pages.Add(index);
  1660. }
  1661. pages.Sort();
  1662. if (pages.Count == 0) return;
  1663. for (int i = pages.Count - 1; i >= 0; i--)
  1664. {
  1665. bindPageList.RemoveAt(pages[i]);
  1666. }
  1667. var r = pdfViewer.Document.RemovePages(pages.ToArray());
  1668. if (!r)
  1669. {
  1670. return;
  1671. }
  1672. pdfViewer.UndoManager.ClearHistory();
  1673. pdfViewer.UndoManager.CanSave = true;
  1674. UpdateAllPageNum();
  1675. pdfViewer.ReloadDocument();
  1676. }
  1677. }
  1678. private List<ListBoxItem> GetListFromSelectedItems()
  1679. {
  1680. List<ListBoxItem> itemlists = new List<ListBoxItem>();
  1681. for (int i = 0; i < PageEditListBox.SelectedItems.Count; i++)
  1682. {
  1683. itemlists.Add(PageEditListBox.SelectedItems[i] as ListBoxItem);
  1684. }
  1685. return itemlists;
  1686. }
  1687. public static bool GetPagesInRange(ref List<int> pageList, string pageRange, int count, char[] enumerationSeparator, char[] rangeSeparator, bool inittag = false)
  1688. {
  1689. string[] rangeSplit = pageRange.Split(enumerationSeparator);
  1690. pageList.Clear();
  1691. foreach (string range in rangeSplit)
  1692. {
  1693. int starttag = 1;
  1694. if (inittag)
  1695. {
  1696. starttag = 0;
  1697. }
  1698. if (range.Contains("-"))
  1699. {
  1700. try
  1701. {
  1702. string[] limits = range.Split(rangeSeparator);
  1703. if (limits.Length >= 2 && !string.IsNullOrWhiteSpace(limits[0]) && !string.IsNullOrWhiteSpace(limits[1]))
  1704. {
  1705. int start = int.Parse(limits[0]);
  1706. int end = int.Parse(limits[1]);
  1707. if ((start < starttag) || (end > count) || (start > end))
  1708. {
  1709. return false;
  1710. }
  1711. for (int i = start; i <= end; ++i)
  1712. {
  1713. if (pageList.Contains(i))
  1714. {
  1715. return false;
  1716. }
  1717. pageList.Add(i - 1);
  1718. }
  1719. continue;
  1720. }
  1721. }
  1722. catch (Exception ex)
  1723. {
  1724. return false;
  1725. }
  1726. }
  1727. int pageNr;
  1728. try
  1729. {
  1730. pageNr = int.Parse(range);
  1731. }
  1732. catch (Exception)
  1733. {
  1734. return false;
  1735. }
  1736. if (pageNr < starttag || pageNr > count)
  1737. {
  1738. return false;
  1739. }
  1740. if (pageList.Contains(pageNr))
  1741. {
  1742. return false;
  1743. }
  1744. pageList.Add(pageNr - 1);
  1745. }
  1746. return true;
  1747. }
  1748. private void DoAddFromOtherPdf(string filepath, string pagerange, int insertindex, string password)
  1749. {
  1750. CPDFDocument doc = CPDFDocument.InitWithFilePath(filepath);
  1751. if(doc.IsLocked && password != string.Empty)
  1752. {
  1753. if(!doc.UnlockWithPassword(password))
  1754. {
  1755. return;
  1756. }
  1757. }
  1758. int pagecount = 0;
  1759. string insertRange = "";
  1760. if (pagerange == "AllPages")
  1761. {
  1762. pagecount = doc.PageCount;
  1763. insertRange = "1-" + pagecount;
  1764. }
  1765. else if (pagerange == "OddPages")
  1766. {
  1767. pagecount = (doc.PageCount + 1) / 2;
  1768. int[] page = new int[(doc.PageCount + 1) / 2];
  1769. for (int i = 0; i < page.Length; i++)
  1770. {
  1771. page[i] = i * 2 + 1;
  1772. }
  1773. insertRange = string.Join(",", page);
  1774. }
  1775. else if (pagerange == "EvenPages")
  1776. {
  1777. if (doc.PageCount == 1)
  1778. {
  1779. insertRange = "1";
  1780. pagecount = 1;
  1781. }
  1782. else
  1783. {
  1784. pagecount = doc.PageCount / 2;
  1785. int[] page = new int[doc.PageCount / 2];
  1786. for (int i = 0; i < page.Length; i++)
  1787. {
  1788. page[i] = i * 2 + 2;
  1789. }
  1790. insertRange = string.Join(",", page);
  1791. }
  1792. }
  1793. else
  1794. {
  1795. List<int> page = new List<int>();
  1796. GetPagesInRange(ref page, pagerange, doc.PageCount, new char[] { ',' }, new char[] { '-' });
  1797. insertRange = pagerange;
  1798. pagecount = page.Count;
  1799. }
  1800. var result = pdfViewer.Document.ImportPagesAtIndex(doc, insertRange, insertindex);
  1801. if (!result)
  1802. {
  1803. return;
  1804. }
  1805. doc.Release();
  1806. RefreshThumbnail();
  1807. PageEditListBox.SelectedItems.Clear();
  1808. for (int i = insertindex; i < insertindex + pagecount; i++)
  1809. {
  1810. PageEditListBox.SelectedItems.Add(PageEditListBox.Items[i] as ListBoxItem);
  1811. }
  1812. }
  1813. private string GetPageParam()
  1814. {
  1815. string pageParam = "";
  1816. List<int> pagesList = new List<int>();
  1817. for (int i = 0; i < PageEditListBox.SelectedItems.Count; i++)
  1818. {
  1819. var item = PageEditListBox.SelectedItems[i] as ListBoxItem;
  1820. var page = GetPageNumTextBlock(item);
  1821. if (page != null)
  1822. {
  1823. pagesList.Add(int.Parse(page.Text));
  1824. }
  1825. }
  1826. if (pagesList.Count != 0)
  1827. {
  1828. pagesList.Sort();
  1829. for (int i = 0; i < pagesList.Count; i++)
  1830. {
  1831. if (i == 0)
  1832. {
  1833. pageParam += pagesList[0].ToString();
  1834. }
  1835. else
  1836. {
  1837. if (pagesList[i] == pagesList[i - 1] + 1)
  1838. {
  1839. if (i >= 2)
  1840. {
  1841. if (pagesList[i - 1] != pagesList[i - 2] + 1)
  1842. pageParam += "-";
  1843. }
  1844. else
  1845. pageParam += "-";
  1846. if (i == pagesList.Count - 1)
  1847. {
  1848. pageParam += pagesList[i].ToString();
  1849. }
  1850. }
  1851. else
  1852. {
  1853. if (i >= 2)
  1854. {
  1855. if (pagesList[i - 1] == pagesList[i - 2] + 1)
  1856. pageParam += pagesList[i - 1].ToString();
  1857. }
  1858. pageParam += "," + pagesList[i].ToString();
  1859. }
  1860. }
  1861. }
  1862. }
  1863. return pageParam;
  1864. }
  1865. public static BitmapSource ToBitmapSource(string path)
  1866. {
  1867. System.Drawing.Icon ico = System.Drawing.Icon.ExtractAssociatedIcon(path);
  1868. System.Drawing.Bitmap bitmap = ico.ToBitmap();
  1869. BitmapSource returnSource;
  1870. try
  1871. {
  1872. returnSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(bitmap.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
  1873. }
  1874. catch
  1875. {
  1876. returnSource = null;
  1877. }
  1878. return returnSource;
  1879. }
  1880. private Tuple<int, int, int> GetRoughViewportRange(ListBox view, Size itemSize, Thickness itemMargin)
  1881. {
  1882. var scrollViewer = GetScrollHost(view);
  1883. if (pdfViewer == null || pdfViewer.Document == null || scrollViewer == null || scrollViewer.ActualHeight == 0 || scrollViewer.ActualWidth == 0)//视图展开
  1884. return new Tuple<int, int, int>(0, 0, 0);
  1885. try
  1886. {
  1887. var currentHeight = scrollViewer.ActualHeight - view.Padding.Top;
  1888. var currentWidth = scrollViewer.ActualWidth;
  1889. var columnCount = (int)(currentWidth / (itemSize.Width + itemMargin.Left));
  1890. var rowCount = (int)Math.Ceiling(currentHeight / (itemSize.Height + itemMargin.Bottom));
  1891. var preItemCount = (int)((scrollViewer.VerticalOffset / scrollViewer.ExtentHeight) * ((pdfViewer.Document.PageCount + columnCount - 1) / columnCount));//滑动百分比*行数 = 大概的垂直位置
  1892. preItemCount = preItemCount * columnCount;
  1893. var preEnd = (int)(((scrollViewer.VerticalOffset + scrollViewer.ActualHeight) / scrollViewer.ExtentHeight) * ((pdfViewer.Document.PageCount + columnCount - 1) / columnCount));
  1894. preEnd = preEnd * columnCount + columnCount - 1;
  1895. var middle = (int)Math.Ceiling(preItemCount + preEnd / 2d);
  1896. return new Tuple<int, int, int>(
  1897. Math.Max(preItemCount, 0),
  1898. Math.Min(view.Items.Count, preEnd),
  1899. middle);
  1900. }
  1901. catch (Exception ex)
  1902. {
  1903. }
  1904. return new Tuple<int, int, int>(0, 0, 0);
  1905. }
  1906. private void ShowAlertWithTimeout(AlertType alertType)
  1907. {
  1908. AlertBorder.Visibility = Visibility.Visible;
  1909. AlertBorder.Opacity = 1.0;
  1910. if (alertType == AlertType.EmptyPageAlert)
  1911. {
  1912. AlertTextBlock.Text = LanguageHelper.DocEditorManager.GetString("Tip_NoPage");
  1913. }
  1914. else if (alertType == AlertType.SinglePageALert)
  1915. {
  1916. AlertTextBlock.Text = "Please select above two pages.";
  1917. }
  1918. else if (alertType == AlertType.AllPageAlert)
  1919. {
  1920. AlertTextBlock.Text = LanguageHelper.DocEditorManager.GetString("Tip_AllPage");
  1921. }
  1922. DoubleAnimation animation = new DoubleAnimation();
  1923. animation.From = 1.0;
  1924. animation.To = 0.0;
  1925. animation.Duration = TimeSpan.FromSeconds(3);
  1926. AlertBorder.BeginAnimation(OpacityProperty, animation);
  1927. }
  1928. #endregion
  1929. private void UserControl_MouseEnter(object sender, MouseEventArgs e)
  1930. {
  1931. MidLane.Visibility = Visibility.Collapsed;
  1932. }
  1933. private void UserControl_SizeChanged(object sender, SizeChangedEventArgs e)
  1934. {
  1935. ItemsInViewHitTest();
  1936. }
  1937. }
  1938. public class InsertEventClass : EventArgs
  1939. {
  1940. public InsertType InsertType = InsertType.BlankPages;
  1941. public string FilePath = string.Empty;
  1942. public double PageWidth = 210 * 2.54;
  1943. public double PageHeight = 297 * 2.54;
  1944. public string PageRange = "0";
  1945. public int InsertIndex = 0;
  1946. public string Password = string.Empty;
  1947. }
  1948. public enum InsertType
  1949. {
  1950. BlankPages,
  1951. CustomBlankPages,
  1952. FromOtherPDF
  1953. }
  1954. /// <summary>
  1955. /// The parameter class used for extraction
  1956. /// </summary>
  1957. public class ExtractEventClass : EventArgs
  1958. {
  1959. /// <summary>
  1960. /// 1- All pages 2 - Odd pages 3 - Even pages 4 - Custom ranges
  1961. /// </summary>
  1962. public int PageMode;
  1963. /// <summary>
  1964. /// PageMode = 1,2,3 PageParm = null;
  1965. /// </summary>
  1966. public List<int> PageParm;
  1967. /// <summary>
  1968. /// In custom mode, the text content is passed over
  1969. /// </summary>
  1970. public string PageName = "";
  1971. /// <summary>
  1972. /// Whether to split into a single file
  1973. /// </summary>
  1974. public bool ExtractToSingleFile;
  1975. /// <summary>
  1976. /// Delete the page after extraction
  1977. /// </summary>
  1978. public bool DeleteAfterExtract;
  1979. }
  1980. public enum AlertType
  1981. {
  1982. EmptyPageAlert,
  1983. SinglePageALert,
  1984. AllPageAlert,
  1985. }
  1986. }