CPDFPageEditControl.xaml.cs 89 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358
  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)//创建空白文档 更新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. /// <summary>
  1117. /// 需要先从文档层添加,再添加UI层,保证显示的页大小准确
  1118. /// </summary>
  1119. /// <param name="ItemIndex"></param>
  1120. /// <returns></returns>
  1121. public ListBoxItem GetNewItem(int ItemIndex)
  1122. {
  1123. int thumbnailWidth = thumbnailSize[zoomLevel];
  1124. Size pageSize = pdfViewer.Document.GetPageSize(ItemIndex);
  1125. if (pageSize.Width == 0 || pageSize.Height == 0)// 全选替换时,手动设定页码大小
  1126. {
  1127. pageSize = new Size(228, 300);
  1128. }
  1129. int imageWidth = pageSize.Width > pageSize.Height ? thumbnailWidth * 2 : (int)(pageSize.Width / pageSize.Height * thumbnailWidth * 2);
  1130. int imageHeight = pageSize.Height > pageSize.Width ? thumbnailWidth * 2 : (int)(pageSize.Height / pageSize.Width * thumbnailWidth * 2);
  1131. Image img = new Image()
  1132. {
  1133. // Margin = new Thickness(0, 0, 5, 0),
  1134. Width = imageWidth,
  1135. Height = imageHeight,
  1136. Stretch = Stretch.Uniform,
  1137. };
  1138. Grid grid = new Grid();
  1139. grid.Children.Add(img);
  1140. List<Point> points = new List<Point>()
  1141. {
  1142. new Point(16.75,1.25),
  1143. new Point(3.25,1.25 ),
  1144. new Point(3.25,19.4013878),
  1145. new Point(10,14.902),
  1146. new Point(16.75,19.4013878),
  1147. };
  1148. Polygon bookmark = new Polygon()
  1149. {
  1150. Points = new PointCollection(points),
  1151. Fill = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#FFBB00")),
  1152. Margin = new Thickness(0, 8, 8, 0),
  1153. VerticalAlignment = VerticalAlignment.Top,
  1154. HorizontalAlignment = HorizontalAlignment.Right,
  1155. Visibility = Visibility.Collapsed,
  1156. };
  1157. grid.Children.Add(bookmark);
  1158. Border border = new Border()
  1159. {
  1160. BorderThickness = new Thickness(2),
  1161. BorderBrush = new SolidColorBrush((System.Windows.Media.Color)System.Windows.Media.ColorConverter.ConvertFromString("#A0A2AE")),
  1162. Child = grid,
  1163. };
  1164. Viewbox viewBox = new Viewbox()
  1165. {
  1166. Margin = new Thickness(0, 8, 0, 0),
  1167. Stretch = System.Windows.Media.Stretch.Uniform,
  1168. Width = thumbnailWidth,
  1169. Height = thumbnailWidth,
  1170. Child = border,
  1171. };
  1172. TextBlock text = new TextBlock()
  1173. {
  1174. HorizontalAlignment = System.Windows.HorizontalAlignment.Center,
  1175. Text = (ItemIndex + 1).ToString(),
  1176. Foreground = Brushes.Black,
  1177. Margin = new Thickness(0, 8, 0, 8),
  1178. };
  1179. StackPanel panel = new StackPanel();
  1180. panel.Children.Add(viewBox);
  1181. panel.Children.Add(text);
  1182. ListBoxItem item = new ListBoxItem();
  1183. item.Content = panel;
  1184. item.Tag = ItemIndex;
  1185. item.Margin = new Thickness(6, 10, 6, 10);
  1186. return item;
  1187. }
  1188. //UI层 在指定位置插入一定数量的空白页 在文档操作之后
  1189. public void AddBlankPages(int pagecount, int insertindex)
  1190. {
  1191. for (int i = 0; i < pagecount; i++)
  1192. {
  1193. var item = GetNewItem(insertindex + i);
  1194. bindPageList.Insert(insertindex + i, item);
  1195. if (visiblePageIndexes.Contains(insertindex + i))
  1196. visiblePageIndexes.Remove(insertindex + i);//如果不删除,则不会显示图片
  1197. }
  1198. PageEditListBox.UpdateLayout();
  1199. }
  1200. /// <summary>
  1201. /// 刷新指定页面的UI
  1202. /// </summary>
  1203. /// <param name="pageindex"></param>
  1204. private async void RenderPage(int pageindex)
  1205. {
  1206. var range = GetRoughViewportRange(PageEditListBox, (PageEditListBox.Items[0] as ListBoxItem).DesiredSize, new Thickness(6, 10, 6, 10));
  1207. if (pageindex < range.Item1 || pageindex > range.Item2)
  1208. return;
  1209. ListBoxItem item = PageEditListBox.Items[pageindex] as ListBoxItem;
  1210. Image img = GetImageElement(item);
  1211. await pdfViewer.GetThumbnail(pageindex, (int)img.Width, (int)img.Height);
  1212. }
  1213. private async void ItemsInViewHitTest()
  1214. {
  1215. if (pdfViewer == null || pdfViewer.Document == null)
  1216. return;
  1217. try
  1218. {
  1219. ScrollViewer sv = GetScrollHost(PageEditListBox);
  1220. if (sv == null) return;
  1221. if (VisualTreeHelper.GetParent(this) == null)
  1222. return;
  1223. //List<int> pagesOnScreen = new List<int>();
  1224. //pageThumbnailsToRequest.Clear();
  1225. var range = GetRoughViewportRange(PageEditListBox, (PageEditListBox.Items[0] as ListBoxItem).DesiredSize, new Thickness(6, 10, 6, 10));
  1226. for (int i = 0; i < PageEditListBox.Items.Count; ++i)
  1227. {
  1228. //if (i>=pdfViewer.Document.PageCount)
  1229. //{
  1230. // break;
  1231. //}
  1232. ListBoxItem item = PageEditListBox.Items[i] as ListBoxItem;
  1233. // ListBoxItem listboxitem = PageEditListBox.ItemContainerGenerator.ContainerFromIndex(i) as ListBoxItem;
  1234. Image img = GetImageElement(item);
  1235. if (i >= (range.Item1 - 1) && i <= range.Item2 || ViewportHelper.IsInViewport(sv, item))//更改判断方式 因为BOTA缩略图不准确
  1236. {
  1237. if (img.Source == null && !visiblePageIndexes.Contains(i))
  1238. {
  1239. visiblePageIndexes.Add(i);
  1240. await Task.Delay(1);//有刷不出图的情况 增减页面时
  1241. await pdfViewer.GetThumbnail(i, (int)img.Width, (int)img.Height);
  1242. Debug.WriteLine("Page {0} is visible, asking for thumb", (i + 1));
  1243. }
  1244. else if (img.Source == null)
  1245. {
  1246. await pdfViewer.GetThumbnail(i, (int)img.Width, (int)img.Height);
  1247. Debug.WriteLine("Page {0} is visible, asking for thumb", (i + 1));
  1248. }
  1249. }
  1250. else
  1251. {
  1252. if (visiblePageIndexes.Contains(i))
  1253. {
  1254. Image image = GetImageElement(PageEditListBox.Items[i] as ListBoxItem);
  1255. if (image.Source != null)
  1256. {
  1257. image.Source = null;
  1258. //(image.Parent as Border).BorderBrush = Brushes.Transparent;
  1259. Debug.WriteLine("Page {0} is out of range, removed thumb", (i + 1));
  1260. }
  1261. else
  1262. {
  1263. Debug.WriteLine("Page {0} is out of range, but had no thumb", (i + 1));
  1264. }
  1265. visiblePageIndexes.Remove(i);
  1266. }
  1267. }
  1268. }
  1269. }
  1270. catch (Exception ex)
  1271. {
  1272. Debug.WriteLine(ex.ToString());
  1273. }
  1274. }
  1275. public void RefreshBookMarkList()
  1276. {
  1277. if (pdfViewer != null)
  1278. {
  1279. var booklist = pdfViewer.Document.GetBookmarkList();
  1280. if (booklist == null) return;
  1281. List<int> marks = new List<int>();
  1282. for (int i = 0; i < booklist.Count; i++)
  1283. {
  1284. marks.Add(booklist[i].PageIndex);
  1285. }
  1286. for (int k = 0; k < PageEditListBox.Items.Count; k++)
  1287. {
  1288. Polygon polygon = GetBookMarkIco(PageEditListBox.Items[k] as ListBoxItem);
  1289. if (marks.Contains(k))
  1290. polygon.Visibility = Visibility.Visible;
  1291. else
  1292. polygon.Visibility = Visibility.Collapsed;
  1293. }
  1294. }
  1295. }
  1296. private void UpdateSelectedIndex()
  1297. {
  1298. if (PageEditListBox.Items.Count == 0)
  1299. PageEditListBox.SelectedIndex = -1;
  1300. else if (PageEditListBox.Items.Count <= pdfViewer.CurrentIndex)
  1301. this.PageEditListBox.SelectedIndex = 0;
  1302. else if (PageEditListBox.SelectedIndex != pdfViewer.CurrentIndex)
  1303. PageEditListBox.SelectedIndex = pdfViewer.CurrentIndex;
  1304. PageEditListBox.ScrollIntoView(PageEditListBox.Items[PageEditListBox.SelectedIndex]);
  1305. }
  1306. private Image GetImageElement(ListBoxItem item)
  1307. {
  1308. Viewbox viewBox = (item.Content as StackPanel).Children[0] as Viewbox;
  1309. Image img = ((viewBox.Child as Border).Child as Grid).Children[0] as Image;
  1310. return img;
  1311. }
  1312. private Polygon GetBookMarkIco(ListBoxItem item)
  1313. {
  1314. Viewbox viewBox = (item.Content as StackPanel).Children[0] as Viewbox;
  1315. Polygon ico = ((viewBox.Child as Border).Child as Grid).Children[1] as Polygon;
  1316. return ico;
  1317. }
  1318. private StackPanel GetPanel(ListBoxItem item)
  1319. {
  1320. StackPanel panel = item.Content as StackPanel;
  1321. return panel;
  1322. }
  1323. private TextBlock GetPageNumTextBlock(ListBoxItem item)
  1324. {
  1325. TextBlock text = (item.Content as StackPanel).Children[1] as TextBlock;
  1326. return text;
  1327. }
  1328. public VirtualizingWrapPanel GetWrapPanel(ListBox listBox)
  1329. {
  1330. Border border = VisualTreeHelper.GetChild(listBox, 0) as Border;
  1331. var panel = Utils.FindVisualChild<VirtualizingWrapPanel>(border);
  1332. return panel;
  1333. }
  1334. private ScrollViewer GetScrollHost(ListBox listBox)
  1335. {
  1336. if (VisualTreeHelper.GetChildrenCount(listBox) > 0)
  1337. {
  1338. int s = VisualTreeHelper.GetChildrenCount(listBox);
  1339. Border border = VisualTreeHelper.GetChild(listBox, 0) as Border;
  1340. if (border != null)
  1341. {
  1342. return VisualTreeHelper.GetChild(border, 0) as ScrollViewer;
  1343. }
  1344. }
  1345. return null;
  1346. }
  1347. //拖拽排序的主体方法
  1348. private void DragToSort(int sourceindex, int targetindex)
  1349. {
  1350. if (targetindex == sourceindex || targetindex < 0)
  1351. {
  1352. MidLane.Visibility = Visibility.Collapsed;
  1353. return;
  1354. }
  1355. var source = PageEditListBox.Items[sourceindex];
  1356. bindPageList.RemoveAt(sourceindex);
  1357. MidLane.Visibility = Visibility.Collapsed;
  1358. bindPageList.Insert(targetindex, source as ListBoxItem);
  1359. PageEditListBox.SelectedItems.Add(source);
  1360. var result = pdfViewer.Document.MovePage(sourceindex, targetindex);
  1361. if (!result)
  1362. {
  1363. MidLane.Visibility = Visibility.Collapsed;
  1364. return;
  1365. }
  1366. pdfViewer.ReloadDocument();
  1367. pdfViewer.GoToPage(PageEditListBox.SelectedIndex);
  1368. pdfViewer.UndoManager.ClearHistory();
  1369. pdfViewer.UndoManager.CanSave = true;
  1370. ItemsInViewHitTest();
  1371. this.PageMoved.Invoke(this, new RoutedEventArgs());
  1372. UpdateSortedPageNum(sourceindex, targetindex);
  1373. }
  1374. //更新排序后的页码 适用于总页数不变的情况
  1375. private void UpdateSortedPageNum(int sourceIndex, int targetIndex)
  1376. {
  1377. int sum = sourceIndex + targetIndex;
  1378. targetIndex = targetIndex > sourceIndex ? targetIndex : sourceIndex;//保证targetindex为较大值
  1379. sourceIndex = sum - targetIndex;
  1380. sourceIndex = sourceIndex <= 0 ? 0 : sourceIndex;
  1381. targetIndex = targetIndex + 1 > PageEditListBox.Items.Count ? PageEditListBox.Items.Count - 1 : targetIndex;
  1382. for (int i = sourceIndex; i <= targetIndex; i++)
  1383. {
  1384. var item = PageEditListBox.Items[i] as ListBoxItem;
  1385. item.Tag = i;
  1386. TextBlock pagenum = GetPageNumTextBlock(item);
  1387. pagenum.Text = (i + 1).ToString();
  1388. }
  1389. }
  1390. /// <summary>
  1391. /// 适用于页总数发生改变的页码更新
  1392. /// </summary>
  1393. private void UpdateAllPageNum()
  1394. {
  1395. for (int i = 0; i < PageEditListBox.Items.Count; i++)
  1396. {
  1397. var pagenum = GetPageNumTextBlock(PageEditListBox.Items[i] as ListBoxItem);
  1398. pagenum.Text = (i + 1).ToString();
  1399. (PageEditListBox.Items[i] as ListBoxItem).Tag = i;
  1400. }
  1401. }
  1402. public void DoInsert(EventArgs e)
  1403. {
  1404. var data = e as InsertEventClass;
  1405. if (data.InsertType == InsertType.BlankPages)
  1406. {
  1407. var size = pdfViewer.Document.GetPageSize(data.InsertIndex - 1);
  1408. if (size.Width == 0 || size.Height == 0)
  1409. size = pdfViewer.Document.GetPageSize(data.InsertIndex);
  1410. pdfViewer.Document.InsertPage(data.InsertIndex, size.Width, size.Height, null);
  1411. RefreshThumbnail();
  1412. PageEditListBox.SelectedItems.Clear();
  1413. PageEditListBox.SelectedIndex = data.InsertIndex;
  1414. }
  1415. else if (data.InsertType == InsertType.CustomBlankPages)
  1416. {
  1417. pdfViewer.Document.InsertPage(data.InsertIndex, data.PageWidth, data.PageHeight, null);
  1418. RefreshThumbnail();
  1419. PageEditListBox.SelectedItems.Clear();
  1420. PageEditListBox.SelectedIndex = data.InsertIndex;
  1421. }
  1422. else
  1423. {
  1424. DoAddFromOtherPdf(data.FilePath, data.PageRange, data.InsertIndex, data.Password);
  1425. }
  1426. UpdateAllPageNum();
  1427. pdfViewer.UndoManager.ClearHistory();
  1428. pdfViewer.UndoManager.CanSave = true;
  1429. pdfViewer.ReloadDocument();
  1430. PageEditListBox.ScrollIntoView(PageEditListBox.SelectedItem as ListBoxItem);
  1431. ItemsInViewHitTest();//刷新图片
  1432. }
  1433. public void DoReplace()
  1434. {
  1435. if (PageEditListBox.SelectedItems.Count < 1)
  1436. {
  1437. ShowAlertWithTimeout(AlertType.EmptyPageAlert);
  1438. return;
  1439. }
  1440. OpenFileDialog dialog = new OpenFileDialog();
  1441. dialog.Multiselect = false;
  1442. dialog.Filter = "(*.pdf)|*.pdf";
  1443. if ((bool)dialog.ShowDialog())
  1444. {
  1445. //用选择的整个文件替换选中页
  1446. CPDFDocument doc = CPDFDocument.InitWithFilePath(dialog.FileName);
  1447. //文件页数
  1448. int pagecount = doc.PageCount;
  1449. int insertindex = PageEditListBox.Items.IndexOf(PageEditListBox.SelectedItem);
  1450. if (insertindex == -1)
  1451. insertindex = 0;
  1452. var result = pdfViewer.Document.ImportPagesAtIndex(doc, "1-" + pagecount, insertindex);
  1453. doc.Release();
  1454. //UI层插入
  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. // RefreshThumbnail();
  1463. pdfViewer.UndoManager.ClearHistory();
  1464. pdfViewer.UndoManager.CanSave = true;
  1465. var list = GetListFromSelectedItems();
  1466. for (int i = insertindex; i < (insertindex + pagecount); i++)
  1467. {
  1468. if (i < PageEditListBox.Items.Count)
  1469. {
  1470. ListBoxItem t = PageEditListBox.Items[i] as ListBoxItem;
  1471. PageEditListBox.SelectedItems.Add(t);
  1472. }
  1473. }
  1474. DoDelete(list, false);
  1475. UpdateAllPageNum();//更新页码
  1476. RefreshBookMarkList();
  1477. ItemsInViewHitTest();//刷新图片
  1478. }
  1479. }
  1480. private void DoRotate(double angleStep)
  1481. {
  1482. if (pdfViewer == null) return;
  1483. if (PageEditListBox.SelectedItems.Count < 1)
  1484. {
  1485. ShowAlertWithTimeout(AlertType.EmptyPageAlert);
  1486. return;
  1487. }
  1488. List<ListBoxItem> pages = new List<ListBoxItem>();
  1489. for (int i = 0; i < PageEditListBox.SelectedItems.Count; i++)
  1490. {
  1491. var image = GetImageElement(PageEditListBox.SelectedItems[i] as ListBoxItem);
  1492. pages.Add(PageEditListBox.SelectedItems[i] as ListBoxItem);
  1493. double angle = (double)image.LayoutTransform.GetValue(RotateTransform.AngleProperty);
  1494. angle += angleStep;
  1495. angle = angle % 360;
  1496. image.LayoutTransform = new RotateTransform(angle, image.ActualWidth / 2, image.ActualHeight / 2);
  1497. var index = PageEditListBox.Items.IndexOf(PageEditListBox.SelectedItems[i]);
  1498. pdfViewer.Document.RotatePage(index, (int)angleStep / 90);
  1499. pdfViewer.Document.ReleasePages(index);
  1500. //旋转页面后取消选中
  1501. pdfViewer.ClearSelectPDFEdit(true);
  1502. pdfViewer.UndoManager.ClearHistory();
  1503. pdfViewer.UndoManager.CanSave = true;
  1504. if (visiblePageIndexes.Contains(index))
  1505. visiblePageIndexes.Remove(index);
  1506. }
  1507. pdfViewer.ReloadDocument();
  1508. ItemsInViewHitTest();
  1509. }
  1510. /// <summary>
  1511. /// 检测文件是否重复 追加尾号
  1512. /// </summary>
  1513. /// <param name="path"></param>
  1514. /// <returns></returns>
  1515. public static string CreateFilePath(string path)
  1516. {
  1517. int i = 1;
  1518. string oldDestName = path;
  1519. do
  1520. {
  1521. if (File.Exists(path))
  1522. {
  1523. int lastDot = oldDestName.LastIndexOf('.');
  1524. string fileExtension = string.Empty;
  1525. string fileName = oldDestName;
  1526. if (lastDot > 0)
  1527. {
  1528. fileExtension = fileName.Substring(lastDot);
  1529. fileName = fileName.Substring(0, lastDot);
  1530. }
  1531. path = fileName + string.Format(@"({0})", i) + fileExtension;
  1532. }
  1533. ++i;
  1534. } while (File.Exists(path));
  1535. return path;
  1536. }
  1537. public void DoExtract(EventArgs e)
  1538. {
  1539. var data = e as ExtractEventClass;
  1540. int pagecount = pdfViewer.Document.PageCount;
  1541. string pageName = "";
  1542. //获取页码范围
  1543. List<int> pagenums = new List<int>();
  1544. pagenums.Clear();
  1545. switch (data.PageMode)
  1546. {
  1547. case 1://全部页面
  1548. for (int i = 0; i < pagecount; i++)
  1549. {
  1550. pagenums.Add(i + 1);
  1551. }
  1552. pageName = "1-" + pagecount;
  1553. break;
  1554. case 2://奇数页面
  1555. int count = (pagecount + 1) / 2;
  1556. for (int i = 0; i < count; i++)
  1557. {
  1558. pagenums.Add(i * 2 + 1);
  1559. }
  1560. pageName = "OddPages";
  1561. break;
  1562. case 3://偶数页面
  1563. if (pagecount == 1)//弹窗时,已经过滤了一次,此处为以防万一。
  1564. return;
  1565. count = pagecount / 2;
  1566. for (int i = 0; i < count; i++)
  1567. {
  1568. pagenums.Add(i * 2 + 2);
  1569. }
  1570. pageName = "EvenPages";
  1571. break;
  1572. case 4://自定义范围
  1573. //弹窗已经判断过文本内容是否合理
  1574. pagenums = data.PageParm;
  1575. pageName = data.PageName;
  1576. break;
  1577. default:
  1578. break;
  1579. }
  1580. System.Windows.Forms.FolderBrowserDialog dialog = new System.Windows.Forms.FolderBrowserDialog();
  1581. if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
  1582. {
  1583. if (string.IsNullOrEmpty(dialog.SelectedPath))
  1584. {
  1585. return;
  1586. }
  1587. }
  1588. else
  1589. return;
  1590. //要显示文件路径
  1591. string selectedfile = "";
  1592. //根据是否单页生成文件 处理
  1593. if (data.ExtractToSingleFile)
  1594. {
  1595. for (int i = 0; i < pagenums.Count; i++)
  1596. {
  1597. string filename = pdfViewer.Document.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(pdfViewer.Document, (pagenums[i]).ToString());
  1603. if (!result)
  1604. {
  1605. //SetReadModeTip(true, "提取异常,请稍后重试", false);
  1606. savedoc.Release();
  1607. continue;
  1608. }
  1609. result = savedoc.WriteToFilePath(path);
  1610. if (!result)
  1611. {
  1612. savedoc.Release();
  1613. continue;
  1614. //File.Delete(path);
  1615. // SetReadModeTip(true, "保存异常,请稍后重试", false);
  1616. }
  1617. savedoc.Release();//释放内存
  1618. }
  1619. }
  1620. else//全部生成一个文件
  1621. {
  1622. string filename = pdfViewer.Document.FileName + " " + pageName + ".pdf";
  1623. string path = System.IO.Path.Combine(dialog.SelectedPath, filename);
  1624. path = CreateFilePath(path);
  1625. selectedfile = path;
  1626. CPDFDocument savedoc = CPDFDocument.CreateDocument();
  1627. string range = (data.PageMode == 1 || data.PageMode == 4) ? pageName : String.Join(",", pagenums);
  1628. bool result = savedoc.ImportPages(pdfViewer.Document, range);
  1629. if (!result)
  1630. {
  1631. return;
  1632. // File.Delete(path);
  1633. }
  1634. result = savedoc.WriteToFilePath(path);
  1635. if (!result)
  1636. {
  1637. //File.Delete(path);
  1638. }
  1639. //IsModefied = true;
  1640. savedoc.Release();//释放内存
  1641. }
  1642. if (data.DeleteAfterExtract)//提取后删除
  1643. {
  1644. List<ListBoxItem> items = new List<ListBoxItem>();
  1645. for (int i = 0; i < pagenums.Count; i++)
  1646. {
  1647. ListBoxItem item = PageEditListBox.Items[pagenums[i]-1] as ListBoxItem;
  1648. items.Add(item);
  1649. }
  1650. DoDelete(items, false);
  1651. pdfViewer.UndoManager.ClearHistory();
  1652. pdfViewer.UndoManager.CanSave = true;
  1653. ItemsInViewHitTest();
  1654. }
  1655. Process.Start(@"explorer.exe", "/select,\"" + selectedfile + "\"");
  1656. }
  1657. private void DoPaste()
  1658. {
  1659. if (pdfViewer == null) return;
  1660. if (ViewportHelper.CopyDoc == null)
  1661. {
  1662. return;
  1663. }
  1664. int insertIndex = 0;
  1665. //粘贴在所有选中项末尾
  1666. for (int k = 0; k < PageEditListBox.SelectedItems.Count; k++)
  1667. {
  1668. if (insertIndex < PageEditListBox.Items.IndexOf(PageEditListBox.SelectedItems[k] as ListBoxItem))
  1669. insertIndex = PageEditListBox.Items.IndexOf(PageEditListBox.SelectedItems[k] as ListBoxItem);
  1670. }
  1671. insertIndex++;
  1672. int pagecount = ViewportHelper.CopyDoc.PageCount;
  1673. bool result = pdfViewer.Document.ImportPagesAtIndex(ViewportHelper.CopyDoc, "1-" + pagecount, insertIndex);
  1674. if (!result)
  1675. {
  1676. return;
  1677. }
  1678. pdfViewer.ReloadDocument();
  1679. AddBlankPages(pagecount, insertIndex);
  1680. ItemsInViewHitTest();
  1681. pdfViewer.UndoManager.ClearHistory();
  1682. pdfViewer.UndoManager.CanSave = true;
  1683. RefreshBookMarkList();
  1684. List<ListBoxItem> pageList = new List<ListBoxItem>();
  1685. PageEditListBox.SelectedItems.Clear();
  1686. for (int i = 0; i < pagecount; i++)
  1687. {
  1688. pageList.Add(PageEditListBox.Items[insertIndex + i] as ListBoxItem);
  1689. PageEditListBox.SelectedItems.Add(PageEditListBox.Items[insertIndex + i] as ListBoxItem);
  1690. }
  1691. UpdateAllPageNum();
  1692. }
  1693. private void DoCopy()
  1694. {
  1695. if (pdfViewer == null) return;
  1696. if (PageEditListBox.SelectedItems.Count < 1)
  1697. {
  1698. ShowAlertWithTimeout(AlertType.EmptyPageAlert);
  1699. return;
  1700. }
  1701. ViewportHelper.CopyDoc = null;
  1702. ViewportHelper.CopyDoc = CPDFDocument.CreateDocument();
  1703. string pageParam = GetPageParam();
  1704. bool result = ViewportHelper.CopyDoc.ImportPages(pdfViewer.Document, pageParam);
  1705. if (!result)
  1706. {
  1707. return;
  1708. }
  1709. }
  1710. private void DoExchange(List<ListBoxItem> pageLists)
  1711. {
  1712. if (pageLists.Count <= 1)
  1713. {
  1714. return;
  1715. }
  1716. List<int> pages = new List<int>();
  1717. for (int i = 0; i < pageLists.Count; i++)
  1718. {
  1719. int pageIndex = PageEditListBox.Items.IndexOf(pageLists[i] as ListBoxItem);
  1720. pages.Add(pageIndex);
  1721. }
  1722. pages.Sort();
  1723. for (int i = 0; i < pages.Count; i++)
  1724. {
  1725. int preindex = pages[i];
  1726. int laterIndex = pages[pages.Count - i - 1];//尾部的索引
  1727. if (laterIndex <= preindex)//交换完成
  1728. return;
  1729. var sourceitem = PageEditListBox.Items[preindex] as ListBoxItem;
  1730. var targetitem = PageEditListBox.Items[laterIndex] as ListBoxItem;
  1731. bindPageList.Remove(sourceitem);
  1732. bindPageList.Remove(targetitem);
  1733. bindPageList.Insert(preindex, targetitem);
  1734. bindPageList.Insert(laterIndex, sourceitem);
  1735. pdfViewer.Document.ExchangePage(preindex, laterIndex);
  1736. pdfViewer.UndoManager.ClearHistory();
  1737. pdfViewer.UndoManager.CanSave = true;
  1738. PageEditListBox.SelectedItems.Add(targetitem);
  1739. PageEditListBox.SelectedItems.Add(sourceitem);
  1740. }
  1741. }
  1742. /// <summary>
  1743. /// 删除选中页面 bool 设置删除前是否弹窗提示
  1744. /// </summary>
  1745. /// <param name="tip">是否弹窗提示</param>
  1746. private void DoDelete(List<ListBoxItem> pageLists, bool tip)
  1747. {
  1748. if (pageLists.Count == 0)
  1749. {
  1750. ShowAlertWithTimeout(AlertType.EmptyPageAlert);
  1751. return;
  1752. }
  1753. if (pageLists.Count == PageEditListBox.Items.Count)
  1754. {
  1755. ShowAlertWithTimeout(AlertType.AllPageAlert);
  1756. return;
  1757. }
  1758. Winform.DialogResult result = Winform.DialogResult.OK;
  1759. if (tip)
  1760. {
  1761. result = Winform.MessageBox.Show(string.Format("Do you want to delete page {0}", GetPageParam()), "Delete", Winform.MessageBoxButtons.OKCancel, Winform.MessageBoxIcon.Warning);
  1762. }
  1763. if (result == Winform.DialogResult.OK || !tip)
  1764. {
  1765. List<int> pages = new List<int>();
  1766. for (int i = 0; i < pageLists.Count; i++)
  1767. {
  1768. var index = PageEditListBox.Items.IndexOf(pageLists[i]);
  1769. pages.Add(index);//存入页的index
  1770. }
  1771. pages.Sort();
  1772. if (pages.Count == 0) return;
  1773. for (int i = pages.Count - 1; i >= 0; i--)
  1774. {
  1775. bindPageList.RemoveAt(pages[i]);
  1776. }
  1777. //文档层操
  1778. var r = pdfViewer.Document.RemovePages(pages.ToArray());
  1779. if (!r)
  1780. {
  1781. return;
  1782. }
  1783. pdfViewer.UndoManager.ClearHistory();
  1784. pdfViewer.UndoManager.CanSave = true;
  1785. UpdateAllPageNum();
  1786. //需要刷新 不然最后一页会出现白板
  1787. // ItemsInViewHitTest();
  1788. pdfViewer.ReloadDocument();
  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. /// <summary>
  1801. /// 校验PageRange 输入是否合法,且可返回List<int> Pages 存放的索引值
  1802. /// </summary>
  1803. /// <param name="pageList">返回的页面集合</param>
  1804. /// <param name="pageRange">需要判断的文本</param>
  1805. /// <param name="count">页面总数</param>
  1806. /// <param name="enumerationSeparator">例 new char[] { ',' }</param>
  1807. /// <param name="rangeSeparator">例 new char[] { '-' }</param>
  1808. /// <param name="inittag"></param>
  1809. /// <returns></returns>
  1810. public static bool GetPagesInRange(ref List<int> pageList, string pageRange, int count, char[] enumerationSeparator, char[] rangeSeparator, bool inittag = false)
  1811. {
  1812. string[] rangeSplit = pageRange.Split(enumerationSeparator);//根据分隔符 拆分字符串
  1813. pageList.Clear();
  1814. foreach (string range in rangeSplit)
  1815. {
  1816. int starttag = 1;
  1817. if (inittag)
  1818. {
  1819. starttag = 0;
  1820. }
  1821. if (range.Contains("-"))//连续页
  1822. {
  1823. try
  1824. {
  1825. string[] limits = range.Split(rangeSeparator);//对子字符串再根据”-“ 拆分
  1826. if (limits.Length >= 2 && !string.IsNullOrWhiteSpace(limits[0]) && !string.IsNullOrWhiteSpace(limits[1]))
  1827. {
  1828. int start = int.Parse(limits[0]);
  1829. int end = int.Parse(limits[1]);
  1830. if ((start < starttag) || (end > count) || (start > end))
  1831. {
  1832. //throw new Exception(string.Format("Invalid page(s) in range {0} - {1}", start, end));
  1833. return false;
  1834. }
  1835. for (int i = start; i <= end; ++i)
  1836. {
  1837. if (pageList.Contains(i))
  1838. {
  1839. return false;
  1840. }
  1841. pageList.Add(i - 1);
  1842. }
  1843. continue;
  1844. }
  1845. }
  1846. catch (Exception ex)
  1847. {
  1848. return false;
  1849. }
  1850. }
  1851. int pageNr;
  1852. try
  1853. {
  1854. // Single page
  1855. pageNr = int.Parse(range);//单页
  1856. }
  1857. catch (Exception)//格式不正确时
  1858. {
  1859. return false;
  1860. }
  1861. if (pageNr < starttag || pageNr > count)
  1862. {
  1863. return false;
  1864. //throw new Exception(string.Format("Invalid page {0}", pageNr));
  1865. }
  1866. if (pageList.Contains(pageNr))
  1867. {
  1868. return false;
  1869. // throw new Exception(string.Format("Invalid page {0}", pageNr));
  1870. }
  1871. pageList.Add(pageNr - 1);
  1872. }
  1873. return true;
  1874. }
  1875. /// <summary>
  1876. /// 从其他pdf插入页面
  1877. /// </summary>
  1878. /// <param name="filepath">文件路径</param>
  1879. /// <param name="pagerange">页码范围</param>
  1880. /// <param name="insertindex">插入位置</param>
  1881. private void DoAddFromOtherPdf(string filepath, string pagerange, int insertindex, string password)
  1882. {
  1883. CPDFDocument doc = CPDFDocument.InitWithFilePath(filepath);
  1884. if(doc.IsLocked && password != string.Empty)
  1885. {
  1886. if(!doc.UnlockWithPassword(password))
  1887. {
  1888. return;
  1889. }
  1890. }
  1891. int pagecount = 0;
  1892. string insertRange = "";
  1893. if (pagerange == "AllPages")
  1894. {
  1895. pagecount = doc.PageCount;
  1896. insertRange = "1-" + pagecount;
  1897. }
  1898. else if (pagerange == "OddPages")
  1899. {
  1900. pagecount = (doc.PageCount + 1) / 2;
  1901. int[] page = new int[(doc.PageCount + 1) / 2];
  1902. for (int i = 0; i < page.Length; i++)
  1903. {
  1904. page[i] = i * 2 + 1;
  1905. }
  1906. insertRange = string.Join(",", page);
  1907. }
  1908. else if (pagerange == "EvenPages")
  1909. {
  1910. if (doc.PageCount == 1)
  1911. {
  1912. insertRange = "1";
  1913. pagecount = 1;
  1914. }
  1915. else
  1916. {
  1917. pagecount = doc.PageCount / 2;
  1918. int[] page = new int[doc.PageCount / 2];
  1919. for (int i = 0; i < page.Length; i++)
  1920. {
  1921. page[i] = i * 2 + 2;
  1922. }
  1923. insertRange = string.Join(",", page);
  1924. }
  1925. }
  1926. else
  1927. {
  1928. List<int> page = new List<int>();
  1929. GetPagesInRange(ref page, pagerange, doc.PageCount, new char[] { ',' }, new char[] { '-' });
  1930. insertRange = pagerange;
  1931. pagecount = page.Count;
  1932. }
  1933. //先文档操作,再更新UI
  1934. var result = pdfViewer.Document.ImportPagesAtIndex(doc, insertRange, insertindex);
  1935. if (!result)
  1936. {
  1937. return;
  1938. }
  1939. doc.Release();
  1940. //刷新UI
  1941. RefreshThumbnail();
  1942. PageEditListBox.SelectedItems.Clear();
  1943. for (int i = insertindex; i < insertindex + pagecount; i++)
  1944. {
  1945. PageEditListBox.SelectedItems.Add(PageEditListBox.Items[i] as ListBoxItem);
  1946. }
  1947. }
  1948. private string GetPageParam()
  1949. {
  1950. string pageParam = "";
  1951. List<int> pagesList = new List<int>();
  1952. for (int i = 0; i < PageEditListBox.SelectedItems.Count; i++)
  1953. {
  1954. var item = PageEditListBox.SelectedItems[i] as ListBoxItem;
  1955. var page = GetPageNumTextBlock(item);
  1956. if (page != null)
  1957. {
  1958. pagesList.Add(int.Parse(page.Text));
  1959. }
  1960. }
  1961. if (pagesList.Count != 0)
  1962. {
  1963. pagesList.Sort();//先对页码排序
  1964. for (int i = 0; i < pagesList.Count; i++)
  1965. {
  1966. if (i == 0)
  1967. {
  1968. pageParam += pagesList[0].ToString();
  1969. }
  1970. else
  1971. {
  1972. if (pagesList[i] == pagesList[i - 1] + 1)//页码连续
  1973. {
  1974. if (i >= 2)
  1975. {
  1976. if (pagesList[i - 1] != pagesList[i - 2] + 1)
  1977. pageParam += "-";
  1978. }
  1979. else
  1980. pageParam += "-";
  1981. if (i == pagesList.Count - 1)
  1982. {
  1983. pageParam += pagesList[i].ToString();
  1984. }
  1985. }
  1986. else//页码不连续时
  1987. {
  1988. if (i >= 2)
  1989. {
  1990. if (pagesList[i - 1] == pagesList[i - 2] + 1)
  1991. pageParam += pagesList[i - 1].ToString();
  1992. }
  1993. pageParam += "," + pagesList[i].ToString();
  1994. }
  1995. }
  1996. }
  1997. }
  1998. return pageParam;
  1999. }
  2000. /// <summary>
  2001. /// 返回指定路径的图标
  2002. /// </summary>
  2003. /// <param name="path"></param>
  2004. /// <returns></returns>
  2005. public static BitmapSource ToBitmapSource(string path)
  2006. {
  2007. System.Drawing.Icon ico = System.Drawing.Icon.ExtractAssociatedIcon(path);
  2008. System.Drawing.Bitmap bitmap = ico.ToBitmap();
  2009. BitmapSource returnSource;
  2010. try
  2011. {
  2012. returnSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(bitmap.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
  2013. }
  2014. catch
  2015. {
  2016. returnSource = null;
  2017. }
  2018. return returnSource;
  2019. }
  2020. //返回当前视图中的item 范围
  2021. private Tuple<int, int, int> GetRoughViewportRange(ListBox view, Size itemSize, Thickness itemMargin)
  2022. {
  2023. var scrollViewer = GetScrollHost(view);
  2024. if (pdfViewer == null || pdfViewer.Document == null || scrollViewer == null || scrollViewer.ActualHeight == 0 || scrollViewer.ActualWidth == 0)//视图展开
  2025. return new Tuple<int, int, int>(0, 0, 0);
  2026. try
  2027. {
  2028. var currentHeight = scrollViewer.ActualHeight - view.Padding.Top;
  2029. var currentWidth = scrollViewer.ActualWidth;
  2030. //计算当前窗口大小能显示的行数和列数
  2031. var columnCount = (int)(currentWidth / (itemSize.Width + itemMargin.Left));
  2032. var rowCount = (int)Math.Ceiling(currentHeight / (itemSize.Height + itemMargin.Bottom));
  2033. var preItemCount = (int)((scrollViewer.VerticalOffset / scrollViewer.ExtentHeight) * ((pdfViewer.Document.PageCount + columnCount - 1) / columnCount));//滑动百分比*行数 = 大概的垂直位置
  2034. preItemCount = preItemCount * columnCount;
  2035. var preEnd = (int)(((scrollViewer.VerticalOffset + scrollViewer.ActualHeight) / scrollViewer.ExtentHeight) * ((pdfViewer.Document.PageCount + columnCount - 1) / columnCount));
  2036. preEnd = preEnd * columnCount + columnCount - 1;
  2037. var middle = (int)Math.Ceiling(preItemCount + preEnd / 2d);
  2038. return new Tuple<int, int, int>(
  2039. Math.Max(preItemCount, 0),
  2040. Math.Min(view.Items.Count, preEnd),
  2041. middle);
  2042. }
  2043. catch (Exception ex)
  2044. {
  2045. }
  2046. return new Tuple<int, int, int>(0, 0, 0);
  2047. }
  2048. private void ShowAlertWithTimeout(AlertType alertType)
  2049. {
  2050. // Reset the status of the AlertBorder control.
  2051. AlertBorder.Visibility = Visibility.Visible;
  2052. AlertBorder.Opacity = 1.0;
  2053. // Check the alert type and set the text of the AlertTextBlock control accordingly.
  2054. if (alertType == AlertType.EmptyPageAlert)
  2055. {
  2056. AlertTextBlock.Text = "Please select at least one page.";
  2057. }
  2058. else if (alertType == AlertType.SinglePageALert)
  2059. {
  2060. AlertTextBlock.Text = "Please select above two pages.";
  2061. }
  2062. else if (alertType == AlertType.AllPageAlert)
  2063. {
  2064. AlertTextBlock.Text = "Please don't select all pages";
  2065. }
  2066. // Animate the opacity of the AlertBorder control to 0.0 over a period of 3 seconds.
  2067. DoubleAnimation animation = new DoubleAnimation();
  2068. animation.From = 1.0;
  2069. animation.To = 0.0;
  2070. animation.Duration = TimeSpan.FromSeconds(3);
  2071. // Start the animation.
  2072. AlertBorder.BeginAnimation(OpacityProperty, animation);
  2073. }
  2074. #endregion
  2075. private void UserControl_MouseEnter(object sender, MouseEventArgs e)
  2076. {
  2077. MidLane.Visibility = Visibility.Collapsed;
  2078. }
  2079. private void UserControl_SizeChanged(object sender, SizeChangedEventArgs e)
  2080. {
  2081. DoSelectItems();
  2082. ItemsInViewHitTest();//Scollchange, triggered on the first load, directly refreshes the interface and reduces the whiteboard display time
  2083. }
  2084. }
  2085. public class InsertEventClass : EventArgs
  2086. {
  2087. public InsertType InsertType = InsertType.BlankPages;
  2088. public string FilePath = string.Empty;
  2089. public double PageWidth = 210 * 2.54;
  2090. public double PageHeight = 297 * 2.54;
  2091. public string PageRange = "0";
  2092. public int InsertIndex = 0;
  2093. public string Password = string.Empty;
  2094. }
  2095. public enum InsertType
  2096. {
  2097. BlankPages,
  2098. CustomBlankPages,
  2099. FromOtherPDF
  2100. }
  2101. /// <summary>
  2102. /// The parameter class used for extraction
  2103. /// </summary>
  2104. public class ExtractEventClass : EventArgs
  2105. {
  2106. /// <summary>
  2107. /// 1- All pages 2 - Odd pages 3 - Even pages 4 - Custom ranges
  2108. /// </summary>
  2109. public int PageMode;
  2110. /// <summary>
  2111. /// PageMode = 1,2,3 PageParm = null;
  2112. /// </summary>
  2113. public List<int> PageParm;
  2114. /// <summary>
  2115. /// In custom mode, the text content is passed over
  2116. /// </summary>
  2117. public string PageName = "";
  2118. /// <summary>
  2119. /// Whether to split into a single file
  2120. /// </summary>
  2121. public bool ExtractToSingleFile;
  2122. /// <summary>
  2123. /// Delete the page after extraction
  2124. /// </summary>
  2125. public bool DeleteAfterExtract;
  2126. }
  2127. public enum AlertType
  2128. {
  2129. EmptyPageAlert,
  2130. SinglePageALert,
  2131. AllPageAlert,
  2132. }
  2133. }