CPDFPageEditControl.xaml.cs 85 KB

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