CPDFPageEditControl.xaml.cs 85 KB

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