CPDFPageEditControl.xaml.cs 81 KB

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