CPDFPageEditControl.xaml.cs 84 KB

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