CPDFPageEditControl.xaml.cs 85 KB

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