CPDFPageEditControl.xaml.cs 85 KB

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