CPDFPageEditControl.xaml.cs 84 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366
  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. double xPos, yPos;
  730. if (!isDragingEnter)
  731. {
  732. Image image = GetImageElement(tempItem);//获取item 图片
  733. Viewbox viewBox = (tempItem.Content as StackPanel).Children[0] as Viewbox;//获取item宽度
  734. ShadowPicture.Width = viewBox.ActualWidth;
  735. ShadowPicture.Height = viewBox.ActualHeight;
  736. ShadowPicture.Source = image.Source;
  737. xPos = e.GetPosition(PageEditListBox).X - item_x;
  738. yPos = e.GetPosition(PageEditListBox).Y - item_y;
  739. }
  740. else
  741. {
  742. var pic = ToBitmapSource(dragingEnterPath);
  743. ShadowPicture.Width = pic.Width;
  744. ShadowPicture.Height = pic.Height;
  745. ShadowPicture.Source = pic;
  746. xPos = e.GetPosition(PageEditListBox).X - pic.Width / 2;
  747. yPos = e.GetPosition(PageEditListBox).Y - pic.Height / 2;
  748. }
  749. ShadowPicture.Margin = new Thickness(xPos, yPos, 0, 0);
  750. var scroll = GetScrollHost(PageEditListBox);
  751. if (listBoxItem != null)
  752. {
  753. var p = VisualTreeHelper.GetOffset(listBoxItem);
  754. MidLane.Visibility = Visibility.Visible;
  755. var panel = GetWrapPanel(PageEditListBox);
  756. var item = (PageEditListBox.Items[0] as ListBoxItem).DesiredSize.Width;
  757. int count = (int)(panel.ViewportWidth / item);
  758. var gap = (panel.ViewportWidth - count * item) / (count + 1) * 1.0;
  759. MidLane.X2 = MidLane.X1 = p.X + gap / 2 + listBoxItem.DesiredSize.Width;
  760. if (pos.X < p.X + gap / 2 + listBoxItem.ActualWidth / 2)
  761. {
  762. MidLane.X2 = MidLane.X1 = p.X - gap / 2;
  763. InsertIndex = PageEditListBox.Items.IndexOf(listBoxItem);
  764. }
  765. else
  766. {
  767. InsertIndex = PageEditListBox.Items.IndexOf(listBoxItem) + 1;
  768. }
  769. MidLane.Y1 = p.Y;
  770. if (MidLane.Y1 < 0)
  771. MidLane.Y1 = 0;
  772. MidLane.Y2 = p.Y + listBoxItem.ActualHeight;
  773. if (MidLane.Y2 < 0)
  774. {
  775. MidLane.Y2 = 0;
  776. }
  777. }
  778. if (pos.Y <= 30 || pos.Y >= PageEditListBox.ActualHeight - 10)
  779. {
  780. MidLane.Visibility = Visibility.Collapsed;
  781. }
  782. if (pos.X <= 40 || pos.X >= scroll.ViewportWidth - 50)
  783. {
  784. MidLane.Visibility = Visibility.Collapsed;
  785. }
  786. speed = 0;
  787. if (pos.Y >= PageEditListBox.ActualHeight - 30)
  788. {
  789. speed = 30 - (int)(PageEditListBox.ActualHeight - pos.Y);
  790. }
  791. else if (pos.Y <= 30)
  792. {
  793. speed = (int)(pos.Y - 30);
  794. }
  795. var v = scroll.VerticalOffset;
  796. scroll.ScrollToVerticalOffset(v + speed);
  797. }
  798. catch (Exception ex)
  799. {
  800. }
  801. }
  802. private void ShadowPicture_Drop(object sender, DragEventArgs e)
  803. {
  804. this.PageEditListBox_Drop(sender, e);
  805. }
  806. private void ListBoxItem_DragLeave(object sender, DragEventArgs e)
  807. {
  808. isDraging = true;
  809. }
  810. public void Delete_Click(object sender, RoutedEventArgs e)
  811. {
  812. if (viewControl == null)
  813. {
  814. return;
  815. }
  816. var list = GetListFromSelectedItems();
  817. DoDelete(list, true);
  818. }
  819. public void Rotate_Click(object sender, RoutedEventArgs e)
  820. {
  821. var item = sender as MenuItem;
  822. double step = 90;
  823. if (item.Name == "LeftRotate")
  824. {
  825. step = -90;
  826. }
  827. else
  828. {
  829. step = 90;
  830. }
  831. DoRotate(step);
  832. PageEditListBox.Focus();
  833. }
  834. private void ListBoxItem_PreviewMouseDoubleClick(object sender, MouseButtonEventArgs e)
  835. {
  836. e.GetPosition(PageEditListBox);
  837. var pos = e.GetPosition(PageEditListBox);
  838. HitTestResult result = VisualTreeHelper.HitTest(PageEditListBox, pos);
  839. if (result == null)
  840. {
  841. return;
  842. }
  843. var listBoxItem = Utils.FindVisualParent<ListBoxItem>(result.VisualHit);
  844. if (listBoxItem != null)
  845. {
  846. CPDFViewer pdfViewer=GetPDFViewer();
  847. }
  848. ExitPageEdit?.Invoke(this, new EventArgs());
  849. }
  850. public void Copy_Click(object sender, RoutedEventArgs e)
  851. {
  852. DoCopy();
  853. DoPaste();
  854. ViewportHelper.CopyDoc = null;
  855. }
  856. private void PageEditListBox_SizeChanged(object sender, SizeChangedEventArgs e)
  857. {
  858. PageEditListBox.ScrollIntoView(PageEditListBox.SelectedItem);
  859. }
  860. private void PageEditor_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
  861. {
  862. if (viewControl == null)
  863. {
  864. return;
  865. }
  866. if (isFirstLoad)
  867. {
  868. isFirstLoad = false;
  869. return;
  870. }
  871. CPDFViewer pdfViewer= GetPDFViewer();
  872. if(pdfViewer!=null && pdfViewer.CurrentRenderFrame!=null)
  873. {
  874. int pageIndex=pdfViewer.CurrentRenderFrame.PageIndex;
  875. if ((bool)e.NewValue == true && viewControl != null && pageIndex >= 0)
  876. {
  877. RefreshThumbnail();
  878. }
  879. if (pageIndex >= PageEditListBox.Items.Count || PageEditListBox.Items.Count == 0)
  880. {
  881. return;
  882. }
  883. ListBoxItem item = PageEditListBox.Items[pageIndex == -1 ? 0 : pageIndex] as ListBoxItem;
  884. PageEditListBox.ScrollIntoView(PageEditListBox.SelectedItem);
  885. PageEditListBox.SelectedItem = item;
  886. }
  887. }
  888. private async void ListBoxItem_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
  889. {
  890. if (!Keyboard.IsKeyDown(Key.LeftCtrl) && !Keyboard.IsKeyDown(Key.LeftShift))
  891. {
  892. var item = sender as ListBoxItem;
  893. Image img = GetImageElement(item);
  894. int itemindex = PageEditListBox.Items.IndexOf(item);
  895. if (img.Source == null)
  896. {
  897. await GetThumbnail(itemindex, (int)img.Width, (int)img.Height);
  898. }
  899. CPDFViewer pdfViewer = GetPDFViewer();
  900. pdfViewer?.GoToPage(itemindex, new Point(0, 0));
  901. }
  902. }
  903. private void PageGrid_PreviewDragEnter(object sender, DragEventArgs e)
  904. {
  905. var file = (System.Array)e.Data.GetData(DataFormats.FileDrop);
  906. if (file == null || file.Length > 1)
  907. { return; }
  908. foreach (var f in file)
  909. {
  910. dragingEnterPath = f.ToString();
  911. if (dragingEnterPath != null)
  912. {
  913. isDragingEnter = true;
  914. }
  915. }
  916. }
  917. private void ContextMenu_Loaded(object sender, RoutedEventArgs e)
  918. {
  919. if (ViewportHelper.CopyDoc == null)
  920. {
  921. var s = sender as ContextMenu;
  922. foreach (var item in s.Items)
  923. {
  924. if ((item as MenuItem).Name == "Paste")
  925. {
  926. (item as MenuItem).IsEnabled = false;
  927. }
  928. }
  929. }
  930. else
  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 = true;
  938. }
  939. }
  940. }
  941. if (PageEditListBox.SelectedItems.Count < 2)
  942. {
  943. var s = sender as ContextMenu;
  944. foreach (var item in s.Items)
  945. {
  946. if ((item as MenuItem).Name == "Exchange")
  947. {
  948. (item as MenuItem).IsEnabled = false;
  949. }
  950. }
  951. }
  952. else
  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 = true;
  960. }
  961. }
  962. }
  963. }
  964. private void UserControl_KeyDown(object sender, KeyEventArgs e)
  965. {
  966. if ((Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control && e.Key == Key.A)
  967. {
  968. if (PageEditListBox.SelectedItems.Count == PageEditListBox.Items.Count)
  969. {
  970. PageEditListBox.UnselectAll();
  971. e.Handled = true;
  972. }
  973. }
  974. }
  975. #endregion
  976. #region Method
  977. public void LoadThumbnails(PDFViewControl viewer)
  978. {
  979. if (viewer == null)
  980. {
  981. return;
  982. }
  983. if (viewControl != null && viewer != viewControl)
  984. {
  985. viewControl = viewer;
  986. this.PopulateThumbnailList();
  987. OnThumbnailGenerated -= _pdfviewer_OnThumbnailGenerated;
  988. OnThumbnailGenerated += _pdfviewer_OnThumbnailGenerated;
  989. }
  990. viewControl = viewer;
  991. if (!isThumbInitialized)
  992. {
  993. this.PopulateThumbnailList();
  994. isThumbInitialized = true;
  995. OnThumbnailGenerated -= _pdfviewer_OnThumbnailGenerated;
  996. OnThumbnailGenerated += _pdfviewer_OnThumbnailGenerated;
  997. }
  998. CPDFViewer pdfviewer = GetPDFViewer();
  999. if(pdfviewer != null && pdfviewer.CurrentRenderFrame!=null)
  1000. {
  1001. int pageIndex = pdfviewer.CurrentRenderFrame.PageIndex;
  1002. if (pageIndex >= 0 && PageEditListBox.Items.Count > pageIndex)
  1003. {
  1004. PageEditListBox.ScrollIntoView(PageEditListBox.Items[pageIndex]);
  1005. (PageEditListBox.Items[pageIndex] as ListBoxItem).IsSelected = true;
  1006. PageEditListBox.SelectedIndex = pageIndex;
  1007. }
  1008. }
  1009. RefreshBookMarkList();
  1010. }
  1011. public void PopulateThumbnailList()
  1012. {
  1013. visiblePageIndexes.Clear();
  1014. bindPageList.Clear();
  1015. // GC.Collect();
  1016. CPDFDocument pdfDoc= GetPDFDocument();
  1017. if(pdfDoc == null || pdfDoc.IsValid()==false)
  1018. {
  1019. return;
  1020. }
  1021. int thumbnailWidth = thumbnailSize[zoomLevel];
  1022. for (int i = 0; i < pdfDoc.PageCount; i++)
  1023. {
  1024. Size pageSize = DataConversionForWPF.CSizeConversionForSize(pdfDoc.GetPageSize(i));
  1025. if (pageSize.Height == 0 || pageSize.Width == 0)
  1026. continue;
  1027. int imageWidth = pageSize.Width > pageSize.Height ? thumbnailWidth * 2 : (int)(pageSize.Width / pageSize.Height * thumbnailWidth * 2);
  1028. int imageHeight = pageSize.Height > pageSize.Width ? thumbnailWidth * 2 : (int)(pageSize.Height / pageSize.Width * thumbnailWidth * 2);
  1029. Image img = new Image()
  1030. {
  1031. //Margin = new Thickness(0, 0, 5, 0),
  1032. Width = imageWidth,
  1033. Height = imageHeight,
  1034. Stretch = Stretch.Uniform,
  1035. };
  1036. Grid grid = new Grid();
  1037. grid.Children.Add(img);
  1038. List<Point> points = new List<Point>()
  1039. {
  1040. new Point(16.75,1.25),
  1041. new Point(3.25,1.25 ),
  1042. new Point(3.25,19.4013878),
  1043. new Point(10,14.902),
  1044. new Point(16.75,19.4013878),
  1045. };
  1046. Polygon bookmark = new Polygon()
  1047. {
  1048. Points = new PointCollection(points),
  1049. Fill = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#FFBB00")),
  1050. Margin = new Thickness(0, 16, 16, 0),
  1051. VerticalAlignment = VerticalAlignment.Top,
  1052. HorizontalAlignment = HorizontalAlignment.Right,
  1053. Visibility = Visibility.Collapsed,
  1054. };
  1055. grid.Children.Add(bookmark);
  1056. Border border = new Border()
  1057. {
  1058. BorderThickness = new Thickness(2),
  1059. BorderBrush = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#A0A2AE")),
  1060. Child = grid,
  1061. };
  1062. Viewbox viewBox = new Viewbox()
  1063. {
  1064. Margin = new Thickness(0, 8, 0, 0),
  1065. Stretch = Stretch.Uniform,
  1066. Width = thumbnailWidth,
  1067. Height = thumbnailWidth,
  1068. Child = border,
  1069. };
  1070. TextBlock text = new TextBlock()
  1071. {
  1072. HorizontalAlignment = HorizontalAlignment.Center,
  1073. Text = (i + 1).ToString(),
  1074. Foreground = Brushes.Black,
  1075. Margin = new Thickness(0, 8, 0, 8),
  1076. };
  1077. StackPanel panel = new StackPanel();
  1078. panel.Children.Add(viewBox);
  1079. panel.Children.Add(text);
  1080. ListBoxItem item = new ListBoxItem();
  1081. item.Content = panel;
  1082. item.Tag = i;
  1083. item.Margin = new Thickness(6, 10, 6, 10);
  1084. item.HorizontalContentAlignment = HorizontalAlignment.Left;
  1085. item.VerticalContentAlignment = VerticalAlignment.Center;
  1086. bindPageList.Add(item);
  1087. }
  1088. PageEditListBox.ItemsSource = bindPageList;
  1089. }
  1090. public ListBoxItem GetNewItem(int ItemIndex)
  1091. {
  1092. int thumbnailWidth = thumbnailSize[zoomLevel];
  1093. CPDFDocument pdfDoc= GetPDFDocument();
  1094. if(pdfDoc == null)
  1095. {
  1096. return new ListBoxItem();
  1097. }
  1098. Size pageSize = DataConversionForWPF.CSizeConversionForSize(pdfDoc.GetPageSize(ItemIndex));
  1099. if (pageSize.Width == 0 || pageSize.Height == 0)
  1100. {
  1101. pageSize = new Size(228, 300);
  1102. }
  1103. int imageWidth = pageSize.Width > pageSize.Height ? thumbnailWidth * 2 : (int)(pageSize.Width / pageSize.Height * thumbnailWidth * 2);
  1104. int imageHeight = pageSize.Height > pageSize.Width ? thumbnailWidth * 2 : (int)(pageSize.Height / pageSize.Width * thumbnailWidth * 2);
  1105. Image img = new Image()
  1106. {
  1107. Width = imageWidth,
  1108. Height = imageHeight,
  1109. Stretch = Stretch.Uniform,
  1110. };
  1111. Grid grid = new Grid();
  1112. grid.Children.Add(img);
  1113. List<Point> points = new List<Point>()
  1114. {
  1115. new Point(16.75,1.25),
  1116. new Point(3.25,1.25 ),
  1117. new Point(3.25,19.4013878),
  1118. new Point(10,14.902),
  1119. new Point(16.75,19.4013878),
  1120. };
  1121. Polygon bookmark = new Polygon()
  1122. {
  1123. Points = new PointCollection(points),
  1124. Fill = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#FFBB00")),
  1125. Margin = new Thickness(0, 8, 8, 0),
  1126. VerticalAlignment = VerticalAlignment.Top,
  1127. HorizontalAlignment = HorizontalAlignment.Right,
  1128. Visibility = Visibility.Collapsed,
  1129. };
  1130. grid.Children.Add(bookmark);
  1131. Border border = new Border()
  1132. {
  1133. BorderThickness = new Thickness(2),
  1134. BorderBrush = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#A0A2AE")),
  1135. Child = grid,
  1136. };
  1137. Viewbox viewBox = new Viewbox()
  1138. {
  1139. Margin = new Thickness(0, 8, 0, 0),
  1140. Stretch = Stretch.Uniform,
  1141. Width = thumbnailWidth,
  1142. Height = thumbnailWidth,
  1143. Child = border,
  1144. };
  1145. TextBlock text = new TextBlock()
  1146. {
  1147. HorizontalAlignment = HorizontalAlignment.Center,
  1148. Text = (ItemIndex + 1).ToString(),
  1149. Foreground = Brushes.Black,
  1150. Margin = new Thickness(0, 8, 0, 8),
  1151. };
  1152. StackPanel panel = new StackPanel();
  1153. panel.Children.Add(viewBox);
  1154. panel.Children.Add(text);
  1155. ListBoxItem item = new ListBoxItem();
  1156. item.Content = panel;
  1157. item.Tag = ItemIndex;
  1158. item.Margin = new Thickness(6, 10, 6, 10);
  1159. return item;
  1160. }
  1161. public void AddBlankPages(int pagecount, int insertindex)
  1162. {
  1163. for (int i = 0; i < pagecount; i++)
  1164. {
  1165. var item = GetNewItem(insertindex + i);
  1166. bindPageList.Insert(insertindex + i, item);
  1167. if (visiblePageIndexes.Contains(insertindex + i))
  1168. visiblePageIndexes.Remove(insertindex + i);
  1169. }
  1170. PageEditListBox.UpdateLayout();
  1171. }
  1172. private async void RenderPage(int pageindex)
  1173. {
  1174. var range = GetRoughViewportRange(PageEditListBox, (PageEditListBox.Items[0] as ListBoxItem).DesiredSize, new Thickness(6, 10, 6, 10));
  1175. if (pageindex < range.Item1 || pageindex > range.Item2)
  1176. return;
  1177. ListBoxItem item = PageEditListBox.Items[pageindex] as ListBoxItem;
  1178. Image img = GetImageElement(item);
  1179. await GetThumbnail(pageindex, (int)img.Width, (int)img.Height);
  1180. }
  1181. private async void ItemsInViewHitTest()
  1182. {
  1183. CPDFDocument pdfDoc= GetPDFDocument();
  1184. if (viewControl == null || pdfDoc == null)
  1185. {
  1186. return;
  1187. }
  1188. try
  1189. {
  1190. ScrollViewer sv = GetScrollHost(PageEditListBox);
  1191. if (sv == null || VisualTreeHelper.GetParent(this) == null)
  1192. {
  1193. return;
  1194. }
  1195. var range = GetRoughViewportRange(PageEditListBox, (PageEditListBox.Items[0] as ListBoxItem).DesiredSize, new Thickness(6, 10, 6, 10));
  1196. for (int i = 0; i < PageEditListBox.Items.Count; ++i)
  1197. {
  1198. ListBoxItem item = PageEditListBox.Items[i] as ListBoxItem;
  1199. Image img = GetImageElement(item);
  1200. if (i >= (range.Item1 - 1) && i <= range.Item2 || ViewportHelper.IsInViewport(sv, item))
  1201. {
  1202. if (img.Source == null && !visiblePageIndexes.Contains(i))
  1203. {
  1204. visiblePageIndexes.Add(i);
  1205. await Task.Delay(1);
  1206. await GetThumbnail(i, (int)img.Width, (int)img.Height);
  1207. //Debug.WriteLine("Page {0} is visible, asking for thumb", (i + 1));
  1208. }
  1209. }
  1210. else
  1211. {
  1212. if (visiblePageIndexes.Contains(i))
  1213. {
  1214. Image image = GetImageElement(PageEditListBox.Items[i] as ListBoxItem);
  1215. if (image.Source != null)
  1216. {
  1217. image.Source = null;
  1218. //Debug.WriteLine("Page {0} is out of range, removed thumb", (i + 1));
  1219. }
  1220. else
  1221. {
  1222. //Debug.WriteLine("Page {0} is out of range, but had no thumb", (i + 1));
  1223. }
  1224. visiblePageIndexes.Remove(i);
  1225. }
  1226. }
  1227. }
  1228. }
  1229. catch (Exception ex)
  1230. {
  1231. Debug.WriteLine(ex.ToString());
  1232. }
  1233. }
  1234. public void RefreshBookMarkList()
  1235. {
  1236. CPDFDocument pdfDoc = GetPDFDocument();
  1237. if (pdfDoc != null)
  1238. {
  1239. var booklist = pdfDoc.GetBookmarkList();
  1240. if (booklist == null) return;
  1241. List<int> marks = new List<int>();
  1242. for (int i = 0; i < booklist.Count; i++)
  1243. {
  1244. marks.Add(booklist[i].PageIndex);
  1245. }
  1246. for (int k = 0; k < PageEditListBox.Items.Count; k++)
  1247. {
  1248. Polygon polygon = GetBookMarkIco(PageEditListBox.Items[k] as ListBoxItem);
  1249. if (marks.Contains(k))
  1250. polygon.Visibility = Visibility.Visible;
  1251. else
  1252. polygon.Visibility = Visibility.Collapsed;
  1253. }
  1254. }
  1255. }
  1256. private void UpdateSelectedIndex()
  1257. {
  1258. CPDFViewer pdfView=GetPDFViewer();
  1259. if(pdfView != null && pdfView.CurrentRenderFrame!=null)
  1260. {
  1261. int pageIndex=pdfView.CurrentRenderFrame.PageIndex;
  1262. if (PageEditListBox.Items.Count == 0)
  1263. {
  1264. PageEditListBox.SelectedIndex = -1;
  1265. }
  1266. else if (PageEditListBox.Items.Count <= pageIndex)
  1267. {
  1268. PageEditListBox.SelectedIndex = 0;
  1269. }
  1270. else if (PageEditListBox.SelectedIndex != pageIndex)
  1271. {
  1272. PageEditListBox.SelectedIndex = pageIndex;
  1273. }
  1274. PageEditListBox.ScrollIntoView(PageEditListBox.Items[PageEditListBox.SelectedIndex]);
  1275. }
  1276. }
  1277. private Image GetImageElement(ListBoxItem item)
  1278. {
  1279. Viewbox viewBox = (item.Content as StackPanel).Children[0] as Viewbox;
  1280. Image img = ((viewBox.Child as Border).Child as Grid).Children[0] as Image;
  1281. return img;
  1282. }
  1283. private Polygon GetBookMarkIco(ListBoxItem item)
  1284. {
  1285. Viewbox viewBox = (item.Content as StackPanel).Children[0] as Viewbox;
  1286. Polygon ico = ((viewBox.Child as Border).Child as Grid).Children[1] as Polygon;
  1287. return ico;
  1288. }
  1289. private StackPanel GetPanel(ListBoxItem item)
  1290. {
  1291. StackPanel panel = item.Content as StackPanel;
  1292. return panel;
  1293. }
  1294. private TextBlock GetPageNumTextBlock(ListBoxItem item)
  1295. {
  1296. TextBlock text = (item.Content as StackPanel).Children[1] as TextBlock;
  1297. return text;
  1298. }
  1299. public VirtualizingWrapPanel GetWrapPanel(ListBox listBox)
  1300. {
  1301. Border border = VisualTreeHelper.GetChild(listBox, 0) as Border;
  1302. var panel = Utils.FindVisualChild<VirtualizingWrapPanel>(border);
  1303. return panel;
  1304. }
  1305. private ScrollViewer GetScrollHost(ListBox listBox)
  1306. {
  1307. if (VisualTreeHelper.GetChildrenCount(listBox) > 0)
  1308. {
  1309. int s = VisualTreeHelper.GetChildrenCount(listBox);
  1310. Border border = VisualTreeHelper.GetChild(listBox, 0) as Border;
  1311. if (border != null)
  1312. {
  1313. return VisualTreeHelper.GetChild(border, 0) as ScrollViewer;
  1314. }
  1315. }
  1316. return null;
  1317. }
  1318. private void DragToSort(int sourceindex, int targetindex)
  1319. {
  1320. if (targetindex == sourceindex || targetindex < 0)
  1321. {
  1322. MidLane.Visibility = Visibility.Collapsed;
  1323. return;
  1324. }
  1325. var source = PageEditListBox.Items[sourceindex];
  1326. bindPageList.RemoveAt(sourceindex);
  1327. MidLane.Visibility = Visibility.Collapsed;
  1328. bindPageList.Insert(targetindex, source as ListBoxItem);
  1329. PageEditListBox.SelectedItems.Add(source);
  1330. CPDFDocument pdfDoc=GetPDFDocument();
  1331. if(pdfDoc != null)
  1332. {
  1333. var result = pdfDoc.MovePage(sourceindex, targetindex);
  1334. if (!result)
  1335. {
  1336. MidLane.Visibility = Visibility.Collapsed;
  1337. return;
  1338. }
  1339. }
  1340. CPDFViewer pdfViewer=GetPDFViewer();
  1341. if(pdfViewer!=null)
  1342. {
  1343. pdfViewer.UpdateVirtualNodes();
  1344. pdfViewer.GoToPage(PageEditListBox.SelectedIndex, new Point(0, 0));
  1345. pdfViewer.UndoManager?.ClearHistory();
  1346. }
  1347. ItemsInViewHitTest();
  1348. this.PageMoved?.Invoke(this, new RoutedEventArgs());
  1349. UpdateSortedPageNum(sourceindex, targetindex);
  1350. }
  1351. private void UpdateSortedPageNum(int sourceIndex, int targetIndex)
  1352. {
  1353. int sum = sourceIndex + targetIndex;
  1354. targetIndex = targetIndex > sourceIndex ? targetIndex : sourceIndex;
  1355. sourceIndex = sum - targetIndex;
  1356. sourceIndex = sourceIndex <= 0 ? 0 : sourceIndex;
  1357. targetIndex = targetIndex + 1 > PageEditListBox.Items.Count ? PageEditListBox.Items.Count - 1 : targetIndex;
  1358. for (int i = sourceIndex; i <= targetIndex; i++)
  1359. {
  1360. var item = PageEditListBox.Items[i] as ListBoxItem;
  1361. item.Tag = i;
  1362. TextBlock pagenum = GetPageNumTextBlock(item);
  1363. pagenum.Text = (i + 1).ToString();
  1364. }
  1365. }
  1366. private void UpdateAllPageNum()
  1367. {
  1368. for (int i = 0; i < PageEditListBox.Items.Count; i++)
  1369. {
  1370. var pagenum = GetPageNumTextBlock(PageEditListBox.Items[i] as ListBoxItem);
  1371. pagenum.Text = (i + 1).ToString();
  1372. (PageEditListBox.Items[i] as ListBoxItem).Tag = i;
  1373. }
  1374. }
  1375. public void DoInsert(EventArgs e)
  1376. {
  1377. var data = e as InsertEventClass;
  1378. CPDFDocument pdfDoc = GetPDFDocument();
  1379. if (data.InsertType == InsertType.BlankPages)
  1380. {
  1381. if(pdfDoc!=null)
  1382. {
  1383. var size = pdfDoc.GetPageSize(data.InsertIndex - 1);
  1384. if (size.width == 0 || size.height == 0)
  1385. {
  1386. size = pdfDoc.GetPageSize(data.InsertIndex);
  1387. }
  1388. pdfDoc.InsertPage(data.InsertIndex, size.width, size.height, "");
  1389. }
  1390. RefreshThumbnail();
  1391. PageEditListBox.SelectedItems.Clear();
  1392. PageEditListBox.SelectedIndex = data.InsertIndex;
  1393. }
  1394. else if (data.InsertType == InsertType.CustomBlankPages)
  1395. {
  1396. pdfDoc.InsertPage(data.InsertIndex, (float)data.PageWidth, (float)data.PageHeight, "");
  1397. RefreshThumbnail();
  1398. PageEditListBox.SelectedItems.Clear();
  1399. PageEditListBox.SelectedIndex = data.InsertIndex;
  1400. }
  1401. else
  1402. {
  1403. DoAddFromOtherPdf(data.FilePath, data.PageRange, data.InsertIndex, data.Password);
  1404. }
  1405. UpdateAllPageNum();
  1406. CPDFViewer pdfViewer= GetPDFViewer();
  1407. if(pdfViewer!=null)
  1408. {
  1409. pdfViewer?.UndoManager?.ClearHistory();
  1410. pdfViewer.UpdateVirtualNodes();
  1411. }
  1412. PageEditListBox.ScrollIntoView(PageEditListBox.SelectedItem as ListBoxItem);
  1413. ItemsInViewHitTest();
  1414. }
  1415. public void DoReplace()
  1416. {
  1417. if (PageEditListBox.SelectedItems.Count < 1)
  1418. {
  1419. ShowAlertWithTimeout(AlertType.EmptyPageAlert);
  1420. return;
  1421. }
  1422. OpenFileDialog dialog = new OpenFileDialog();
  1423. dialog.Multiselect = false;
  1424. dialog.Filter = "(*.pdf)|*.pdf";
  1425. if ((bool)dialog.ShowDialog())
  1426. {
  1427. CPDFDocument doc = CPDFDocument.InitWithFilePath(dialog.FileName);
  1428. int pagecount = doc.PageCount;
  1429. int insertindex = PageEditListBox.Items.IndexOf(PageEditListBox.SelectedItem);
  1430. if (insertindex == -1)
  1431. insertindex = 0;
  1432. CPDFDocument pdfDoc = GetPDFDocument();
  1433. if(pdfDoc!=null)
  1434. {
  1435. pdfDoc.ImportPagesAtIndex(doc, "1-" + pagecount, insertindex);
  1436. }
  1437. doc.Release();
  1438. for (int i = 0; i < pagecount; i++)
  1439. {
  1440. var item = GetNewItem(insertindex + i);
  1441. bindPageList.Insert(insertindex + i, item);
  1442. if (visiblePageIndexes.Contains(insertindex + i))
  1443. visiblePageIndexes.Remove(insertindex + i);
  1444. }
  1445. CPDFViewer pdfViewer=GetPDFViewer();
  1446. if(pdfViewer!=null)
  1447. {
  1448. pdfViewer.UndoManager?.ClearHistory();
  1449. }
  1450. var list = GetListFromSelectedItems();
  1451. for (int i = insertindex; i < (insertindex + pagecount); i++)
  1452. {
  1453. if (i < PageEditListBox.Items.Count)
  1454. {
  1455. ListBoxItem t = PageEditListBox.Items[i] as ListBoxItem;
  1456. PageEditListBox.SelectedItems.Add(t);
  1457. }
  1458. }
  1459. DoDelete(list, false);
  1460. UpdateAllPageNum();
  1461. RefreshBookMarkList();
  1462. ItemsInViewHitTest();
  1463. }
  1464. }
  1465. private void DoRotate(double angleStep)
  1466. {
  1467. if (viewControl == null) return;
  1468. if (PageEditListBox.SelectedItems.Count < 1)
  1469. {
  1470. ShowAlertWithTimeout(AlertType.EmptyPageAlert);
  1471. return;
  1472. }
  1473. List<ListBoxItem> pages = new List<ListBoxItem>();
  1474. CPDFViewer pdfViewer = GetPDFViewer();
  1475. for (int i = 0; i < PageEditListBox.SelectedItems.Count; i++)
  1476. {
  1477. var image = GetImageElement(PageEditListBox.SelectedItems[i] as ListBoxItem);
  1478. pages.Add(PageEditListBox.SelectedItems[i] as ListBoxItem);
  1479. double angle = (double)image.LayoutTransform.GetValue(RotateTransform.AngleProperty);
  1480. angle += angleStep;
  1481. angle = angle % 360;
  1482. image.LayoutTransform = new RotateTransform(angle, image.ActualWidth / 2, image.ActualHeight / 2);
  1483. var index = PageEditListBox.Items.IndexOf(PageEditListBox.SelectedItems[i]);
  1484. CPDFDocument pdfDoc = GetPDFDocument();
  1485. if(pdfDoc!=null)
  1486. {
  1487. pdfDoc.RotatePage(index, (int)angleStep / 90);
  1488. pdfDoc.ReleasePages(index);
  1489. }
  1490. pdfViewer?.UndoManager?.ClearHistory();
  1491. if (visiblePageIndexes.Contains(index))
  1492. visiblePageIndexes.Remove(index);
  1493. }
  1494. pdfViewer?.UpdateVirtualNodes();
  1495. ItemsInViewHitTest();
  1496. }
  1497. public static string CreateFilePath(string path)
  1498. {
  1499. int i = 1;
  1500. string oldDestName = path;
  1501. do
  1502. {
  1503. if (File.Exists(path))
  1504. {
  1505. int lastDot = oldDestName.LastIndexOf('.');
  1506. string fileExtension = string.Empty;
  1507. string fileName = oldDestName;
  1508. if (lastDot > 0)
  1509. {
  1510. fileExtension = fileName.Substring(lastDot);
  1511. fileName = fileName.Substring(0, lastDot);
  1512. }
  1513. path = fileName + string.Format(@"({0})", i) + fileExtension;
  1514. }
  1515. ++i;
  1516. } while (File.Exists(path));
  1517. return path;
  1518. }
  1519. public void DoExtract(EventArgs e)
  1520. {
  1521. var data = e as ExtractEventClass;
  1522. CPDFDocument pdfDoc= GetPDFDocument();
  1523. if(pdfDoc== null)
  1524. {
  1525. return;
  1526. }
  1527. int pagecount = pdfDoc.PageCount;
  1528. string pageName = "";
  1529. List<int> pagenums = new List<int>();
  1530. pagenums.Clear();
  1531. switch (data.PageMode)
  1532. {
  1533. case 1:
  1534. for (int i = 0; i < pagecount; i++)
  1535. {
  1536. pagenums.Add(i + 1);
  1537. }
  1538. pageName = "1-" + pagecount;
  1539. break;
  1540. case 2:
  1541. int count = (pagecount + 1) / 2;
  1542. for (int i = 0; i < count; i++)
  1543. {
  1544. pagenums.Add(i * 2 + 1);
  1545. }
  1546. pageName = "OddPages";
  1547. break;
  1548. case 3:
  1549. if (pagecount == 1)
  1550. return;
  1551. count = pagecount / 2;
  1552. for (int i = 0; i < count; i++)
  1553. {
  1554. pagenums.Add(i * 2 + 2);
  1555. }
  1556. pageName = "EvenPages";
  1557. break;
  1558. case 4:
  1559. pagenums = data.PageParm;
  1560. pageName = data.PageName;
  1561. break;
  1562. default:
  1563. break;
  1564. }
  1565. Winform.FolderBrowserDialog dialog = new Winform.FolderBrowserDialog();
  1566. if (dialog.ShowDialog() == Winform.DialogResult.OK)
  1567. {
  1568. if (string.IsNullOrEmpty(dialog.SelectedPath))
  1569. {
  1570. return;
  1571. }
  1572. }
  1573. else
  1574. return;
  1575. string selectedfile = "";
  1576. if (data.ExtractToSingleFile)
  1577. {
  1578. for (int i = 0; i < pagenums.Count; i++)
  1579. {
  1580. string filename = pdfDoc.FileName + " " + (pagenums[i]) + ".pdf";
  1581. string path = System.IO.Path.Combine(dialog.SelectedPath, filename);
  1582. path = CreateFilePath(path);
  1583. selectedfile = path;
  1584. CPDFDocument savedoc = CPDFDocument.CreateDocument();
  1585. bool result = savedoc.ImportPages(pdfDoc, (pagenums[i]).ToString());
  1586. if (!result)
  1587. {
  1588. savedoc.Release();
  1589. continue;
  1590. }
  1591. result = savedoc.WriteToFilePath(path);
  1592. if (!result)
  1593. {
  1594. savedoc.Release();
  1595. continue;
  1596. }
  1597. savedoc.Release();
  1598. }
  1599. }
  1600. else
  1601. {
  1602. string filename = pdfDoc.FileName + " " + pageName + ".pdf";
  1603. string path = System.IO.Path.Combine(dialog.SelectedPath, filename);
  1604. path = CreateFilePath(path);
  1605. selectedfile = path;
  1606. CPDFDocument savedoc = CPDFDocument.CreateDocument();
  1607. string range = (data.PageMode == 1 || data.PageMode == 4) ? pageName : String.Join(",", pagenums);
  1608. bool result = savedoc.ImportPages(pdfDoc, range);
  1609. if (!result)
  1610. {
  1611. return;
  1612. }
  1613. result = savedoc.WriteToFilePath(path);
  1614. if (!result)
  1615. {
  1616. }
  1617. savedoc.Release();
  1618. }
  1619. if (data.DeleteAfterExtract)
  1620. {
  1621. List<ListBoxItem> items = new List<ListBoxItem>();
  1622. for (int i = 0; i < pagenums.Count; i++)
  1623. {
  1624. ListBoxItem item = PageEditListBox.Items[pagenums[i]-1] as ListBoxItem;
  1625. items.Add(item);
  1626. }
  1627. DoDelete(items, false);
  1628. CPDFViewer pdfViewer= GetPDFViewer();
  1629. if(pdfViewer != null)
  1630. {
  1631. pdfViewer.UndoManager?.ClearHistory();
  1632. }
  1633. ItemsInViewHitTest();
  1634. }
  1635. Process.Start(@"explorer.exe", "/select,\"" + selectedfile + "\"");
  1636. }
  1637. private void DoPaste()
  1638. {
  1639. if (viewControl == null) return;
  1640. if (ViewportHelper.CopyDoc == null)
  1641. {
  1642. return;
  1643. }
  1644. int insertIndex = 0;
  1645. for (int k = 0; k < PageEditListBox.SelectedItems.Count; k++)
  1646. {
  1647. if (insertIndex < PageEditListBox.Items.IndexOf(PageEditListBox.SelectedItems[k] as ListBoxItem))
  1648. insertIndex = PageEditListBox.Items.IndexOf(PageEditListBox.SelectedItems[k] as ListBoxItem);
  1649. }
  1650. insertIndex++;
  1651. int pagecount = ViewportHelper.CopyDoc.PageCount;
  1652. CPDFDocument pdfDoc = GetPDFDocument();
  1653. if (pdfDoc == null)
  1654. {
  1655. return;
  1656. }
  1657. bool result = pdfDoc.ImportPagesAtIndex(ViewportHelper.CopyDoc, "1-" + pagecount, insertIndex);
  1658. if (!result)
  1659. {
  1660. return;
  1661. }
  1662. CPDFViewer pdfViewer=GetPDFViewer();
  1663. pdfViewer?.UpdateVirtualNodes();
  1664. AddBlankPages(pagecount, insertIndex);
  1665. ItemsInViewHitTest();
  1666. pdfViewer?.UndoManager?.ClearHistory();
  1667. RefreshBookMarkList();
  1668. List<ListBoxItem> pageList = new List<ListBoxItem>();
  1669. PageEditListBox.SelectedItems.Clear();
  1670. for (int i = 0; i < pagecount; i++)
  1671. {
  1672. pageList.Add(PageEditListBox.Items[insertIndex + i] as ListBoxItem);
  1673. PageEditListBox.SelectedItems.Add(PageEditListBox.Items[insertIndex + i] as ListBoxItem);
  1674. }
  1675. UpdateAllPageNum();
  1676. }
  1677. private void DoCopy()
  1678. {
  1679. if (viewControl == null) return;
  1680. if (PageEditListBox.SelectedItems.Count < 1)
  1681. {
  1682. ShowAlertWithTimeout(AlertType.EmptyPageAlert);
  1683. return;
  1684. }
  1685. ViewportHelper.CopyDoc = null;
  1686. ViewportHelper.CopyDoc = CPDFDocument.CreateDocument();
  1687. CPDFDocument pdfDoc=GetPDFDocument();
  1688. if(pdfDoc != null)
  1689. {
  1690. string pageParam = GetPageParam();
  1691. ViewportHelper.CopyDoc.ImportPages(pdfDoc, pageParam);
  1692. }
  1693. }
  1694. private void DoExchange(List<ListBoxItem> pageLists)
  1695. {
  1696. if (pageLists.Count <= 1)
  1697. {
  1698. return;
  1699. }
  1700. List<int> pages = new List<int>();
  1701. for (int i = 0; i < pageLists.Count; i++)
  1702. {
  1703. int pageIndex = PageEditListBox.Items.IndexOf(pageLists[i] as ListBoxItem);
  1704. pages.Add(pageIndex);
  1705. }
  1706. pages.Sort();
  1707. for (int i = 0; i < pages.Count; i++)
  1708. {
  1709. int preindex = pages[i];
  1710. int laterIndex = pages[pages.Count - i - 1];
  1711. if (laterIndex <= preindex)
  1712. return;
  1713. var sourceitem = PageEditListBox.Items[preindex] as ListBoxItem;
  1714. var targetitem = PageEditListBox.Items[laterIndex] as ListBoxItem;
  1715. bindPageList.Remove(sourceitem);
  1716. bindPageList.Remove(targetitem);
  1717. bindPageList.Insert(preindex, targetitem);
  1718. bindPageList.Insert(laterIndex, sourceitem);
  1719. CPDFDocument pdfDoc= GetPDFDocument();
  1720. pdfDoc?.ExchangePage(preindex, laterIndex);
  1721. CPDFViewer pdfViewer=GetPDFViewer();
  1722. pdfViewer?.UndoManager?.ClearHistory();
  1723. PageEditListBox.SelectedItems.Add(targetitem);
  1724. PageEditListBox.SelectedItems.Add(sourceitem);
  1725. }
  1726. }
  1727. private void DoDelete(List<ListBoxItem> pageLists, bool tip)
  1728. {
  1729. if (pageLists.Count == 0)
  1730. {
  1731. ShowAlertWithTimeout(AlertType.EmptyPageAlert);
  1732. return;
  1733. }
  1734. if (pageLists.Count == PageEditListBox.Items.Count)
  1735. {
  1736. ShowAlertWithTimeout(AlertType.AllPageAlert);
  1737. return;
  1738. }
  1739. Winform.DialogResult result = Winform.DialogResult.OK;
  1740. if (tip)
  1741. {
  1742. result = Winform.MessageBox.Show(Helper.LanguageHelper.DocEditorManager.GetString("Warn_Delete")
  1743. , Helper.LanguageHelper.CommonManager.GetString("Caption_Warning")
  1744. , Winform.MessageBoxButtons.OKCancel, Winform.MessageBoxIcon.Warning);
  1745. }
  1746. if (result == Winform.DialogResult.OK || !tip)
  1747. {
  1748. List<int> pages = new List<int>();
  1749. for (int i = 0; i < pageLists.Count; i++)
  1750. {
  1751. var index = PageEditListBox.Items.IndexOf(pageLists[i]);
  1752. pages.Add(index);
  1753. }
  1754. pages.Sort();
  1755. if (pages.Count == 0) return;
  1756. for (int i = pages.Count - 1; i >= 0; i--)
  1757. {
  1758. bindPageList.RemoveAt(pages[i]);
  1759. }
  1760. CPDFDocument pdfDoc=GetPDFDocument();
  1761. if(pdfDoc==null)
  1762. {
  1763. return;
  1764. }
  1765. var r = pdfDoc.RemovePages(pages.ToArray());
  1766. if (!r)
  1767. {
  1768. return;
  1769. }
  1770. CPDFViewer pdfViewer= GetPDFViewer();
  1771. pdfViewer?.UndoManager?.ClearHistory();
  1772. UpdateAllPageNum();
  1773. pdfViewer?.UpdateVirtualNodes();
  1774. }
  1775. }
  1776. private List<ListBoxItem> GetListFromSelectedItems()
  1777. {
  1778. List<ListBoxItem> itemlists = new List<ListBoxItem>();
  1779. for (int i = 0; i < PageEditListBox.SelectedItems.Count; i++)
  1780. {
  1781. itemlists.Add(PageEditListBox.SelectedItems[i] as ListBoxItem);
  1782. }
  1783. return itemlists;
  1784. }
  1785. public static bool GetPagesInRange(ref List<int> pageList, string pageRange, int count, char[] enumerationSeparator, char[] rangeSeparator, bool inittag = false)
  1786. {
  1787. string[] rangeSplit = pageRange.Split(enumerationSeparator);
  1788. pageList.Clear();
  1789. foreach (string range in rangeSplit)
  1790. {
  1791. int starttag = 1;
  1792. if (inittag)
  1793. {
  1794. starttag = 0;
  1795. }
  1796. if (range.Contains("-"))
  1797. {
  1798. try
  1799. {
  1800. string[] limits = range.Split(rangeSeparator);
  1801. if (limits.Length >= 2 && !string.IsNullOrWhiteSpace(limits[0]) && !string.IsNullOrWhiteSpace(limits[1]))
  1802. {
  1803. int start = int.Parse(limits[0]);
  1804. int end = int.Parse(limits[1]);
  1805. if ((start < starttag) || (end > count) || (start > end))
  1806. {
  1807. return false;
  1808. }
  1809. for (int i = start; i <= end; ++i)
  1810. {
  1811. if (pageList.Contains(i))
  1812. {
  1813. return false;
  1814. }
  1815. pageList.Add(i - 1);
  1816. }
  1817. continue;
  1818. }
  1819. }
  1820. catch (Exception ex)
  1821. {
  1822. return false;
  1823. }
  1824. }
  1825. int pageNr;
  1826. try
  1827. {
  1828. pageNr = int.Parse(range);
  1829. }
  1830. catch (Exception)
  1831. {
  1832. return false;
  1833. }
  1834. if (pageNr < starttag || pageNr > count)
  1835. {
  1836. return false;
  1837. }
  1838. if (pageList.Contains(pageNr))
  1839. {
  1840. return false;
  1841. }
  1842. pageList.Add(pageNr - 1);
  1843. }
  1844. return true;
  1845. }
  1846. private void DoAddFromOtherPdf(string filepath, string pagerange, int insertindex, string password)
  1847. {
  1848. CPDFDocument doc = CPDFDocument.InitWithFilePath(filepath);
  1849. if(doc.IsLocked && password != string.Empty)
  1850. {
  1851. if(!doc.UnlockWithPassword(password))
  1852. {
  1853. return;
  1854. }
  1855. }
  1856. int pagecount = 0;
  1857. string insertRange = "";
  1858. if (pagerange == "AllPages")
  1859. {
  1860. pagecount = doc.PageCount;
  1861. insertRange = "1-" + pagecount;
  1862. }
  1863. else if (pagerange == "OddPages")
  1864. {
  1865. pagecount = (doc.PageCount + 1) / 2;
  1866. int[] page = new int[(doc.PageCount + 1) / 2];
  1867. for (int i = 0; i < page.Length; i++)
  1868. {
  1869. page[i] = i * 2 + 1;
  1870. }
  1871. insertRange = string.Join(",", page);
  1872. }
  1873. else if (pagerange == "EvenPages")
  1874. {
  1875. if (doc.PageCount == 1)
  1876. {
  1877. insertRange = "1";
  1878. pagecount = 1;
  1879. }
  1880. else
  1881. {
  1882. pagecount = doc.PageCount / 2;
  1883. int[] page = new int[doc.PageCount / 2];
  1884. for (int i = 0; i < page.Length; i++)
  1885. {
  1886. page[i] = i * 2 + 2;
  1887. }
  1888. insertRange = string.Join(",", page);
  1889. }
  1890. }
  1891. else
  1892. {
  1893. List<int> page = new List<int>();
  1894. GetPagesInRange(ref page, pagerange, doc.PageCount, new char[] { ',' }, new char[] { '-' });
  1895. insertRange = pagerange;
  1896. pagecount = page.Count;
  1897. }
  1898. CPDFDocument pdfDoc = GetPDFDocument();
  1899. if(pdfDoc == null)
  1900. {
  1901. return;
  1902. }
  1903. var result = pdfDoc.ImportPagesAtIndex(doc, insertRange, insertindex);
  1904. if (!result)
  1905. {
  1906. return;
  1907. }
  1908. doc.Release();
  1909. RefreshThumbnail();
  1910. PageEditListBox.SelectedItems.Clear();
  1911. for (int i = insertindex; i < insertindex + pagecount; i++)
  1912. {
  1913. PageEditListBox.SelectedItems.Add(PageEditListBox.Items[i] as ListBoxItem);
  1914. }
  1915. }
  1916. private string GetPageParam()
  1917. {
  1918. string pageParam = "";
  1919. List<int> pagesList = new List<int>();
  1920. for (int i = 0; i < PageEditListBox.SelectedItems.Count; i++)
  1921. {
  1922. var item = PageEditListBox.SelectedItems[i] as ListBoxItem;
  1923. var page = GetPageNumTextBlock(item);
  1924. if (page != null)
  1925. {
  1926. pagesList.Add(int.Parse(page.Text));
  1927. }
  1928. }
  1929. if (pagesList.Count != 0)
  1930. {
  1931. pagesList.Sort();
  1932. for (int i = 0; i < pagesList.Count; i++)
  1933. {
  1934. if (i == 0)
  1935. {
  1936. pageParam += pagesList[0].ToString();
  1937. }
  1938. else
  1939. {
  1940. if (pagesList[i] == pagesList[i - 1] + 1)
  1941. {
  1942. if (i >= 2)
  1943. {
  1944. if (pagesList[i - 1] != pagesList[i - 2] + 1)
  1945. pageParam += "-";
  1946. }
  1947. else
  1948. pageParam += "-";
  1949. if (i == pagesList.Count - 1)
  1950. {
  1951. pageParam += pagesList[i].ToString();
  1952. }
  1953. }
  1954. else
  1955. {
  1956. if (i >= 2)
  1957. {
  1958. if (pagesList[i - 1] == pagesList[i - 2] + 1)
  1959. pageParam += pagesList[i - 1].ToString();
  1960. }
  1961. pageParam += "," + pagesList[i].ToString();
  1962. }
  1963. }
  1964. }
  1965. }
  1966. return pageParam;
  1967. }
  1968. public static BitmapSource ToBitmapSource(string path)
  1969. {
  1970. System.Drawing.Icon ico = System.Drawing.Icon.ExtractAssociatedIcon(path);
  1971. System.Drawing.Bitmap bitmap = ico.ToBitmap();
  1972. BitmapSource returnSource;
  1973. try
  1974. {
  1975. returnSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(bitmap.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
  1976. }
  1977. catch
  1978. {
  1979. returnSource = null;
  1980. }
  1981. return returnSource;
  1982. }
  1983. private Tuple<int, int, int> GetRoughViewportRange(ListBox view, Size itemSize, Thickness itemMargin)
  1984. {
  1985. var scrollViewer = GetScrollHost(view);
  1986. CPDFDocument pdfDoc = GetPDFDocument();
  1987. if (pdfDoc == null)
  1988. {
  1989. return new Tuple<int, int, int>(0, 0, 0);
  1990. }
  1991. if (viewControl == null || pdfDoc == null || scrollViewer == null || scrollViewer.ActualHeight == 0 || scrollViewer.ActualWidth == 0)
  1992. return new Tuple<int, int, int>(0, 0, 0);
  1993. try
  1994. {
  1995. var currentHeight = scrollViewer.ActualHeight - view.Padding.Top;
  1996. var currentWidth = scrollViewer.ActualWidth;
  1997. var columnCount = (int)(currentWidth / (itemSize.Width + itemMargin.Left));
  1998. var rowCount = (int)Math.Ceiling(currentHeight / (itemSize.Height + itemMargin.Bottom));
  1999. var preItemCount = (int)((scrollViewer.VerticalOffset / scrollViewer.ExtentHeight) * ((pdfDoc.PageCount + columnCount - 1) / columnCount));
  2000. preItemCount = preItemCount * columnCount;
  2001. var preEnd = (int)(((scrollViewer.VerticalOffset + scrollViewer.ActualHeight) / scrollViewer.ExtentHeight) * ((pdfDoc.PageCount + columnCount - 1) / columnCount));
  2002. preEnd = preEnd * columnCount + columnCount - 1;
  2003. var middle = (int)Math.Ceiling(preItemCount + preEnd / 2d);
  2004. return new Tuple<int, int, int>(
  2005. Math.Max(preItemCount, 0),
  2006. Math.Min(view.Items.Count, preEnd),
  2007. middle);
  2008. }
  2009. catch (Exception ex)
  2010. {
  2011. }
  2012. return new Tuple<int, int, int>(0, 0, 0);
  2013. }
  2014. private void ShowAlertWithTimeout(AlertType alertType)
  2015. {
  2016. AlertBorder.Visibility = Visibility.Visible;
  2017. AlertBorder.Opacity = 1.0;
  2018. if (alertType == AlertType.EmptyPageAlert)
  2019. {
  2020. AlertTextBlock.Text = Helper.LanguageHelper.DocEditorManager.GetString("Tip_NoPage");
  2021. }
  2022. else if (alertType == AlertType.SinglePageALert)
  2023. {
  2024. AlertTextBlock.Text = "Please select above two pages.";
  2025. }
  2026. else if (alertType == AlertType.AllPageAlert)
  2027. {
  2028. AlertTextBlock.Text = Helper.LanguageHelper.DocEditorManager.GetString("Tip_AllPage");
  2029. }
  2030. DoubleAnimation animation = new DoubleAnimation();
  2031. animation.From = 1.0;
  2032. animation.To = 0.0;
  2033. animation.Duration = TimeSpan.FromSeconds(3);
  2034. AlertBorder.BeginAnimation(OpacityProperty, animation);
  2035. }
  2036. #endregion
  2037. private void UserControl_MouseEnter(object sender, MouseEventArgs e)
  2038. {
  2039. MidLane.Visibility = Visibility.Collapsed;
  2040. }
  2041. private void UserControl_SizeChanged(object sender, SizeChangedEventArgs e)
  2042. {
  2043. ItemsInViewHitTest();
  2044. }
  2045. private CPDFDocument GetPDFDocument()
  2046. {
  2047. CPDFViewer pdfViewer = GetPDFViewer();
  2048. if (pdfViewer!=null)
  2049. {
  2050. return pdfViewer.GetDocument();
  2051. }
  2052. return null;
  2053. }
  2054. private CPDFViewer GetPDFViewer()
  2055. {
  2056. if (viewControl != null && viewControl.PDFViewTool != null)
  2057. {
  2058. CPDFViewer pdfViewer = viewControl.PDFViewTool.GetCPDFViewer();
  2059. if (pdfViewer != null)
  2060. {
  2061. return pdfViewer;
  2062. }
  2063. }
  2064. return null;
  2065. }
  2066. public async Task GetThumbnail(int pageIndex, int imageWidth, int imageHeight)
  2067. {
  2068. if (imageWidth <= 0 || imageHeight <= 0)
  2069. {
  2070. return;
  2071. }
  2072. if (viewControl == null || viewControl.PDFViewTool == null)
  2073. {
  2074. return;
  2075. }
  2076. CPDFViewer pdfViewer = viewControl.PDFViewTool.GetCPDFViewer();
  2077. CPDFDocument pdfdoc = pdfViewer?.GetDocument();
  2078. if (pdfdoc == null)
  2079. {
  2080. return;
  2081. }
  2082. CPDFPage page = pdfdoc.PageAtIndex(pageIndex);
  2083. byte[] bmpData = new byte[imageWidth * imageHeight * 4];
  2084. await Task.Run(() => page.RenderPageBitmap(0, 0, imageWidth, imageHeight, 0xFFFFFFFF, bmpData, 1, true));
  2085. if (OnThumbnailGenerated != null)
  2086. {
  2087. OnThumbnailGenerated(pageIndex, bmpData, imageWidth, imageHeight);
  2088. }
  2089. }
  2090. }
  2091. public class InsertEventClass : EventArgs
  2092. {
  2093. public InsertType InsertType = InsertType.BlankPages;
  2094. public string FilePath = string.Empty;
  2095. public double PageWidth = 210 * 2.54;
  2096. public double PageHeight = 297 * 2.54;
  2097. public string PageRange = "0";
  2098. public int InsertIndex = 0;
  2099. public string Password = string.Empty;
  2100. }
  2101. public enum InsertType
  2102. {
  2103. BlankPages,
  2104. CustomBlankPages,
  2105. FromOtherPDF
  2106. }
  2107. /// <summary>
  2108. /// The parameter class used for extraction
  2109. /// </summary>
  2110. public class ExtractEventClass : EventArgs
  2111. {
  2112. /// <summary>
  2113. /// 1- All pages 2 - Odd pages 3 - Even pages 4 - Custom ranges
  2114. /// </summary>
  2115. public int PageMode;
  2116. /// <summary>
  2117. /// PageMode = 1,2,3 PageParm = null;
  2118. /// </summary>
  2119. public List<int> PageParm;
  2120. /// <summary>
  2121. /// In custom mode, the text content is passed over
  2122. /// </summary>
  2123. public string PageName = "";
  2124. /// <summary>
  2125. /// Whether to split into a single file
  2126. /// </summary>
  2127. public bool ExtractToSingleFile;
  2128. /// <summary>
  2129. /// Delete the page after extraction
  2130. /// </summary>
  2131. public bool DeleteAfterExtract;
  2132. }
  2133. public enum AlertType
  2134. {
  2135. EmptyPageAlert,
  2136. SinglePageALert,
  2137. AllPageAlert,
  2138. }
  2139. }