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