CPDFPageEditControl.xaml.cs 80 KB

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