CPDFPageEditControl.xaml.cs 89 KB

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