CPDFPageEditControl.xaml.cs 84 KB

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