CPDFPageEditControl.xaml.cs 85 KB

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