CPDFPageEditControl.xaml.cs 85 KB

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