CPDFPageEditControl.xaml.cs 85 KB

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