CPDFPageEditControl.xaml.cs 84 KB

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