1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799 |
- using ComPDFKit.PDFDocument;
- using ComPDFKit_Conversion.Converter;
- using ComPDFKitViewer.PdfViewer;
- using Dropbox.Api.Team;
- using Microsoft.Win32;
- using PDF_Master.CustomControl;
- using PDF_Master.EventAggregators;
- using PDF_Master.Helper;
- using PDF_Master.Model;
- using PDF_Master.Model.HomePageToolsDialogs;
- using PDF_Master.Model.PageEdit;
- using PDF_Master.Properties;
- using PDFReader_WPF.Helper;
- using Prism.Commands;
- using Prism.Events;
- using Prism.Mvvm;
- using Prism.Regions;
- using Prism.Services.Dialogs;
- using System;
- using System.Collections.Generic;
- using System.Collections.ObjectModel;
- using System.Diagnostics;
- using System.IO;
- using System.Linq;
- using System.Threading;
- using System.Threading.Tasks;
- using System.Windows;
- using System.Windows.Controls;
- using System.Windows.Input;
- using System.Windows.Media;
- using System.Windows.Media.Imaging;
- using WIA;
- using static PDF_Master.Model.Dialog.ToolsDialogs.SaftyDialogs.DeleteSafetySettintgsModel;
- namespace PDF_Master.ViewModels.PageEdit
- {
- public class PageEditContentViewModel : BindableBase, INavigationAware
- {
- #region 文案
- private string T_title;
- public string T_Title
- {
- get { return T_title; }
- set
- {
- SetProperty(ref T_title, value);
- }
- }
- private string T_rotateLeftToolTip;
- public string T_RotateLeftToolTip
- {
- get { return T_rotateLeftToolTip; }
- set
- {
- SetProperty(ref T_rotateLeftToolTip, value);
- }
- }
- private string T_rotateRightToolTip;
- public string T_RotateRightToolTip
- {
- get { return T_rotateRightToolTip; }
- set
- {
- SetProperty(ref T_rotateRightToolTip, value);
- }
- }
- private string T_deleteToolTip;
- public string T_DeleteToolTip
- {
- get { return T_deleteToolTip; }
- set
- {
- SetProperty(ref T_deleteToolTip, value);
- }
- }
- private string T_deleteLook = "";
- public string T_DeleteLook
- {
- get { return T_deleteLook; }
- set
- {
- SetProperty(ref T_deleteLook, value);
- }
- }
- private string t_Insert;
- public string T_Insert
- {
- get { return t_Insert; }
- set
- {
- SetProperty(ref t_Insert, value);
- }
- }
- private string t_InsertFile;
- public string T_InsertFile
- {
- get { return t_InsertFile; }
- set
- {
- SetProperty(ref t_InsertFile, value);
- }
- }
- private string t_InsertaBlankPage;
- public string T_InsertaBlankPage
- {
- get { return t_InsertaBlankPage; }
- set
- {
- SetProperty(ref t_InsertaBlankPage, value);
- }
- }
- private string t_InsertaCustomPage;
- public string T_InsertaCustomPage
- {
- get { return t_InsertaCustomPage; }
- set
- {
- SetProperty(ref t_InsertaCustomPage, value);
- }
- }
- private string t_Extract;
- public string T_Extract
- {
- get { return t_Extract; }
- set
- {
- SetProperty(ref t_Extract, value);
- }
- }
- private string t_Replace;
- public string T_Replace
- {
- get { return t_Replace; }
- set
- {
- SetProperty(ref t_Replace, value);
- }
- }
- private string t_Split;
- public string T_Split
- {
- get { return t_Split; }
- set
- {
- SetProperty(ref t_Split, value);
- }
- }
- private string t_InsertPage;
- public string T_InsertPage
- {
- get { return t_InsertPage; }
- set
- {
- SetProperty(ref t_InsertPage, value);
- }
- }
- private string t_Reverse;
- public string T_Reverse
- {
- get { return t_Reverse; }
- set
- {
- SetProperty(ref t_Reverse, value);
- }
- }
- private string t_ExtractPage;
- public string T_ExtractPage
- {
- get { return t_ExtractPage; }
- set
- {
- SetProperty(ref t_ExtractPage, value);
- }
- }
- private string t_ReplacePage;
- public string T_ReplacePage
- {
- get { return t_ReplacePage; }
- set
- {
- SetProperty(ref t_ReplacePage, value);
- }
- }
- private void InitString()
- {
- T_InsertFile = App.MainPageLoader.GetString("PageEdit_Insert");
- T_Insert = App.MainPageLoader.GetString("PageEdit_InsertFile");
- T_InsertaBlankPage = App.MainPageLoader.GetString("PageEdit_InsertaBlankPage");
- T_InsertaCustomPage = App.MainPageLoader.GetString("PageEdit_InsertaCustomPage");
- T_Extract = App.MainPageLoader.GetString("PageEdit_Extract");
- T_Replace = App.MainPageLoader.GetString("PageEdit_Replace");
- T_Split = App.MainPageLoader.GetString("PageEdit_Split");
- T_InsertPage = App.MainPageLoader.GetString("PageEdit_InsertPage");
- T_Reverse = App.MainPageLoader.GetString("PageEdit_Reverse");
- T_ExtractPage = App.MainPageLoader.GetString("PageEdit_ExtractPage");
- T_ReplacePage = App.MainPageLoader.GetString("PageEdit_ReplacePage");
- T_Title = App.MainPageLoader.GetString("Thumbnails_Title");
- T_DeleteToolTip = App.MainPageLoader.GetString("ToolTipsPageEdit_Delete");
- T_DeleteLook = App.MainPageLoader.GetString("T_DeleteLook");
- T_RotateRightToolTip = App.MainPageLoader.GetString("ToolTipsPageEdit_RotateRight");
- T_RotateLeftToolTip = App.MainPageLoader.GetString("ToolTipsPageEdit_RotateLeft");
- }
- #endregion 文案
- public CPDFViewer PDFViewer;
- public PageEditItem CurrentPageEditItem = null;
- public ViewContentViewModel viewContentViewModel;
- private IDialogService dialogs;
- private IEventAggregator eventor;
- /// <summary>
- /// 用于筛选多窗体时间的唯一识别码
- /// </summary>
- private string unicode = null;
- /// <summary>
- /// 项数据集合
- /// </summary>
- public ObservableCollection<PageEditItem> PageEditItems { get; set; }
- /// <summary>
- /// 页面范围的项集合
- /// </summary>
- public ObservableCollection<string> PageRangeItems { get; set; }
- #region 属性
- /// <summary>
- /// 判断是否是添加页面
- /// </summary>
- public bool IsAddPages { get; set; } = false;
- /// <summary>
- /// 增加两个变量,用于记录当前控件内已经刷新图片的索引值,用于显示页面尺寸大小时,先显示当前范围可见Item的页面尺寸
- /// </summary>
- private int startRefreshedIndex = 0;
- private int endRefreshedIndex = 0;
- /// <summary>
- /// 正在初始化(正在初始化过程中 不发布通知BOTA刷新的事件)
- /// </summary>
- public bool Initializing = false;
- /// <summary>
- /// 是否是第一次加载
- /// </summary>
- private bool isFirstLoad = true;
- /// <summary>
- /// 记录多选项中最后一项的索引
- /// </summary>
- public int maxSelectedIndex = -1;
- private Visibility showTip = Visibility.Collapsed;
- /// <summary>
- /// 是否显示渐隐提示
- /// </summary>
- public Visibility ShowTip
- {
- get { return showTip; }
- set
- {
- SetProperty(ref showTip, value);
- }
- }
- private Visibility isLoading = Visibility.Collapsed;
- /// <summary>
- /// 是否正在处理中
- /// </summary>
- public Visibility IsLoading
- {
- get { return isLoading; }
- set
- {
- SetProperty(ref isLoading, value);
- }
- }
- private int listSelecedIndex;
- /// <summary>
- /// 缩略图选中项的索引
- /// </summary>
- public int ListSelectedIndex
- {
- get { return listSelecedIndex; }
- set
- {
- SetProperty(ref listSelecedIndex, value);
- if (!IsSelectFormSelf && value >= 0)
- {
- //显示页面范围选择控件
- TxtPageInputVisibility = Visibility.Visible;
- TbPageRange = (ListSelectedIndex + 1).ToString();
- }
- }
- }
- /// <summary>
- ///右键不会选中页面, 不要跳转
- /// </summary>
- /// 判断是否是右键选择
- private bool isMouseRightButtonDown = false;
- public bool IsMouseRightButtonDown
- {
- get { return isMouseRightButtonDown; }
- set { SetProperty(ref isMouseRightButtonDown, value); }
- }
- /// <summary>
- /// 右键选择索引
- /// </summary>
- public int RightSelectedIndex = 0;
- /// <summary>
- /// 右键选择 集合
- /// </summary>
- public List<int> RightSelectedIndexs = new List<int>();
- /// <summary>
- /// 多选
- /// </summary>
- private bool isMultiSelected;
- /// <summary>
- /// 是否有多选 用于判断倒序和替换功能
- /// </summary>
- public bool IsMultiSelected
- {
- get { return isMultiSelected; }
- set
- {
- SetProperty(ref isMultiSelected, value);
- }
- }
- private int comboxSelectIndex;
- /// <summary>
- /// 下拉框选项集合
- /// </summary>
- public int ComboxSelectIndex
- {
- get { return comboxSelectIndex; }
- set
- {
- SetProperty(ref comboxSelectIndex, value);
- //隐藏tb页面范围显示控件
- TxtPageInputVisibility = Visibility.Collapsed;
- //选中指定的页面范围
- SuitPageRange(comboxSelectIndex);
- }
- }
- private Visibility tbPageRangeVisibility = Visibility.Visible;
- /// <summary>
- /// 页面范围的文本显示
- /// </summary>
- public Visibility TbPageRangeVisibility
- {
- get { return tbPageRangeVisibility; }
- set
- {
- SetProperty(ref tbPageRangeVisibility, value);
- if (value == Visibility.Visible)
- {
- comboxSelectIndex = -1;
- }
- }
- }
- private string tbPageRange;
- /// <summary>
- /// 页面范围显示的内容
- /// </summary>
- public string TbPageRange
- {
- get { return tbPageRange; }
- set
- {
- SetProperty(ref tbPageRange, value);
- }
- }
- private Visibility txtPageInputVisibility = Visibility.Collapsed;
- /// <summary>
- /// 页面自定义输入框的显示
- /// </summary>
- public Visibility TxtPageInputVisibility
- {
- get { return txtPageInputVisibility; }
- set
- {
- SetProperty(ref txtPageInputVisibility, value);
- }
- }
- /// <summary>
- /// 页面缩放状态,-1 为最小值,1为最大值
- /// </summary>
- private int zoomIndex = 0;
- public int ZoomIndex
- {
- get { return zoomIndex; }
- set
- {
- SetProperty(ref zoomIndex, value);
- }
- }
- private string toastText = App.MainPageLoader.GetString("PageEdit_Failed");
- /// <summary>
- /// Toast提示
- /// </summary>
- public string ToastText
- {
- get { return toastText; }
- set
- {
- SetProperty(ref toastText, value);
- }
- }
- private Visibility isBOTAThumb = Visibility.Collapsed;
- /// <summary>
- /// 是否是BOTA侧边栏的缩略图
- /// </summary>
- public Visibility IsBOTAThumb
- {
- get { return isBOTAThumb; }
- set
- {
- SetProperty(ref isBOTAThumb, value);
- }
- }
- private Visibility showedPageSize = Visibility.Collapsed;
- /// <summary>
- /// 显示页面尺寸
- /// </summary>
- public Visibility ShowedPageSize
- {
- get { return showedPageSize; }
- set
- {
- SetProperty(ref showedPageSize, value);
- //if (IsBOTAThumb != Visibility.Visible)
- //{
- // if (value == Visibility.Visible)
- // {
- // HidePageSize = Visibility.Collapsed;
- // }
- // else
- // {
- // HidePageSize = Visibility.Visible;
- // }
- //}
- }
- }
- private Visibility hidePageSize = Visibility.Collapsed;
- /// <summary>
- /// 隐藏页面尺寸
- /// </summary>
- public Visibility HidePageSize
- {
- get { return hidePageSize; }
- set
- {
- SetProperty(ref hidePageSize, value);
- }
- }
- private bool canPaste = false;
- /// <summary>
- /// 是否可以粘贴
- /// </summary>
- public bool CanPaste
- {
- get { return canPaste; }
- set
- {
- SetProperty(ref canPaste, value);
- }
- }
- /// <summary>
- /// 页面缩放的范围
- /// </summary>
- private List<Size> ItemSizes = new List<Size>() {
- new Size(104,142),
- new Size(208, 294),
- new Size(312,441)
- };
- //选中的页面集合
- private List<int> selectedPageList = new List<int>();
- /// <summary>
- /// 是否是下拉框选项改变引起的选项变更事件
- /// </summary>
- private bool IsSelectFormSelf = false;
- public bool IsShowPageSize = false;
- public string Txt = Properties.Resources.txtex;
- public string Word = Properties.Resources.wordex;
- public string Ppt = Properties.Resources.pptex;
- public string Excel = Properties.Resources.excelex;
- public string Html = Properties.Resources.htmlex;
- public string Image = Properties.Resources.imageex;
- public string Pdf = Properties.Resources.pdf;
- #endregion 属性
- #region 命令
- public DelegateCommand<object> SelectionChangedCommand { get; set; }
- /// <summary>
- /// 拦截键盘输入的事件
- /// </summary>
- public DelegateCommand<object> PreviewKeyDown { get; set; }
- /// <summary>
- /// 粘贴
- /// </summary>
- public DelegateCommand PasteCommand { get; set; }
- /// <summary>
- /// 复制
- /// </summary>
- public DelegateCommand CopyCommand { get; set; }
- /// <summary>
- /// 剪切
- /// </summary>
- public DelegateCommand CutCommand { get; set; }
- /// <summary>
- /// 替换文件
- /// </summary>
- public DelegateCommand ReplaceCommand { get; set; }
- /// <summary>
- /// 插入文件命令
- /// </summary>
- public DelegateCommand<object> InsertCommand { get; set; }
- /// <summary>
- /// 拆分文件
- /// </summary>
- public DelegateCommand SplitCommand { get; set; }
- /// <summary>
- /// 提取文件
- /// </summary>
- public DelegateCommand ExtractCommand { get; set; }
- /// <summary>
- /// 逆时针旋转
- /// </summary>
- public DelegateCommand LeftRotateCommand { get; set; }
- /// <summary>
- /// 顺时针旋转
- /// </summary>
- public DelegateCommand RightRotateCommand { get; set; }
- /// <summary>
- /// 删除
- /// </summary>
- public DelegateCommand DeleteCommand { get; set; }
- /// <summary>
- /// 倒序
- /// </summary>
- public DelegateCommand ReverseCommand { get; set; }
- /// <summary>
- /// 放大
- /// </summary>
- public DelegateCommand ZoomInCommand { get; set; }
- /// <summary>
- /// 缩小
- /// </summary>
- public DelegateCommand ZoomOutCommand { get; set; }
- /// <summary>
- /// 显示页面大小
- /// </summary>
- public DelegateCommand ShowPageSizeCommand { get; set; }
- public DelegateCommand ClearSelectedCommand { get; set; }
- /// <summary>
- /// 进入页面编辑
- /// </summary>
- public DelegateCommand EnterPageEditCommand { get; set; }
- #endregion 命令
- public PageEditContentViewModel(IDialogService dialogService, IEventAggregator eventAggregator)
- {
- //变量初始化
- dialogs = dialogService;
- eventor = eventAggregator;
- unicode = App.mainWindowViewModel.SelectedItem.Unicode;
- PageEditItems = new ObservableCollection<PageEditItem>();
- PageRangeItems = new ObservableCollection<string>();
- //绑定命令
- SelectionChangedCommand = new DelegateCommand<object>(SelectionChangedEvent);
- PreviewKeyDown = new DelegateCommand<object>(PreviewKeyDownEvent);
- SplitCommand = new DelegateCommand(SplitCommandEvent);
- InsertCommand = new DelegateCommand<object>(InsertCommandEvent);
- ReplaceCommand = new DelegateCommand(ReplaceCommandEvent, CanFileCommandExcute).ObservesProperty(() => IsMouseRightButtonDown);
- ExtractCommand = new DelegateCommand(ExtractCommandEvent, CanFileCommandExcute).ObservesProperty(() => IsMouseRightButtonDown);
- DeleteCommand = new DelegateCommand(DeleteCommandEvent, CanFileCommandExcute).ObservesProperty(() => IsMouseRightButtonDown);
- LeftRotateCommand = new DelegateCommand(LeftRotateCommandEvent, CanFileCommandExcute).ObservesProperty(() => IsMouseRightButtonDown);
- RightRotateCommand = new DelegateCommand(RightRotateCommandEvent, CanFileCommandExcute).ObservesProperty(() => IsMouseRightButtonDown);
- ReverseCommand = new DelegateCommand(ReverseCommandEvent, CanReverseFileCommandExcute).ObservesProperty(() => IsMultiSelected);
- ZoomInCommand = new DelegateCommand(ZoomInCommandEvent, CanZoomIn).ObservesProperty(() => ZoomIndex);
- ZoomOutCommand = new DelegateCommand(ZoomOutCommandEvent, CanZoomOut).ObservesProperty(() => ZoomIndex);
- ShowPageSizeCommand = new DelegateCommand(ShowPageSize);
- CopyCommand = new DelegateCommand(copy);
- PasteCommand = new DelegateCommand(() => { Paste(); }, CanPasteExcute).ObservesProperty(() => CanPaste);
- CutCommand = new DelegateCommand(cut);
- ClearSelectedCommand = new DelegateCommand(clearSelected);
- EnterPageEditCommand = new DelegateCommand(enterpageeditr);
- //订阅页面刷新事件
- eventAggregator.GetEvent<PageEditRefreshEvent>().Subscribe(OnPageEditRefreshEvent, e => e.Unicode == unicode);
- eventAggregator.GetEvent<ViewContentEvent>().Subscribe(ViewContentChangedEvent, e => e.Unicode == unicode);
- CacheFilePath.Instance.PropertyChanged += Instance_PropertyChanged;
- RefreshPageRangeItem();
- InitString();
- }
- #region 事件
- private void ViewContentChangedEvent(ViewContentEventArgs obj)
- {
- //只有在缩略图模式下响应刷新,进入页面编辑时 会刷新可见范围内图片,不需要响应这个事件
- if (IsBOTAThumb == Visibility.Visible)
- {
- PageEditItems[PDFViewer.CurrentIndex].IsGetImage = false;
- PageEditItems[PDFViewer.CurrentIndex].Size = PDFViewer.Document.GetPageSize(PDFViewer.CurrentIndex);
- RefreshItemImage(PDFViewer.CurrentIndex, PDFViewer.CurrentIndex);
- }
- }
- /// <summary>
- /// 进入页面编辑
- /// </summary>
- private void enterpageeditr()
- {
- viewContentViewModel.EnterPageEdit();
- }
- private void Instance_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
- {
- if (e.PropertyName == "CopyDoc")
- {
- if (CacheFilePath.Instance.CopyDoc != null)
- {
- CanPaste = true;
- }
- }
- }
- /// <summary>
- /// 替换功能的逻辑
- /// 实现效果是,先删除后插入
- /// 跨页多选后替换的位置是多选的第一页位置
- /// </summary>
- private async void ReplaceCommandEvent()
- {
- DataTrackingHelper.SetSendInformation(DataTrackingHelper.EventType.Purchase_PageEdit, DataTrackingHelper.EntryPathKeyType.SubTbr_PageEdit);
- DataTrackingHelper.AddFirstAndSecondaryPath(DataTrackingHelper.FirstPath.Reading, DataTrackingHelper.SecondaryPath.Replace);
- DataTrackingHelper.IsClearEntryPath = true;
- DataTrackingHelper.SendEvent(DataTrackingHelper.EventType.SubTbr_PageEdit, "SubTbr_Btn", "Btn_SubTbr_Replace");
- //支持插入格式:PDF、图片、Office格式文件
- string allfiles = Pdf + Txt + Word + Excel + Ppt + Image + Html;
- OpenFileDialog dialog = new OpenFileDialog();
- //dialog.Multiselect = false;
- //dialog.Filter = PDF_Master.Properties.Resources.OpenDialogFilter;
- dialog.Filter = string.Format($"Files({allfiles.Replace(";", ",")}|{allfiles})|" +
- $"PDF({Pdf})|{Pdf}|" +
- $"Microsoft Office Word({Word})|{Word}|" +
- $"Microsoft Office Excel({Excel})|{Excel}|" +
- $"Microsoft Office PowerPoint({Ppt})|{Ppt}|" +
- $"Txt({Txt})|{Txt}|" +
- $"Picture({Image})|{Image}|" +
- $"Html({Html})|{Html}"
- );
- List<int> indexList = new List<int>();
- for (int i = 0; i < PageEditItems.Count; i++)
- {
- if (PageEditItems[i].Selected)
- {
- indexList.Add(i);
- }
- }
- //因为虚拟化 可能获取不到所有选中项的页码 需要结合选中项的集合判断一下
- if (selectedPageList.Count > 0 && selectedPageList.Count > indexList.Count)
- {
- indexList = new List<int>();
- for (int j = 0; j < selectedPageList.Count; j++)
- {
- indexList.Add(selectedPageList[j] - 1);
- }
- }
- indexList.Sort();
- //全选页面 提示不能全选,230711不要提示
- //if (indexList.Count > 0 && indexList.Count == PDFViewer.Document.PageCount)
- //{
- // AlertsMessage alertsMessage = new AlertsMessage();
- // alertsMessage.ShowDialog("", App.MainPageLoader.GetString("PageEdit_DeleteAllPage"), App.ServiceLoader.GetString("Text_ok"));
- // return;
- //}
- if ((bool)dialog.ShowDialog())
- {
- //付费锁
- if (!ServiceHelper.IAPBeforeFunction())
- {
- return;
- }
- IsLoading = Visibility.Visible;
- await Task.Delay(200);
- int pageCount = PDFViewer.Document.PageCount;
- int insertIndex = listSelecedIndex;
- string fileName = GetInsertFromFile(dialog.FileName);
- #region 历史版本
- //从文件插入到指定位置
- //var result = await InsertFromFile(listSelecedIndex + 1, fileName);
- //if (result)
- //{
- // //插入成功后再删除原有页面
- // //2023-06-05 索引需要-1,因为上面的listSelecedIndex + 1,需要还原
- // //DoRemoveSelectedPages(new List<int>() { ListSelectedIndex - 1 });
- // DoRemoveSelectedPages(indexList);
- //}
- #endregion 历史版本
- //先记录索引(第一个选定页面)
- int index = ListSelectedIndex;
- if (IsMouseRightButtonDown)
- {
- index = RightSelectedIndex;
- if (IsMultiSelected)
- {
- indexList = RightSelectedIndexs;
- }
- else
- {
- indexList = new List<int> { index };
- }
- }
- //替换页面 先看文件是否加密,如果加密,先解密后,再替换
- //将文档验证是否为空,是否解密,置前,若为空直接退出
- bool isDiscryptied = GetDocumentIsDiscryptied(fileName, null, out CPDFDocument doc, out string password);
- if (isDiscryptied)
- {
- //先删除
- int flag = DoRemoveSelectedPages(indexList, false, true);
- if (flag == -1)
- {
- return;
- }
- if (PDFViewer.Document.PageCount == 0)
- {
- index = 0;
- }
- //再新增,避免索引串号的情况
- var result = await InsertFromFile(index, fileName, doc, password);
- if (result)
- {
- ReloadAfterOption(true, false, Tuple.Create(insertIndex - 1, insertIndex + pageCount));
- }
- }
- IsLoading = Visibility.Collapsed;
- }
- }
- /// <summary>
- /// 拆分功能的逻辑
- /// </summary>
- private void SplitCommandEvent()
- {
- DataTrackingHelper.SetSendInformation(DataTrackingHelper.EventType.Purchase_PageEdit, DataTrackingHelper.EntryPathKeyType.SubTbr_PageEdit);
- DataTrackingHelper.AddFirstAndSecondaryPath(DataTrackingHelper.FirstPath.Reading, DataTrackingHelper.SecondaryPath.Split);
- DataTrackingHelper.IsClearEntryPath = true;
- DataTrackingHelper.SendEvent(DataTrackingHelper.EventType.SubTbr_PageEdit, "SubTbr_Btn", "Btn_SubTbr_Split");
- DialogParameters valuePairs = new DialogParameters();
- valuePairs.Add(ParameterNames.PDFViewer, PDFViewer);
- valuePairs.Add(ParameterNames.PageEditSelectedIndex, ListSelectedIndex);
- valuePairs.Add(ParameterNames.PageEditSelectedItems, TbPageRange);
- dialogs.ShowDialog(DialogNames.SplitDialog, valuePairs, e =>
- {
- if (e.Result == ButtonResult.OK && e.Parameters != null)
- {
- //付费锁
- if (!ServiceHelper.IAPBeforeFunction())
- {
- return;
- }
- //保存并继续,使用了高级功能则弹窗权益弹窗
- if (!viewContentViewModel.saveFile(true))
- {
- return;
- }
- var model = e.Parameters.GetValue<HomePageSplitDialogModel>(ParameterNames.DataModel);
- DoSplitPages(model);
- }
- });
- }
- /// <summary>
- /// 提取功能的逻辑
- /// </summary>
- private void ExtractCommandEvent()
- {
- DataTrackingHelper.SetSendInformation(DataTrackingHelper.EventType.Purchase_PageEdit, DataTrackingHelper.EntryPathKeyType.SubTbr_PageEdit);
- DataTrackingHelper.AddFirstAndSecondaryPath(DataTrackingHelper.FirstPath.Reading, DataTrackingHelper.SecondaryPath.Extract);
- DataTrackingHelper.IsClearEntryPath = true;
- DataTrackingHelper.SendEvent(DataTrackingHelper.EventType.SubTbr_PageEdit, "SubTbr_Btn", "Btn_SubTbr_Extract");
- DialogParameters keyValuePairs = new DialogParameters();
- //因无法删除所有页面,若选中所有页面提取,则需要将「提取后删除页面」复选项置灰
- if (selectedPageList.Count == PageEditItems.Count)
- {
- keyValuePairs.Add(ParameterNames.IsDeleteAfterExtract, false);
- }
- else
- {
- keyValuePairs.Add(ParameterNames.IsDeleteAfterExtract, true);
- }
- dialogs.ShowDialog(DialogNames.ExtractDialog, keyValuePairs, e =>
- {
- if (e.Result == ButtonResult.OK && e.Parameters != null)
- {
- //付费锁
- if (!ServiceHelper.IAPBeforeFunction())
- {
- return;
- }
- //保存并继续,使用了高级功能则弹窗权益弹窗
- if (!viewContentViewModel.saveFile(true))
- {
- return;
- }
- var model = e.Parameters.GetValue<ExtractModel>(ParameterNames.DataModel);
- DoExtractPages(model.IsEveryPageToFile, model.IsDeleteAfterExtract);
- }
- });
- }
- /// <summary>
- /// 插入功能的逻辑
- /// </summary>
- private async void InsertCommandEvent(object type)
- {
- DataTrackingHelper.SetSendInformation(DataTrackingHelper.EventType.Purchase_PageEdit, DataTrackingHelper.EntryPathKeyType.SubTbr_PageEdit);
- DataTrackingHelper.AddFirstAndSecondaryPath(DataTrackingHelper.FirstPath.Reading, DataTrackingHelper.SecondaryPath.Insert);
- DataTrackingHelper.IsClearEntryPath = true;
- DataTrackingHelper.SendEvent(DataTrackingHelper.EventType.SubTbr_PageEdit, "SubTbr_Btn", "Btn_SubTbr_Insert");
- if ((string)type == null)
- {
- return;
- }
- int pageIndex = 0;
- if (IsMouseRightButtonDown)
- {
- pageIndex = RightSelectedIndex;
- }
- else
- {
- pageIndex = ListSelectedIndex;
- }
- //获取插入位置
- int insertIndex = 0;
- if (pageIndex < 0)
- {
- insertIndex = PageEditItems.Count;
- }
- else
- {
- insertIndex = pageIndex + 1;
- if (insertIndex >= PDFViewer.Document.PageCount)
- {
- insertIndex = PDFViewer.Document.PageCount;
- }
- if (isMultiSelected && maxSelectedIndex != -1)
- {
- insertIndex = maxSelectedIndex + 1;
- }
- }
- IsLoading = Visibility.Visible;
- await System.Threading.Tasks.Task.Delay(3);
- PageEditHistory history = new PageEditHistory();
- history.InsertIndex = insertIndex;
- #region 插入空白页面
- if ((string)type == ParameterNames.InsertType_Blank)
- {
- //付费锁
- if (!ServiceHelper.IAPBeforeFunction())
- {
- return;
- }
- history.Type = ActionType.InsertCustomPages;
- history.InsertFilePath = "";
- //插入空白页面
- bool result;
- if (insertIndex == 0)
- {
- result = PDFViewer.Document.InsertPage(insertIndex, PageEditItems[insertIndex].Size.Width, PageEditItems[insertIndex].Size.Height, null);
- history.PageSize = PageEditItems[insertIndex].Size;
- }
- else
- {
- result = PDFViewer.Document.InsertPage(insertIndex, PageEditItems[insertIndex - 1].Size.Width, PageEditItems[insertIndex - 1].Size.Height, null);
- history.PageSize = PageEditItems[insertIndex - 1].Size;
- }
- if (!result)
- {
- IsLoading = Visibility.Collapsed;
- ShowToast();
- return;
- }
- //UI层插入Item
- var item = GetNewPageEditItem(insertIndex);
- PageEditItems.Insert(insertIndex, item);
- //插入后 滚动到 选中的页面
- ReloadAfterOption(true, false, Tuple.Create(0, insertIndex + 1), true);
- await Task.Delay(10);
- //选中插入的页面
- ListSelectedIndex = insertIndex;
- }
- #endregion 插入空白页面
- #region 插入文件
- else if ((string)type == ParameterNames.InsertType_File)
- {
- //支持插入格式:PDF、图片、Office格式文件
- string allfiles = Pdf + Txt + Word + Excel + Ppt + Image + Html;
- OpenFileDialog dialog = new OpenFileDialog();
- dialog.Multiselect = false;
- dialog.Filter = string.Format($"Files({allfiles.Replace(";", ",")}|{allfiles})|" +
- $"PDF({Pdf})|{Pdf}|" +
- $"Microsoft Office Word({Word})|{Word}|" +
- $"Microsoft Office Excel({Excel})|{Excel}|" +
- $"Microsoft Office PowerPoint({Ppt})|{Ppt}|" +
- $"Txt({Txt})|{Txt}|" +
- $"Picture({Image})|{Image}|" +
- $"Html({Html})|{Html}"
- );
- //OpenFileDialog dialog = new OpenFileDialog();
- //dialog.Multiselect = false;
- //dialog.Filter = PDF_Master.Properties.Resources.OpenDialogFilter;
- if ((bool)dialog.ShowDialog())
- {
- //付费锁
- if (!ServiceHelper.IAPBeforeFunction())
- {
- return;
- }
- string fileName = GetInsertFromFile(dialog.FileName);
- //将文档验证是否为空,是否解密,置前,若为空直接退出
- bool IsLocked = GetDocumentIsDiscryptied(fileName, null, out CPDFDocument doc, out string password);
- if (IsLocked == false)
- {
- return;
- }
- //ToolMethod.SetFileThumbImg(fileName);
- //插入文件
- var result = await InsertFromFile(insertIndex, fileName, doc, password);
- if (!result)
- {
- IsLoading = Visibility.Collapsed;
- ShowToast();
- return;
- }
- ReloadAfterOption(true, false, Tuple.Create(0, PDFViewer.Document.PageCount));
- }
- IsLoading = Visibility.Collapsed;
- //里面附带了Undo栈记录,需要提前返回,避免重复记录
- return;
- }
- #endregion 插入文件
- #region 插入自定义页面
- else
- {
- DialogParameters keyValuePairs = new DialogParameters();
- Size size = new Size();
- size.Width = CommonHelper.GetUnitsFromPageSize(PDFViewer.Document.GetPageSize(listSelecedIndex).Width);
- size.Height = CommonHelper.GetUnitsFromPageSize(PDFViewer.Document.GetPageSize(listSelecedIndex).Height);
- keyValuePairs.Add(ParameterNames.CurrentPageSize, size);
- keyValuePairs.Add(ParameterNames.PageEditSelectedIndex, pageIndex);
- //int o = ListSelectedIndex;
- //插入自定义页面
- dialogs.ShowDialog(DialogNames.InsertDialog, keyValuePairs, e =>
- {
- if (e.Result == ButtonResult.OK && e.Parameters != null)
- {
- //付费锁
- if (!ServiceHelper.IAPBeforeFunction())
- {
- return;
- }
- var model = e.Parameters.GetValue<CustomInsertModel>(ParameterNames.DataModel);
- var result = InsertFromCustomPage(insertIndex, model.width, model.height, model.filepath);
- if (!result)
- {
- return;
- }
- history.Type = ActionType.InsertCustomPages;
- history.InsertFilePath = model.filepath;
- history.PageSize = new Size(model.width, model.height);
- }
- });
- }
- #endregion 插入自定义页面
- IsLoading = Visibility.Collapsed;
- //添加记录到Undo栈,清除Redo栈
- history.viewmodel = this;
- PDFViewer.UndoManager.AddHistory(history);
- }
- public string GetInsertFromFile(string file)
- {
- var fileType = System.IO.Path.GetExtension(file).ToLower();
- string fileName = string.Empty;
- if (Pdf.Contains(fileType))
- {
- fileName = file;
- }
- else if (Image.Contains(fileType))
- {
- fileName = GetImageFile(file);
- }
- else
- {
- fileName = GetOfficeFile(file);
- }
- if (string.IsNullOrEmpty(fileName))
- {
- AlertsMessage alertsMessage = new AlertsMessage();
- alertsMessage.ShowDialog("", App.MainPageLoader.GetString("ErrorFile_Warning"), App.ServiceLoader.GetString("Text_ok"));
- IsLoading = Visibility.Collapsed;
- return fileName;
- }
- if (File.Exists(fileName) == false)
- {
- AlertsMessage alertsMessage = new AlertsMessage();
- alertsMessage.ShowDialog("", App.MainPageLoader.GetString("ErrorFile_Warning"), App.ServiceLoader.GetString("Text_ok"));
- IsLoading = Visibility.Collapsed;
- return fileName;
- }
- return fileName;
- }
- private string GetOfficeFile(string sourcepath, Microsoft.Office.Interop.Word.WdPaperSize paperSize = Microsoft.Office.Interop.Word.WdPaperSize.wdPaperA4, double margin = 0)
- {
- try
- {
- string fileName = null;
- CPDFViewer pDFViewer = new CPDFViewer();
- pDFViewer.CreateDocument();
- string targetPath = "";
- targetPath = ConverterHelper.ConvertOfficeToPDF(sourcepath, paperSize, margin);
- if (pDFViewer.Document == null)
- {
- AlertsMessage alertsMessage = new AlertsMessage();
- alertsMessage.ShowDialog("", App.MainPageLoader.GetString("Create PDF failed"), App.ServiceLoader.GetString("Text_ok"));
- return null;
- }
- string file1 = sourcepath.Substring(sourcepath.LastIndexOf("\\") + 1, sourcepath.LastIndexOf(".") - sourcepath.LastIndexOf("\\") - 1) + ".pdf";
- var tempdoc = CPDFDocument.InitWithFilePath(targetPath);
- if (tempdoc == null)
- {
- AlertsMessage alertsMessage = new AlertsMessage();
- alertsMessage.ShowDialog("", App.MainPageLoader.GetString("Create PDF failed"), App.ServiceLoader.GetString("Text_ok"));
- return null;
- }
- pDFViewer.Document.ImportPages(tempdoc, "");
- string tempfile = CacheFilePath.Instance.CreatedFilePath;
- fileName = CommonHelper.CreateFilePath(Path.Combine(tempfile, App.UntitledFileNmae));
- pDFViewer.Document.WriteToFilePath(fileName);
- pDFViewer.CloseDocument();
- pDFViewer.InitDocument(fileName);
- return fileName;
- }
- catch
- {
- string str = "没有安装";
- //判断是否有安装office软件
- var officeType = Type.GetTypeFromProgID("Word.Application");
- if (officeType == null)
- {
- str += "Word;";
- }
- officeType = Type.GetTypeFromProgID("Excel.Application");
- if (officeType == null)
- {
- str += "Excel;";
- }
- officeType = Type.GetTypeFromProgID("Powerpoint.Application");
- if (officeType == null)
- {
- str += "Excel;";
- }
- AlertsMessage alertsMessage = new AlertsMessage();
- if (str != "没有安装")
- {
- alertsMessage.ShowDialog("", App.MainPageLoader.GetString("NoOffice_Warning"), App.ServiceLoader.GetString("Text_ok"));
- }
- else
- {
- alertsMessage.ShowDialog("", App.MainPageLoader.GetString("CreateFileFailedWarning"), App.ServiceLoader.GetString("Text_ok"));
- }
- return null;
- }
- }
- private string GetImageFile(string fileName)
- {
- CPDFViewer pDFViewer = new CPDFViewer();
- pDFViewer.CreateDocument();
- string path = fileName.Substring(fileName.LastIndexOf("\\") + 1, fileName.LastIndexOf(".") - fileName.LastIndexOf("\\") - 1) + ".pdf";
- System.Drawing.Bitmap pic = new System.Drawing.Bitmap(fileName);
- int width = pic.Size.Width;
- int height = pic.Size.Height;
- string ex = System.IO.Path.GetExtension(fileName);
- //其他格式或者名称中含空格的图片 在本地先转存一下
- if ((ex != ".jpg" && ex != ".jpeg") || !Uri.IsWellFormedUriString(fileName, UriKind.Absolute))
- {
- //将其他格式图片转换成jpg
- string folderPath = Path.GetTempPath();
- if (File.Exists(folderPath))
- {
- File.Delete(folderPath);
- }
- DirectoryInfo tempfolder = new DirectoryInfo(folderPath);
- if (!tempfolder.Exists)
- {
- tempfolder.Create();
- }
- string targetPath = System.IO.Path.Combine(folderPath, Guid.NewGuid().ToString());
- fileName = targetPath;
- pic.Save(targetPath, System.Drawing.Imaging.ImageFormat.Jpeg);
- }
- pic.Dispose();
- var result = pDFViewer.Document.InsertPage(0, width, height, fileName);
- if (!result)
- {
- AlertsMessage alertsMessage = new AlertsMessage();
- alertsMessage.ShowDialog("", App.MainPageLoader.GetString("Create PDF failed"), App.ServiceLoader.GetString("Text_ok"));
- return null;
- }
- string tempfile = CacheFilePath.Instance.CreatedFilePath;
- string file = CommonHelper.CreateFilePath(Path.Combine(tempfile, App.UntitledFileNmae));
- pDFViewer.Document.WriteToFilePath(file);
- pDFViewer.CloseDocument();
- pDFViewer.InitDocument(file);
- return file;
- }
- /// <summary>
- /// 删除选中页面
- /// </summary>
- private async void DeleteCommandEvent()
- {
- DataTrackingHelper.SetSendInformation(DataTrackingHelper.EventType.Purchase_PageEdit, DataTrackingHelper.EntryPathKeyType.SubTbr_PageEdit);
- DataTrackingHelper.AddFirstAndSecondaryPath(DataTrackingHelper.FirstPath.Reading, DataTrackingHelper.SecondaryPath.Delete);
- DataTrackingHelper.IsClearEntryPath = true;
- DataTrackingHelper.SendEvent(DataTrackingHelper.EventType.SubTbr_PageEdit, "SubTbr_Btn", "Btn_SubTbr_Delete");
- AlertsMessage alertsMessage = new AlertsMessage();
- alertsMessage.ShowDialog("", T_DeleteLook, App.ServiceLoader.GetString("Text_no"), App.ServiceLoader.GetString("Text_ok"));
- if (alertsMessage.result == ContentResult.Ok)
- {
- IsLoading = Visibility.Visible;
- await Task.Delay(3);
- int pageIndex = 0;
- int index = 0;
- if (IsMouseRightButtonDown)
- {
- int count = RightSelectedIndexs.Count;
- pageIndex = RightSelectedIndex;
- if (IsMultiSelected)
- {
- index = DoRemoveSelectedPages(RightSelectedIndexs);
- }
- else
- {
- index = DoRemoveSelectedPages(new List<int> { pageIndex });
- }
- }
- else
- {
- index = DoRemoveSelectedPages();
- }
- //删除后 选中项
- if (index != -1)
- {
- if (index <= PDFViewer.Document.PageCount)
- {
- index = index + 1;
- }
- }
- else
- {
- index = 0;
- }
- if (IsBOTAThumb == Visibility.Visible)
- {
- GoToPage(new List<int>() { index });
- }
- ReloadAfterOption(true, true, Tuple.Create(0, PDFViewer.Document.PageCount));
- //通知Xaml删除后 选中的页面,从VM设置选中项会有问题
- NotifyUIToRefresh(new List<int>() { index });
- IsLoading = Visibility.Collapsed;
- }
- }
- /// <summary>
- /// 左旋转页面的逻辑
- /// </summary>
- private void LeftRotateCommandEvent()
- {
- DataTrackingHelper.SetSendInformation(DataTrackingHelper.EventType.Purchase_PageEdit, DataTrackingHelper.EntryPathKeyType.SubTbr_PageEdit);
- DataTrackingHelper.AddFirstAndSecondaryPath(DataTrackingHelper.FirstPath.Reading, DataTrackingHelper.SecondaryPath.Rotate);
- DataTrackingHelper.IsClearEntryPath = true;
- DataTrackingHelper.SendEvent(DataTrackingHelper.EventType.SubTbr_PageEdit, "SubTbr_Btn", "Btn_SubTbr_Rotate");
- List<int> pageitems = new List<int>();
- if (IsMouseRightButtonDown)
- {
- if (IsMultiSelected)
- {
- pageitems.AddRange(RightSelectedIndexs);
- }
- else
- {
- pageitems.Add(RightSelectedIndex);
- }
- RotateSelectedPages(false, pageitems);
- }
- else
- {
- RotateSelectedPages(false);
- }
- }
- /// <summary>
- /// 右旋转页面的逻辑
- /// </summary>
- private void RightRotateCommandEvent()
- {
- DataTrackingHelper.SetSendInformation(DataTrackingHelper.EventType.Purchase_PageEdit, DataTrackingHelper.EntryPathKeyType.SubTbr_PageEdit);
- DataTrackingHelper.AddFirstAndSecondaryPath(DataTrackingHelper.FirstPath.Reading, DataTrackingHelper.SecondaryPath.Rotate);
- DataTrackingHelper.IsClearEntryPath = true;
- DataTrackingHelper.SendEvent(DataTrackingHelper.EventType.SubTbr_PageEdit, "SubTbr_Btn", "Btn_SubTbr_Rotate");
- List<int> pageitems = new List<int>();
- if (IsMouseRightButtonDown)
- {
- if (IsMultiSelected)
- {
- pageitems.AddRange(RightSelectedIndexs);
- }
- else
- {
- pageitems.Add(RightSelectedIndex);
- }
- RotateSelectedPages(true, pageitems);
- }
- else
- {
- RotateSelectedPages();
- }
- }
- /// <summary>
- /// 页面倒序的逻辑
- /// </summary>
- private async void ReverseCommandEvent()
- {
- DataTrackingHelper.SetSendInformation(DataTrackingHelper.EventType.Purchase_PageEdit, DataTrackingHelper.EntryPathKeyType.SubTbr_PageEdit);
- DataTrackingHelper.AddFirstAndSecondaryPath(DataTrackingHelper.FirstPath.Reading, DataTrackingHelper.SecondaryPath.Reverse);
- DataTrackingHelper.IsClearEntryPath = true;
- DataTrackingHelper.SendEvent(DataTrackingHelper.EventType.SubTbr_PageEdit, "SubTbr_Btn", "Btn_SubTbr_Reverse");
- IsLoading = Visibility.Visible;
- await Task.Delay(3);
- List<int> pages = new List<int>();
- for (int i = 0; i < PageEditItems.Count; i++)
- {
- if (PageEditItems[i].Selected)
- {
- pages.Add(i);
- }
- }
- DoReverse(pages);
- IsLoading = Visibility.Collapsed;
- }
- /// <summary>
- /// 将指定页面结合进行倒序
- /// </summary>
- private async void DoReverse(List<int> pages, bool isFromUndoRedo = false)
- {
- if (pages.Count <= 1)
- {
- ShowToast("请至少选择两个图片进行倒序操作。");
- return;
- }
- //付费锁
- if (!ServiceHelper.IAPBeforeFunction())
- {
- return;
- }
- pages.Sort();
- //记录原位置和目标位置 用于undo,redo
- Dictionary<int, int> sourceTarget = new Dictionary<int, int>();
- for (int i = 0; i < pages.Count; i++)
- {
- int preindex = pages[i];
- int laterIndex = pages[pages.Count - i - 1];//尾部的索引
- if (laterIndex <= preindex)//交换完成
- {
- //用于记录选中集合为奇数时,最中间Item的还原
- sourceTarget.Add(preindex, preindex);
- break;
- }
- var result = ExchangeItem(preindex, laterIndex);
- if (!result)
- {
- ShowToast();
- IsLoading = Visibility.Collapsed;
- return;
- }
- sourceTarget.Add(preindex, laterIndex);
- }
- await Task.Delay(20);
- //转换成页码数据集合,传递给UI,选中目标页面
- //因虚拟化加载的问题,通过Selected来控制Item选中效果会有问题
- List<int> pageRange = new List<int>();
- for (int i = 0; i < pages.Count; i++)
- {
- pageRange.Add(pages[i] + 1);
- }
- NotifyUIToRefresh(pageRange);
- ReloadAfterOption(true, false, null);
- if (!isFromUndoRedo)
- {
- PageEditHistory history = new PageEditHistory();
- history.Type = ActionType.Reverse;
- history.SourceTargetValue = sourceTarget;
- history.viewmodel = this;
- PDFViewer.UndoManager.AddHistory(history);
- }
- }
- /// <summary>
- /// 交换两个Item顺序
- /// </summary>
- /// <param name="preiIndex"></param>
- /// <param name="laterIndex"></param>
- /// <returns></returns>
- private bool ExchangeItem(int preiIndex, int laterIndex)
- {
- if (preiIndex == laterIndex)
- {
- return true;
- }
- var sourceitem = PageEditItems[preiIndex];
- var targetitem = PageEditItems[laterIndex];
- var result = PDFViewer.Document.ExchangePage(preiIndex, laterIndex);
- if (!result)
- {
- return false;
- }
- PageEditItems.Remove(sourceitem);
- PageEditItems.Remove(targetitem);
- PageEditItems.Insert(preiIndex, targetitem);
- PageEditItems.Insert(laterIndex, sourceitem);
- return true;
- }
- /// <summary>
- /// 是否可以执行文件操作命令 除插入、拆分外
- /// </summary>
- /// <returns></returns>
- private bool CanFileCommandExcute()
- {
- //增加是否有选中多页的判断
- //修复问题:全选页面后,ctrl取消第一页的选中时,其余操作会因为ListSelectedIndex为-1被禁用的问题
- if (IsMouseRightButtonDown)
- {
- if (RightSelectedIndex < 0 && !IsMultiSelected)
- {
- return false;
- }
- else
- {
- return true;
- }
- }
- else
- {
- if (ListSelectedIndex < 0 && !IsMultiSelected)
- {
- return false;
- }
- else
- {
- return true;
- }
- }
- }
- private bool CanReverseFileCommandExcute()
- {
- if (IsMouseRightButtonDown)
- {
- if (RightSelectedIndex >= 0 && IsMultiSelected)
- {
- return true;
- }
- else
- {
- return false;
- }
- }
- else
- {
- if (ListSelectedIndex >= 0 && IsMultiSelected)
- {
- return true;
- }
- else
- {
- return false;
- }
- }
- }
- /// <summary>
- /// 校验是否可以替换
- /// </summary>
- /// <returns></returns>
- private bool CanReplaceCommandExcute()
- {
- //return !IsMultiSelected;
- return true;
- }
- /// <summary>
- /// 放大页面
- /// </summary>
- private void ZoomInCommandEvent()
- {
- ZoomIndex++;
- ChangeItemSize(ItemSizes[ZoomIndex + 1]);
- NotifyUIToRefresh();
- }
- /// <summary>
- /// 缩小页面
- /// </summary>
- private async void ZoomOutCommandEvent()
- {
- ZoomIndex--;
- ChangeItemSize(ItemSizes[ZoomIndex + 1]);
- //增加一定延时,计算页面显示范围时,用新的尺寸进行计算
- await Task.Delay(3);
- NotifyUIToRefresh();
- }
- /// <summary>
- ///
- /// </summary>
- /// <param name="newsize"></param>
- public void ChangeItemSize(Size newsize)
- {
- for (int i = 0; i < PageEditItems.Count; i++)
- {
- PageEditItems[i].ItemSize = newsize;
- }
- RefreshPageNum();
- List<int> indexList = GetSelectedItemPageNumbers();
- if (indexList.Count > 0)
- {
- //选中项集合 也需要 同步更新
- selectedPageList.Clear();
- selectedPageList.AddRange(indexList);
- }
- if (selectedPageList.Count > 0)
- {
- //缩略图模式 调整item大小的时候,更新选中项
- //如果注释掉,调整BOTA宽度后,缩略图视图中不会显示选中项
- if (selectedPageList.Count < 1)
- {
- NotifyUIToRefresh(new List<int>() { PDFViewer.CurrentIndex + 1 });
- }
- else
- {
- NotifyUIToRefresh(selectedPageList);
- }
- }
- }
- private bool CanZoomIn()
- {
- if (ZoomIndex >= 1)
- {
- return false;
- }
- else
- {
- return true;
- }
- }
- private bool CanZoomOut()
- {
- if (ZoomIndex <= -1)
- {
- return false;
- }
- else
- {
- return true;
- }
- }
- /// <summary>
- /// 响应UI发送刷新图片的事件
- /// </summary>
- /// <param name="e"></param>
- private void OnPageEditRefreshEvent(PageEditRefreshEventArgs e)
- {
- //UI发送事件过来通知刷新图片时
- //调整逻辑,前后预加载5页
- RefreshItemImage(e.PageRange.Item1 - 2, e.PageRange.Item2 + 2);
- }
- /// <summary>
- /// 选项改变事件
- /// 虚拟化的时候不会触发选中事件
- /// </summary>
- /// <param name="e"></param>
- private void SelectionChangedEvent(object e)
- {
- if (IsSelectFormSelf)
- {
- //避免频繁的触发该事件
- return;
- }
- var args = e as SelectionChangedEventArgs;
- //下下策 从UI控件获取所有选项的集合
- var listbox = args.OriginalSource as ListBox;
- if (args != null)
- {
- selectedPageList = new List<int>();
- for (int i = 0; i < listbox.SelectedItems.Count; i++)
- {
- if (!selectedPageList.Contains((listbox.SelectedItems[i] as PageEditItem).PageNumber))
- {
- selectedPageList.Add((listbox.SelectedItems[i] as PageEditItem).PageNumber);
- }
- }
- ////根据选中的范围 适配全部页面范围、奇数页面范围等
- //if (pagelist.Count == PageEditItems.Count)
- //{
- // ComboxSelectIndex = 0;
- // return;
- //}
- //只选中单个页面是,listselectedIndex 更准确
- if (selectedPageList.Count == 1)
- {
- TbPageRange = (listSelecedIndex + 1).ToString();
- //缩放 平移移动页面,页面大小出现不全的问题
- listbox.ScrollIntoView(listbox.SelectedItems[0]);
- //需要刷新 startRefreshIndex 、endRefreshedIndex
- //这个方法 会有串联地方,然后不起作用
- //NotifyUIToRefresh();
- //保险起见,暂时只能用这个方法
- if (listbox != null)
- {
- var itemSize = new Size((listbox.Items[0] as PageEditItem).ItemSize.Width + 32, (listbox.Items[0] as PageEditItem).ItemSize.Height + 30);
- Tuple<int, int, int> range = (Tuple<int, int, int>)GetRoughFromView(listbox, itemSize, new Thickness(5, 10, 5, 10));
- //RefreshItemImage(range.Item1, range.Item2);
- startRefreshedIndex = range.Item1;
- endRefreshedIndex = range.Item2;
- }
- }
- else
- {
- //根据选中的页面转换成1,3-10类似的字符串
- string pageparm = CommonHelper.GetPageParmFromList(selectedPageList);
- TbPageRange = pageparm;
- }
- }
- //Ctrl+A时让所有item选中
- var isCtrlorShiftDown = ((Keyboard.IsKeyDown(Key.LeftCtrl) && Keyboard.IsKeyDown(Key.A)) || (Keyboard.IsKeyDown(Key.RightCtrl) && Keyboard.IsKeyDown(Key.A)));
- if (isCtrlorShiftDown)
- {
- for (int i = 0; i < PageEditItems.Count; i++)
- {
- PageEditItems[i].Selected = true;
- }
- }
- //判断是否有选中多项
- if (listbox.SelectedItems.Count > 1)
- {
- IsMultiSelected = true;
- maxSelectedIndex = listbox.Items.IndexOf(listbox.SelectedItems[listbox.SelectedItems.Count - 1]);
- }
- else
- {
- IsMultiSelected = false;
- //非多选的时候需要重置多选页码的标志符
- //否则会有多选页面复制后,粘贴位置不准确的问题
- maxSelectedIndex = -1;
- }
- }
- private object GetRoughFromView(ListBox view, Size itemSize, Thickness itemMargin)
- {
- var scrollViewer = CommonHelper.FindVisualChild<ScrollViewer>(view);
- if (scrollViewer == null || scrollViewer.ActualHeight == 0 || scrollViewer.ActualWidth == 0)//视图展开
- return new Tuple<int, int, int>(0, 0, 0);
- try
- {
- var currentHeight = scrollViewer.ActualHeight - view.Padding.Top;
- var currentWidth = scrollViewer.ActualWidth;
- //计算当前窗口大小能显示的行数和列数
- var columnCount = (int)(currentWidth / (itemSize.Width + itemMargin.Left));
- var rowCount = (int)Math.Ceiling(currentHeight / (itemSize.Height + itemMargin.Bottom));
- var preItemCount = (int)((scrollViewer.VerticalOffset / scrollViewer.ExtentHeight) * ((view.Items.Count + columnCount - 1) / columnCount));//滑动百分比*行数 = 大概的垂直位置
- preItemCount = preItemCount * columnCount;
- var preEnd = (int)(((scrollViewer.VerticalOffset + scrollViewer.ActualHeight) / scrollViewer.ExtentHeight) * ((view.Items.Count + columnCount - 1) / columnCount));
- preEnd = preEnd * columnCount + columnCount - 1;
- var middle = (int)Math.Ceiling(preItemCount + preEnd / 2d);
- return new Tuple<int, int, int>(
- Math.Max(preItemCount, 0),
- Math.Min(view.Items.Count, preEnd),
- middle);
- }
- catch { }
- return new Tuple<int, int, int>(0, 0, 0);
- }
- /// <summary>
- /// 限制文本框输入内容
- /// </summary>
- /// <param name="e"></param>
- private void PreviewKeyDownEvent(object e)
- {
- var args = e as KeyEventArgs;
- if (args == null)
- {
- return;
- }
- ////枚举 过滤所有不合理的输入
- //if (args.Key != Key.Enter && args.Key != Key.Back && args.Key != Key.OemComma && args.Key != Key.OemMinus && args.Key != Key.Subtract && !((args.Key >= Key.D0 && args.Key <= Key.D9) || (args.Key >= Key.NumPad0 && args.Key <= Key.NumPad9)))
- //{
- // args.Handled = true;
- //}
- if (args.Key == Key.Enter)
- {
- if (PageRangeItems.Contains((args.OriginalSource as TextBox).Text))
- {
- return;
- }
- List<int> TargetPageIndexs = new List<int>();
- var result = CommonHelper.GetPagesInRange(ref TargetPageIndexs, (args.OriginalSource as TextBox).Text, PDFViewer.Document.PageCount, new char[] { ',', ',' }, new char[] { '-' });
- if (!result)
- {
- ListSelectedIndex = -1;
- TbPageRange = string.Empty;
- AlertsMessage alertsMessage = new AlertsMessage();
- alertsMessage.ShowDialog("", App.MainPageLoader.GetString("PageRangeWarning"), App.ServiceLoader.GetString("Text_ok"));
- return;
- }
- //选中输入的页面范围
- List<int> pageRange = new List<int>();
- for (int i = 0; i < PageEditItems.Count; i++)
- {
- if (TargetPageIndexs.Contains(PageEditItems[i].PageNumber - 1))
- {
- pageRange.Add(i + 1);
- }
- }
- NotifyUIToRefresh(pageRange);
- }
- }
- /// <summary>
- /// 失去焦点后选中页面
- /// </summary>
- /// <param name="obj"></param>
- public void lostfocus(object obj)
- {
- var args = obj as RoutedEventArgs;
- if (args == null || (args.OriginalSource as TextBox) == null)
- {
- return;
- }
- List<int> TargetPageIndexs = new List<int>();
- if (PageRangeItems.Contains((args.OriginalSource as TextBox).Text) && ComboxSelectIndex != 5)
- {
- //选中其他项,失去焦点时不报错
- return;
- }
- var result = CommonHelper.GetPagesInRange(ref TargetPageIndexs, (args.OriginalSource as TextBox).Text, PDFViewer.Document.PageCount, new char[] { ',', ',' }, new char[] { '-' });
- if (!result)
- {
- ListSelectedIndex = -1;
- TbPageRange = string.Empty;
- AlertsMessage alertsMessage = new AlertsMessage();
- alertsMessage.ShowDialog("", App.MainPageLoader.GetString("PageRangeWarning"), App.ServiceLoader.GetString("Text_ok"));
- return;
- }
- //选中输入的页面范围
- List<int> pageRange = new List<int>();
- for (int i = 0; i < PageEditItems.Count; i++)
- {
- if (TargetPageIndexs.Contains(PageEditItems[i].PageNumber - 1))
- {
- pageRange.Add(i + 1);
- }
- }
- NotifyUIToRefresh(pageRange);
- }
- #endregion 事件
- #region 方法
- /// <summary>
- /// Esc退出多选
- /// </summary>
- private void clearSelected()
- {
- //缩略图不支持esc取消选中;
- if (IsBOTAThumb == Visibility.Visible)
- {
- return;
- }
- else
- {
- ListSelectedIndex = -1;
- }
- }
- /// <summary>
- /// 调用打印机
- /// </summary>
- public async void print(List<int> SelectedPages)
- {
- //保存并继续,使用了高级功能则弹窗权益弹窗
- if (!viewContentViewModel.saveFile(true))
- {
- return;
- }
- if (ListSelectedIndex != -1)
- {
- await App.Current.Dispatcher.InvokeAsync(() =>
- {
- PDFViewer.GoToPage(ListSelectedIndex);
- });
- }
- DialogParameters printValue = new DialogParameters();
- printValue.Add(ParameterNames.PDFViewer, PDFViewer);
- printValue.Add(ParameterNames.FilePath, PDFViewer.Document.FileName);
- printValue.Add(ParameterNames.PrintCurrentPage, PDFViewer.CurrentIndex);
- printValue.Add(ParameterNames.PageList, SelectedPages);
- dialogs.ShowDialog(DialogNames.HomePagePrinterDialog, printValue, e => { });
- }
- /// <summary>
- /// 剪切
- /// </summary>
- private void cut()
- {
- //没有权限时,拦截剪切操作
- if (!viewContentViewModel.CheckPermissionBeforeOption())
- {
- return;
- }
- CacheFilePath.Instance.CopyDoc = null;
- CacheFilePath.Instance.CopyDoc = CPDFDocument.CreateDocument();
- List<int> pages = new List<int>();
- for (int i = 0; i < PageEditItems.Count; i++)
- {
- if (PageEditItems[i].Selected)
- {
- pages.Add(i + 1);
- }
- }
- bool result = CacheFilePath.Instance.CopyDoc.ImportPages(PDFViewer.Document, String.Join(",", pages));
- if (!result)
- {
- ShowToast();
- return;
- }
- List<int> pageitems = new List<int>();
- if (IsMouseRightButtonDown)
- {
- if (IsMultiSelected)
- {
- pageitems.AddRange(RightSelectedIndexs);
- }
- else
- {
- pageitems.Add(RightSelectedIndex);
- }
- DoRemoveSelectedPages(pageitems);
- }
- else
- {
- DoRemoveSelectedPages();
- }
- ReloadAfterOption(true, true, Tuple.Create(0, PDFViewer.Document.PageCount));
- }
- /// <summary>
- /// 复制
- /// </summary>
- private void copy()
- {
- DataTrackingHelper.SetSendInformation(DataTrackingHelper.EventType.Purchase_PageEdit, DataTrackingHelper.EntryPathKeyType.SubTbr_PageEdit);
- DataTrackingHelper.AddFirstAndSecondaryPath(DataTrackingHelper.FirstPath.Reading, DataTrackingHelper.SecondaryPath.Copy);
- DataTrackingHelper.IsClearEntryPath = true;
- DataTrackingHelper.SendEvent(DataTrackingHelper.EventType.SubTbr_PageEdit, "SubTbr_Btn", "Btn_SubTbr_Copy");
- if (!ServiceHelper.IAPBeforeFunction())
- {
- return;
- }
- if (viewContentViewModel.CheckPermissionBeforeOption())
- {
- int pageIndex = 0;
- if (IsMouseRightButtonDown)
- {
- pageIndex = RightSelectedIndex;
- }
- else
- {
- pageIndex = ListSelectedIndex;
- }
- CacheFilePath.Instance.CopyDoc?.Release();
- CacheFilePath.Instance.CopyDoc = CPDFDocument.CreateDocument();
- List<int> pages = new List<int>();
- if (isMultiSelected)
- {
- //确认是多选了页面时,通过页面的选中状态获取选中页面
- for (int i = 0; i < PageEditItems.Count; i++)
- {
- if (PageEditItems[i].Selected)
- {
- pages.Add(i + 1);
- }
- }
- }
- else
- {
- //没有多选时,根据listbox的选中索引获取选中页面
- pages.Add(pageIndex + 1);
- }
- bool result = CacheFilePath.Instance.CopyDoc.ImportPages(PDFViewer.Document, String.Join(",", pages));
- if (!result)
- {
- ShowToast();
- return;
- }
- }
- }
- /// <summary>
- /// 是否可以粘贴
- /// </summary>
- /// <returns></returns>
- private bool CanPasteExcute()
- {
- return this.CanPaste;
- }
- /// <summary>
- /// 粘贴
- /// </summary>
- private void Paste(int Index = -1)
- {
- if (!ServiceHelper.IAPBeforeFunction())
- {
- return;
- }
- int pageIndex = 0;
- if (IsMouseRightButtonDown)
- {
- pageIndex = RightSelectedIndex;
- }
- else
- {
- pageIndex = ListSelectedIndex;
- }
- IsLoading = Visibility.Visible;
- int insertindex = maxSelectedIndex > pageIndex ? maxSelectedIndex : pageIndex;
- insertindex++;
- if (Index >= 0)
- {
- insertindex = Index;
- }
- else if (pageIndex == -1)
- {
- insertindex = PageEditItems.Count;
- }
- if (CacheFilePath.Instance.CopyDoc == null)
- {
- return;
- }
- int pagecount = CacheFilePath.Instance.CopyDoc.PageCount;
- bool result = PDFViewer.Document.ImportPagesAtIndex(CacheFilePath.Instance.CopyDoc, "1-" + pagecount, insertindex);
- if (!result)
- {
- IsLoading = Visibility.Collapsed;
- ShowToast();
- return;
- }
- //UI层插入
- for (int i = 0; i < pagecount; i++)
- {
- var item = GetNewPageEditItem(i);
- PageEditItems.Insert(insertindex + i, item);
- }
- //加一点延时才能显示选中效果-2023.4.12,为解决卡顿问题,注释掉,注释掉未出现该选中问题
- //await Task.Delay(200);
- List<int> pageRange = new List<int>();
- for (int i = 0; i < pagecount; i++)
- {
- pageRange.Add(insertindex + i + 1);
- }
- PageEditHistory history = new PageEditHistory();
- history.InsertIndex = insertindex;
- history.InsertPageCount = pagecount;
- history.Type = ActionType.Paste;
- history.viewmodel = this;
- PDFViewer.UndoManager.AddHistory(history);
- if (IsBOTAThumb == Visibility.Visible)
- {
- GoToPage(pageRange);
- }
- //刷新页码等
- ReloadAfterOption(true, false, new Tuple<int, int>(0, PDFViewer.Document.PageCount));
- //通知Xaml选中新增的页面,从VM设置选中项会有问题
- NotifyUIToRefresh(pageRange);
- IsLoading = Visibility.Collapsed;
- IsAddPages = true;
- }
- public void GoToPage(List<int> pageRange)
- {
- int index = pageRange.Last() - 1;
- //跳转页面 需要写在ReloadAfterOption()之前,不然跳转失败的概率大
- //插入页面需要重新加载 ,不然会有bug(bug:选中最后 一页,粘贴,跳转失败)
- PDFViewer.ReloadDocument();
- //await Task.Delay(500);
- PDFViewer.GoToPage(index);
- }
- /// <summary>
- /// 页面编辑执行Undo操作的方法
- /// </summary>
- public async void Undo(PageEditHistory history)
- {
- switch (history.Type)
- {
- case ActionType.RightRotate:
- var rightlist = history.SourceTargetValue.Keys.ToList<int>();
- RotateSelectedPages(false, rightlist, true);
- break;
- case ActionType.LeftRotate:
- var leftlist = history.SourceTargetValue.Keys.ToList<int>();
- RotateSelectedPages(true, leftlist, true);
- break;
- case ActionType.InsertFromFile:
- case ActionType.Paste:
- List<int> pageList = new List<int>();
- for (int i = 0; i < history.InsertPageCount; i++)
- {
- pageList.Add(history.InsertIndex + i);
- }
- int index = DoRemoveSelectedPages(pageList, true);
- UndoPageOperations(index);
- break;
- case ActionType.InsertCustomPages:
- index = DoRemoveSelectedPages(new List<int> { history.InsertIndex }, true);
- UndoPageOperations(index);
- break;
- case ActionType.DragSort:
- //将字典倒序后,将每个Source的值恢复到Key的位置
- var SourceTargets = history.SourceTargetValue;
- var keys = SourceTargets.Keys.ToArray();
- Array.Reverse(keys);
- foreach (var key in keys)
- {
- MoveItemToIndex(SourceTargets[key], key);
- }
- //刷新页码等
- ReloadAfterOption(true, false, new Tuple<int, int>(0, PDFViewer.Document.PageCount));
- List<int> selectedPages = new List<int>();
- //将索引集合转换成页码集合
- foreach (var key in SourceTargets.Keys)
- {
- selectedPages.Add(key + 1);
- }
- //通知UI选中Item
- NotifyUIToRefresh(selectedPages);
- break;
- case ActionType.Reverse:
- //将字典倒序后,将每个Source的值恢复到Key的位置
- var SourceTarget = history.SourceTargetValue;
- var pres = SourceTarget.Keys.ToArray();
- foreach (var key in pres)
- {
- if (key != SourceTarget[key])
- {
- ExchangeItem(key, SourceTarget[key]);
- }
- }
- await Task.Delay(20);
- //刷新页码等
- ReloadAfterOption(true, false, null);
- List<int> Pages = new List<int>();
- //将索引集合转换成页码集合
- foreach (var key in SourceTarget.Keys)
- {
- Pages.Add(key + 1);
- }
- foreach (var key in SourceTarget.Values)
- {
- Pages.Add(key + 1);
- }
- //通知UI选中Item
- NotifyUIToRefresh(Pages);
- break;
- default:
- break;
- }
- }
- private void UndoPageOperations(int index)
- {
- //【页面编辑】插入页面后,undo,页码更新
- ReloadAfterOption(true, false, new Tuple<int, int>(0, PDFViewer.Document.PageCount));
- //删除后 选中项
- if (index != -1)
- {
- if (index <= PDFViewer.Document.PageCount)
- {
- index = index + 1;
- }
- }
- else
- {
- index = 0;
- }
- //通知Xaml删除后 选中的页面,从VM设置选中项会有问题
- NotifyUIToRefresh(new List<int>() { index });
- }
- /// <summary>
- /// 页面编辑执行Redo操作的方法
- /// </summary>
- public async void Redo(PageEditHistory history)
- {
- switch (history.Type)
- {
- case ActionType.RightRotate:
- var rightlist = history.SourceTargetValue.Keys.ToList<int>();
- RotateSelectedPages(true, rightlist, true);
- break;
- case ActionType.LeftRotate:
- var leftlist = history.SourceTargetValue.Keys.ToList<int>();
- RotateSelectedPages(false, leftlist, true);
- break;
- case ActionType.InsertFromFile:
- //将文档验证是否为空,是否解密,置前,若为空直接退出
- bool IsLocked = GetDocumentIsDiscryptied(history.InsertFilePath, history.InsertFilePassWord, out CPDFDocument doc, out string password);
- if (IsLocked == false)
- {
- return;
- }
- await InsertFromFile(history.InsertIndex, history.InsertFilePath, doc, history.InsertFilePassWord, true);
- ReloadAfterOption(true, false, Tuple.Create(history.InsertIndex - 1, history.InsertIndex + history.InsertPageCount));
- break;
- case ActionType.InsertCustomPages:
- InsertFromCustomPage(history.InsertIndex, history.PageSize.Width, history.PageSize.Height, history.InsertFilePath);
- ListSelectedIndex = history.InsertIndex;
- break;
- case ActionType.DragSort:
- DragToSort(history.InsertIndex, history.SourceTargetValue.Keys.ToList<int>(), true);
- break;
- case ActionType.Reverse:
- var list = history.SourceTargetValue.Keys.ToList<int>().Union(history.SourceTargetValue.Values.ToList<int>()).ToList<int>();
- DoReverse(list, true);
- break;
- case ActionType.Paste:
- Paste(history.InsertIndex);
- break;
- default:
- break;
- }
- }
- /// <summary>
- /// 退出页面编辑面试,回到阅读页
- /// </summary>
- public void BackToPDFViewer(int PageIndex)
- {
- PDFViewer.GoToPage(PageIndex);
- viewContentViewModel.ExitToolMode();
- }
- /// <summary>
- /// 显示Toast提示
- /// </summary>
- public void ShowToast(string content = "")
- {
- if (!string.IsNullOrEmpty(content))
- {
- ToastText = content;
- }
- else
- {
- ToastText = App.MainPageLoader.GetString("OpentonFail_Warning");
- }
- ShowTip = Visibility.Visible;
- }
- /// <summary>
- /// 通知UI刷新页面范围
- /// 或通过xaml来设置选中项
- /// </summary>vb nmjvcx
- private void NotifyUIToRefresh(List<int> pageRange = null)
- {
- if (pageRange == null || pageRange.Count <= 0)
- {
- //通知UI刷新页面范围
- eventor.GetEvent<PageEditNotifyEvent>().Publish(new PageEditNotifyEventArgs(unicode));
- }
- else
- {
- //通知UI刷新页面范围
- eventor.GetEvent<PageEditNotifyEvent>().Publish(new PageEditNotifyEventArgs(unicode, NotifyType.SelectItems, pageRange));
- }
- }
- /// <summary>
- /// 获取已选中的页面集合
- /// </summary>
- /// <returns></returns>
- private List<int> getSelectedPage()
- {
- List<int> pages = new List<int>();
- for (int i = 0; i < PageEditItems.Count; i++)
- {
- if (PageEditItems[i].Selected)
- {
- pages.Add(i);
- }
- }
- return pages;
- }
- /// <summary>
- /// 删除选中项的方法 不带Reload操作
- /// 方便其他逻辑中调用
- /// </summary>
- private int DoRemoveSelectedPages(List<int> pageList = null, bool isFromUndoRedo = false, bool isReplace = false)
- {
- PageEditItem pageEditItem = null;
- int index = -1;
- if (!ServiceHelper.IAPBeforeFunction())
- {
- return index;
- }
- //删除后 的选中项
- index = maxSelectedIndex;
- List<int> indexList = new List<int>();
- if (pageList == null || pageList.Count == 0)
- {
- for (int i = 0; i < PageEditItems.Count; i++)
- {
- if (PageEditItems[i].Selected)
- {
- indexList.Add(i);
- }
- }
- //因为虚拟化 可能获取不到所有选中项的页码 需要结合选中项的集合判断一下
- if (selectedPageList.Count > 0 && selectedPageList.Count > indexList.Count)
- {
- indexList = new List<int>();
- for (int j = 0; j < selectedPageList.Count; j++)
- {
- indexList.Add(selectedPageList[j] - 1);
- }
- }
- }
- else
- {
- indexList = pageList;
- }
- if (indexList.Count > 0 && indexList.Count == PDFViewer.Document.PageCount)
- {
- // 全部替换 不显示 不能删除所有的弹窗
- if (isReplace == false)
- {
- AlertsMessage alertsMessage = new AlertsMessage();
- alertsMessage.ShowDialog("", App.MainPageLoader.GetString("PageEdit_DeleteAllPage"), App.ServiceLoader.GetString("Text_ok"));
- return -1;
- }
- }
- bool isLast = false;
- if (index == -1 && indexList.Count > 0)
- {
- if (isMultiSelected)
- {
- indexList.Sort();
- index = indexList.First();
- }
- else
- {
- index = indexList.Last();
- }
- }
- if (index == PageEditItems.Count)
- {
- pageEditItem = PageEditItems[index - 1];
- }
- else if (index < PageEditItems.Count)
- {
- if ((index + 1) >= PageEditItems.Count)
- {
- pageEditItem = PageEditItems[PageEditItems.Count - 1];
- isLast = true;
- }
- else
- {
- pageEditItem = PageEditItems[index + 1];
- }
- }
- var result = PDFViewer.Document.RemovePages(indexList.ToArray());
- if (!result)
- {
- ShowToast();
- return -1;
- }
- //文档层操作成功后再删除UI层
- for (int i = indexList.Count - 1; i >= 0; i--)
- {
- PageEditItems.RemoveAt(indexList[i]);
- }
- if (!isFromUndoRedo)
- {
- ////清除页面编辑Undo,Redo栈
- //UndoStack.Clear();
- //RedoStack.Clear();
- //this.CanUndo = false;
- //this.CanRedo = false;
- }
- index = PageEditItems.IndexOf(pageEditItem);
- if (index == -1 && indexList.Count > 0)
- {
- if (isLast)
- {
- index = PageEditItems.Count - 1;
- }
- else
- {
- index = indexList.Last();
- }
- }
- return index;
- }
- /// <summary>
- /// 提取选中页面的方法
- /// </summary>
- /// <param name="isEveryPageToFile">是否每页生成一个文件</param>
- /// <param name="isDeleteAfterExtract">是否提取后删除页面</param>
- private async void DoExtractPages(bool isEveryPageToFile, bool isDeleteAfterExtract)
- {
- System.Windows.Forms.FolderBrowserDialog dialog = new System.Windows.Forms.FolderBrowserDialog();
- if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
- {
- if (string.IsNullOrEmpty(dialog.SelectedPath))
- {
- AlertsMessage alertsMessage = new AlertsMessage();
- alertsMessage.ShowDialog("", App.MainPageLoader.GetString("OperationFailWarning"), App.ServiceLoader.GetString("Text_ok"));//补充提示文案
- return;
- }
- }
- else
- return;
- string selectedfile = "";
- IsLoading = Visibility.Visible;
- await Task.Delay(3);
- List<int> pagenums = new List<int>();
- for (int i = 0; i < PageEditItems.Count; i++)
- {
- if (PageEditItems[i].Selected)
- {
- pagenums.Add(PageEditItems[i].PageNumber);
- }
- }
- if (IsMouseRightButtonDown)
- {
- if (IsMultiSelected)
- {
- for (int i = 0; i < RightSelectedIndexs.Count; i++)
- {
- RightSelectedIndexs[i] = RightSelectedIndexs[i] + 1;
- }
- pagenums = RightSelectedIndexs;
- }
- else
- {
- pagenums = new List<int>() { RightSelectedIndex + 1 };
- }
- }
- if (isEveryPageToFile)
- {
- //每页生成的单独的文件
- for (int i = 0; i < pagenums.Count; i++)
- {
- string filename = PDFViewer.Document.FileName + " " + "pages " + pagenums[i] + ".pdf";
- string path = System.IO.Path.Combine(dialog.SelectedPath, filename);
- path = CommonHelper.CreateFilePath(path);
- selectedfile = path;
- CPDFDocument savedoc = CPDFDocument.CreateDocument();
- bool result = savedoc.ImportPages(PDFViewer.Document, pagenums[i].ToString());
- if (!result)
- {
- savedoc.Release();
- continue;
- }
- result = savedoc.WriteToFilePath(path);
- if (!result)
- {
- savedoc.Release();
- continue;
- }
- savedoc.Release();//释放内存
- }
- }
- else//全部生成一个文件
- {
- string filename = PDFViewer.Document.FileName + " " + "pages " + CommonHelper.GetPageParmFromList(pagenums) + ".pdf";
- string path = System.IO.Path.Combine(dialog.SelectedPath, filename);
- path = CommonHelper.CreateFilePath(path);
- selectedfile = path;
- CPDFDocument savedoc = CPDFDocument.CreateDocument();
- string range = String.Join(",", pagenums);
- bool result = savedoc.ImportPages(PDFViewer.Document, range);
- if (!result)
- {
- ShowToast();
- IsLoading = Visibility.Collapsed;
- return;
- }
- result = savedoc.WriteToFilePath(path);
- if (!result)
- {
- ShowToast();
- }
- savedoc.Release();//释放内存
- }
- if (isDeleteAfterExtract)
- {
- //先提取后删除,index和其他地方设置不一样
- int index = DoRemoveSelectedPages() + 1;
- if (index > PDFViewer.Document.PageCount)
- {
- index = PDFViewer.Document.PageCount;
- }
- ReloadAfterOption(true, false, Tuple.Create(0, PDFViewer.Document.PageCount));
- //通知Xaml删除后 选中的页面,从VM设置选中项会有问题
- NotifyUIToRefresh(new List<int>() { index });
- }
- CommonHelper.ShowFileBrowser(selectedfile);
- IsLoading = Visibility.Collapsed;
- }
- private async void DoSplitPages(HomePageSplitDialogModel model)
- {
- try
- {
- var pdfViewer = PDFViewer;
- System.Windows.Forms.FolderBrowserDialog dialog = new System.Windows.Forms.FolderBrowserDialog();
- //dialog.Description = App.MainPageLoader.GetString("Main_OpenFolderNoteWarning"); ;
- if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
- {
- if (string.IsNullOrEmpty(dialog.SelectedPath))
- {
- return;
- }
- }
- else
- return;
- var data = model;
- int PageCount = pdfViewer.Document.PageCount;
- string selectedfile = "";
- string directory = System.IO.Path.Combine(dialog.SelectedPath, pdfViewer.Document.FileName);
- if (Directory.Exists(directory) == false)
- {
- Directory.CreateDirectory(directory);
- }
- App.mainWindowViewModel.ProcessCloseAction = PageSplitClear;
- string filename = "";
- int index = 0;
- if (data.Mode == HomePageSplitDialogModel.SplitMode.AveragePages)
- {
- int perPages = Convert.ToInt32(data.GetModeCount);
- int splitCount = (int)Math.Ceiling((double)PageCount / (double)perPages);
- index = splitCount;
- ChatGTPAIHelper.SetIntProcess(true, "Splitting...", index, System.Windows.Visibility.Visible);
- //TODO:命名规则是否要调整
- selectedfile = data.FileName + " " + "1.pdf";
- for (int i = 0; i < splitCount; i++)
- {
- App.mainWindowViewModel.Value = i;
- await Task.Delay(50); // 模拟长时间操作
- if (App.mainWindowViewModel.ProgressTitle == "Canceling")
- {
- return;
- }
- int startNum = i * perPages + 1;
- int endNum = Math.Min(PageCount, (i + 1) * perPages);
- string range = startNum.ToString() + "-" + endNum.ToString();
- CPDFDocument savedoc = CPDFDocument.CreateDocument();
- bool result = savedoc.ImportPages(pdfViewer.Document, range);
- if (!result)
- {
- savedoc.Release();
- continue;
- }
- filename = GetFileName(data, i);
- string path = System.IO.Path.Combine(directory, filename);
- path = CommonHelper.CreateFilePath(path);
- result = savedoc.WriteToFilePath(path);
- if (!result)
- {
- savedoc.Release();
- continue;
- }
- savedoc.Release();
- selectedfile = path;
- }
- }
- else if (data.Mode == HomePageSplitDialogModel.SplitMode.AverageFiles)
- {
- int docCount = Convert.ToInt32(data.GetModeCount);
- int avePages = (int)Math.Floor((double)PageCount / (double)docCount);
- index = avePages;
- ChatGTPAIHelper.SetIntProcess(true, "Splitting...", index, System.Windows.Visibility.Visible);
- int remain = PageCount % docCount;
- int startNum = 1;
- //TODO:命名规则是否要调整
- selectedfile = data.FileName + " " + "1.pdf";
- for (int i = 0; i < docCount; i++)
- {
- App.mainWindowViewModel.Value = i;
- await Task.Delay(50); // 模拟长时间操作
- if (App.mainWindowViewModel.ProgressTitle == "Canceling")
- {
- return;
- }
- int endNum = startNum + (avePages - 1);
- if (i < remain) endNum++;
- endNum = Math.Min(endNum, PageCount);
- string range = startNum + "-" + endNum;
- startNum = endNum + 1;
- filename = GetFileName(data, i);
- string path = System.IO.Path.Combine(directory, filename);
- path = CommonHelper.CreateFilePath(path);
- CPDFDocument savedoc = CPDFDocument.CreateDocument();
- bool result = savedoc.ImportPages(pdfViewer.Document, range);
- if (!result)
- {
- savedoc.Release();
- continue;
- }
- result = savedoc.WriteToFilePath(path);
- if (!result)
- {
- savedoc.Release();
- continue;
- }
- savedoc.Release();
- selectedfile = path;
- }
- }
- else//自定义页码范围
- {
- string pageRange = "";
- List<int> pageList1 = new List<int>();
- if (data.PageMode == HomePageSplitDialogModel.PageRangeMode.OddPage)
- {
- int[] page = new int[(PageCount + 1) / 2];
- index = page.Length;
- ChatGTPAIHelper.SetIntProcess(true, "Splitting...", index, System.Windows.Visibility.Visible);
- for (int i = 0; i < page.Length; i++)
- {
- App.mainWindowViewModel.Value = i;
- await Task.Delay(50); // 模拟长时间操作
- if (App.mainWindowViewModel.ProgressTitle == "Canceling")
- {
- return;
- }
- page[i] = i * 2 + 1;
- }
- pageRange = string.Join(",", page);
- }
- else if (data.PageMode == HomePageSplitDialogModel.PageRangeMode.EvenPage)
- {
- int[] page = new int[PageCount / 2];
- index = page.Length;
- ChatGTPAIHelper.SetIntProcess(true, "Splitting...", index, System.Windows.Visibility.Visible);
- for (int i = 0; i < page.Length; i++)
- {
- App.mainWindowViewModel.Value = i;
- await Task.Delay(50); // 模拟长时间操作
- if (App.mainWindowViewModel.ProgressTitle == "Canceling")
- {
- return;
- }
- page[i] = i * 2 + 2;
- }
- pageRange = string.Join(",", page);
- }
- else if (data.PageMode == HomePageSplitDialogModel.PageRangeMode.CustomPage)
- {
- ChatGTPAIHelper.SetIntProcess(true, "Splitting...", PageCount, System.Windows.Visibility.Visible);
- pageRange = data.PageRange;
- }
- //如果是自定义输入页面范围的话,直接解析
- CommonHelper.GetPagesInRange(ref pageList1, pageRange, PageCount, new char[] { ',' }, new char[] { '-' });
- index = pageList1.Count;
- #region //part1
- selectedfile = "";
- CPDFDocument saveDoc1 = CPDFDocument.CreateDocument();
- //string filepath = data.FileName + " " + "1.pdf";
- filename = GetFileName(data, 0);
- string path1 = Path.Combine(directory, filename);
- path1 = CommonHelper.CreateFilePath(path1);
- bool result = saveDoc1.ImportPages(pdfViewer.Document, pageRange);
- if (!result)
- {
- saveDoc1.Release();
- ShowToast();
- ChatGTPAIHelper.clossProcess(index);
- return;
- }
- result = saveDoc1.WriteToFilePath(path1);
- if (!result)
- {
- saveDoc1.Release();
- ShowToast();
- ChatGTPAIHelper.clossProcess(index);
- return;
- }
- saveDoc1.Release();
- selectedfile = path1;
- #endregion //part1
- #region 方案二 //Part2 除了选定之外的页面
- List<int> pageList2 = new List<int>();
- for (int i = 1; i <= pdfViewer.Document.PageCount; i++)
- {
- if (!pageList1.Contains(i - 1))//pagelist1 存放的是index
- pageList2.Add(i);
- }
- string pageRange2 = string.Join(",", pageList2);
- CPDFDocument saveDoc2 = CPDFDocument.CreateDocument();
- string filepath2 = /*data.FileName + " " + "2.pdf";*/ GetFileName(data, 1);
- string path2 = /*Path.Combine(dialog.SelectedPath, filepath2);*/Path.Combine(directory, filepath2);
- path2 = CommonHelper.CreateFilePath(path2);
- bool result1 = saveDoc2.ImportPages(pdfViewer.Document, pageRange2);
- if (!result1)
- {
- saveDoc2.Release();
- ShowToast();
- return;
- }
- result1 = saveDoc2.WriteToFilePath(path2);
- if (!result1)
- {
- saveDoc2.Release();
- ShowToast();
- return;
- }
- saveDoc2.Release();
- //selectedfile = path2;
- }
- #endregion 方案二 //Part2 除了选定之外的页面
- //显示文件夹,并选中一个文件
- Process.Start("explorer", "/select,\"" + selectedfile + "\"");
- ChatGTPAIHelper.clossProcess(index);
- }
- catch
- {
- }
- }
- private void PageSplitClear()
- {
- App.mainWindowViewModel.ProgressTitle = "Canceling";
- App.mainWindowViewModel.IsProcessVisible = System.Windows.Visibility.Collapsed;
- }
- private string GetFileName(HomePageSplitDialogModel model, int index)
- {
- string filename = "";
- string label = model.HasLabel ? model.FileNameLabel : "";
- string deimiter = model.HasDeimiter ? model.FileNameDeimiter : "";
- if (model.IsSourceNameFront)
- {
- filename = model.SourceFileName + deimiter + label + (index + 1) + ".pdf";
- }
- else
- {
- filename = label + (index + 1) + deimiter + model.SourceFileName + ".pdf";
- }
- return filename;
- }
- /// <summary>
- /// 将文件插入到指定位置
- /// </summary>
- /// <param name="insertIndex"></param>
- public async Task<bool> InsertFromFile(int insertIndex, string filePath, CPDFDocument doc = null, string oldPassWord = null, bool isFromUndoRedo = false)
- {
- if (doc == null)
- {
- return false;
- }
- int pageCount = doc.PageCount;
- //插入整个新文档
- //文档层插入
- var insertresult = PDFViewer.Document.ImportPagesAtIndex(doc, "1-" + pageCount, insertIndex);
- if (!insertresult)
- {
- ShowToast();
- return false;
- }
- //插入成功后释放临时Document对象
- doc.Release();
- //UI层插入
- for (int i = 0; i < pageCount; i++)
- {
- var item = GetNewPageEditItem(i);
- PageEditItems.Insert(insertIndex + i, item);
- }
- //加一点延时才能显示选中效果
- await Task.Delay(200);
- List<int> pageRange = new List<int>();
- for (int i = 0; i < pageCount; i++)
- {
- pageRange.Add(insertIndex + i + 1);
- }
- if (IsBOTAThumb == Visibility.Visible)
- {
- GoToPage(pageRange);
- }
- NotifyUIToRefresh(pageRange);
- //如果是undo redo里调用本方法,则不需要添加到Undo栈
- if (!isFromUndoRedo)
- {
- //添加记录到Undo栈,清空Redo栈
- PageEditHistory history = new PageEditHistory();
- history.Type = ActionType.InsertFromFile;
- history.InsertIndex = insertIndex;
- history.InsertFilePath = filePath;
- history.InsertFilePassWord = oldPassWord;
- history.InsertPageCount = pageCount;
- history.viewmodel = this;
- PDFViewer.UndoManager.AddHistory(history);
- }
- return true;
- }
- public bool GetDocumentIsDiscryptied(string filePath, string oldPassWord, out CPDFDocument doc, out string password)
- {
- doc = CPDFDocument.InitWithFilePath(filePath);
- password = "";
- if (doc == null)
- {
- //文件损坏
- AlertsMessage alertsMessage = new AlertsMessage();
- alertsMessage.ShowDialog("", App.MainPageLoader.GetString("Main_OpenFileFailedWarning"), App.ServiceLoader.GetString("Text_ok"));
- return false;
- }
- if (doc.IsLocked)
- {
- if (!string.IsNullOrEmpty(oldPassWord))
- {
- var result = doc.UnlockWithPassword(oldPassWord);
- if (result)
- {
- password = oldPassWord;
- }
- }
- //没有传入密码,或者用传入密码解密失败是,需要弹出界面弹窗
- if (doc.IsLocked)
- {
- VerifyPasswordResult result = SecurityHelper.VerifyPasswordByPasswordKind(doc, EnumPasswordKind.StatusPermissionsPassword, dialogs);
- if (result.IsDiscryptied)
- {
- if (result.Password != null)
- {
- string filePath1 = doc.FilePath;
- if (doc.IsLocked)
- {
- doc.UnlockWithPassword(result.Password);
- }
- else
- {
- doc.CheckOwnerPassword(result.Password);
- }
- password = result.Password;
- }
- }
- else
- {
- return false;
- }
- }
- }
- return true;
- }
- /// <summary>
- /// 插入自定义页面
- /// </summary>
- /// <param name="insertIndex"></param>
- /// <param name="width"></param>
- /// <param name="height"></param>
- /// <param name="filePath"></param>
- /// <returns></returns>
- private bool InsertFromCustomPage(int insertIndex, double width, double height, string filePath)
- {
- try
- {
- bool result = false;
- //文档层插入
- if (!string.IsNullOrEmpty(filePath))
- {
- BitmapFrame frame = BitmapFrame.Create(new Uri(filePath));
- byte[] imageData = new byte[frame.PixelWidth * frame.PixelHeight * 4];
- frame.CopyPixels(imageData, frame.PixelWidth * 4, 0);
- result = PDFViewer.Document.InsertPage(insertIndex, frame.Width, frame.Height, imageData, CPDFDocumentImageMode.CPDFDocumentImageModeScaleToFill);
- }
- else
- {
- result = PDFViewer.Document.InsertPage(insertIndex, width, height, null);
- }
- if (!result)
- {
- ShowToast();
- return false;
- }
- //UI层插入Item ,需要处理一下Item
- var item = GetNewPageEditItem(insertIndex);
- PageEditItems.Insert(insertIndex, item);
- ReloadAfterOption(true, false, Tuple.Create(insertIndex - 1, insertIndex + 1), true);
- //选中插入的页面
- ListSelectedIndex = insertIndex;
- return true;
- }
- catch
- { return false; }
- }
- /// <summary>
- /// 根据索引创建新的Item
- /// </summary>
- /// <param name="index"></param>
- /// <returns></returns>
- private PageEditItem GetNewPageEditItem(int index)
- {
- PageEditItem item = new PageEditItem();
- if (PDFViewer.Document.PageAtIndex(index).Rotation % 2 != 0)
- {
- ///标记为横向页面
- item.isVertical = false;
- }
- item.PageNumber = index + 1;
- var pagesize = PDFViewer.Document.GetPageSize(index);
- item.Size = pagesize;
- //修复 缩放后粘贴的页面大小不一致的问题
- item.ItemSize = ItemSizes[ZoomIndex + 1];
- return item;
- }
- /// <summary>
- /// 进行文件操作后刷新PDFView
- /// 清除undo 栈
- /// 重加载Document
- /// 设置保存状态
- /// </summary>
- /// <param name="needRefreshPageNum">是否需要刷新页码</param>
- /// <param name="needClearUndoHistory">是否需要清空注释Undo栈</param>
- /// <param name="pageRange">需要刷新的页面范围图片</param>
- public void ReloadAfterOption(bool needRefreshPageNum = false, bool needClearUndoHistory = false, Tuple<int, int> pageRange = null, bool isScrollIntoView = false)
- {
- if (needRefreshPageNum)
- {
- RefreshPageNum();
- //从页面编辑退出的值,根据内容走,进页面编辑是这一页内容,退出来还是
- if (CurrentPageEditItem != null && IsBOTAThumb != Visibility.Visible)
- {
- int pageIndex = CurrentPageEditItem.PageNumber - 1;
- if (pageIndex != PDFViewer.CurrentIndex)
- {
- PDFViewer.GoToPage(pageIndex);
- }
- }
- //插入、替换等更新页码,页码输入框的值未更新
- RefreshTbPageRange();
- }
- if (needClearUndoHistory)
- {
- //只有删除操作清空undo栈
- //可能会引起注释模块联动问题 需要留意
- PDFViewer.UndoManager.ClearHistory();
- }
- if (pageRange != null)
- {
- if (pageRange.Item2 - pageRange.Item1 > 30)
- {
- if (isScrollIntoView)
- {
- //插入后 滚动到 选中的页面
- List<int> pageRanges = new List<int>() { pageRange.Item2 };
- NotifyUIToRefresh(pageRanges);
- }
- else
- {
- //范围较大时,通知UI获取更准确的刷新范围
- NotifyUIToRefresh();
- }
- }
- else
- {
- RefreshItemImage(pageRange.Item1, pageRange.Item2);
- if (isScrollIntoView)
- {
- if (ListSelectedIndex == -1)
- {
- //插入后 滚动到 选中的页面
- List<int> pageRanges = new List<int>() { pageRange.Item2 };
- NotifyUIToRefresh(pageRanges);
- }
- }
- }
- }
- PDFViewer.UndoManager.CanSave = true;
- PDFViewer.ReloadDocument();
- //解决:阅读页放大到只能看到最后一页时,从缩略图删除最后一页,阅读页面没有联动刷新
- if (PDFViewer.GetVerticalOffset() >= PDFViewer.GetExtendHeight())
- {
- PDFViewer.ScrollToVerticalOffset(PDFViewer.GetExtendHeight());
- }
- }
- /// <summary>
- /// 重新获取选中页码
- /// /插入、替换等更新页码,页码输入框的值未更新
- /// </summary>
- private void RefreshTbPageRange()
- {
- List<int> indexList = GetSelectedItemPageNumbers();
- if (indexList.Count > 0)
- {
- //选中项集合 也需要 同步更新
- selectedPageList.Clear();
- selectedPageList.AddRange(indexList);
- //只选中单个页面是,listselectedIndex 更准确
- if (indexList.Count == 1)
- {
- TbPageRange = (listSelecedIndex + 1).ToString();
- }
- else
- {
- //根据选中的页面转换成1,3-10类似的字符串
- string pageparm = CommonHelper.GetPageParmFromList(indexList);
- TbPageRange = pageparm;
- }
- }
- }
- private List<int> GetSelectedItemPageNumbers()
- {
- List<int> indexList = new List<int>();
- for (int i = 0; i < PageEditItems.Count; i++)
- {
- if (PageEditItems[i].Selected)
- {
- indexList.Add(PageEditItems[i].PageNumber);
- }
- }
- return indexList;
- }
- /// <summary>
- /// 旋转所有选中页面
- /// </summary>
- /// <param name="rightRotate"></param>
- private async void RotateSelectedPages(bool rightRotate = true, List<int> pageitems = null, bool isFromUndoRedo = false)
- {
- if (!ServiceHelper.IAPBeforeFunction())
- {
- return;
- }
- IsLoading = Visibility.Visible;
- await Task.Delay(2);
- Dictionary<int, int> items = new Dictionary<int, int>();
- if (pageitems == null)
- {
- //旋转选中页面
- items = SetRotateSelectedPagesEvent(rightRotate);
- }
- else
- {
- if (pageitems.Count == 0)
- {
- items = SetRotateSelectedPagesEvent(rightRotate);
- }
- else
- {
- //旋转对应Items集合
- for (int i = 0; i < pageitems.Count; i++)
- {
- PDFViewer.RotatePage(ComPDFKitViewer.PageRotate.Rotate90, rightRotate, pageitems[i]);
- items.Add(pageitems[i], pageitems[i]);
- //重新拿图
- if (PageEditItems.Count > pageitems[i])
- {
- PageEditItems[pageitems[i]].IsGetImage = false;
- }
- }
- }
- }
- //旋转页面后取消选中
- PDFViewer.ClearSelectPDFEdit(true);
- //如果是undo,Redo里调用的方法,则不记录到栈里
- if (!isFromUndoRedo)
- {
- //记录进Undo栈
- PageEditHistory history = new PageEditHistory();
- history.Type = rightRotate ? ActionType.RightRotate : ActionType.LeftRotate;
- history.SourceTargetValue = items;
- history.viewmodel = this;
- PDFViewer.UndoManager.AddHistory(history);
- }
- //页面范围-横向页面,旋转90°后,输入框应当变成具体的页码,因为旋转后不是横向页面了(纵向页面同理)
- if (items.Count > 0)
- {
- ReloadAfterOption(true, false, Tuple.Create(items.Keys.First(), items.Keys.Last()));
- }
- IsLoading = Visibility.Collapsed;
- }
- private Dictionary<int, int> SetRotateSelectedPagesEvent(bool rightRotate)
- {
- Dictionary<int, int> items = new Dictionary<int, int>();
- for (int i = 0; i < PageEditItems.Count; i++)
- {
- if (PageEditItems[i].Selected)
- {
- //逆时针旋转传 - 1 顺时针旋转传1
- //直接用PDFViewer的旋转接口,需要留意好,中间层不能有自动清空undo栈
- PDFViewer.RotatePage(ComPDFKitViewer.PageRotate.Rotate90, rightRotate, i);
- items.Add(i, i);
- //重新拿图
- PageEditItems[i].IsGetImage = false;
- }
- }
- return items;
- }
- /// <summary>
- /// 刷新页码
- /// </summary>
- private void RefreshPageNum()
- {
- for (int i = 0; i < PageEditItems.Count; i++)
- {
- PageEditItems[i].PageNumber = i + 1;
- if (IsBOTAThumb == Visibility.Visible)
- {
- PageEditItems[i].FontSize = 12;
- }
- else
- {
- PageEditItems[i].FontSize = 14;
- }
- }
- }
- /// <summary>
- /// 刷新页面范围下拉框
- /// </summary>
- private void RefreshPageRangeItem()
- {
- PageRangeItems.Clear();
- PageRangeItems.Add(App.MainPageLoader.GetString("WritableComboBox_AllPage"));
- PageRangeItems.Add(App.MainPageLoader.GetString("WritableComboBox_OddPage"));
- PageRangeItems.Add(App.MainPageLoader.GetString("WritableComboBox_EvenPage"));
- PageRangeItems.Add("Horizontal Page");
- PageRangeItems.Add("Vertical Page");
- PageRangeItems.Add(App.MainPageLoader.GetString("WritableComboBox_CustomRangeEge"));
- }
- /// <summary>
- /// 选中目标页面范围的页面
- /// </summary>
- /// <param name="index">页面范围选中项索引</param>
- private async void SuitPageRange(int index)
- {
- List<int> pageRange = new List<int>();
- switch (index)
- {
- case 0:
- for (int i = 0; i < PageEditItems.Count; i++)
- {
- pageRange.Add(i + 1);
- }
- break;
- case 1:
- //奇数页
- //先清空所有选项
- ListSelectedIndex = -1;
- for (int i = 0; i < PageEditItems.Count; i++)
- {
- if (i % 2 == 0)
- {
- pageRange.Add(i + 1);
- }
- }
- break;
- case 2:
- //偶数页
- //先清空所有选项
- ListSelectedIndex = -1;
- for (int i = 0; i < PageEditItems.Count; i++)
- {
- if (i % 2 != 0)
- {
- pageRange.Add(i + 1);
- }
- }
- break;
- case 3://横向页面
- //先清空所有选项
- ListSelectedIndex = -1;
- for (int i = 0; i < PageEditItems.Count; i++)
- {
- if (!PageEditItems[i].isVertical)
- {
- pageRange.Add(i + 1);
- }
- }
- break;
- case 4://纵向页面
- for (int i = 0; i < PageEditItems.Count; i++)
- {
- if (PageEditItems[i].isVertical)
- {
- pageRange.Add(i + 1);
- }
- }
- break;
- case 5://自定义
- TxtPageInputVisibility = Visibility.Visible;
- await Task.Delay(30);
- TbPageRange = "";
- break;
- default:
- break;
- }
- if (pageRange.Count > 0)
- {
- //避免在下面的过程中频繁触发SelectionChanged事件
- IsSelectFormSelf = true;
- NotifyUIToRefresh(pageRange);
- //为了避免重复选中,条件也符合而文本缺失的情况
- TbPageRange = PageRangeItems[index];
- RightSelectedIndexs.Clear();
- foreach (var item in pageRange)
- {
- RightSelectedIndexs.Add(item - 1);
- }
- IsSelectFormSelf = false;
- }
- else
- {
- //选中了下拉框的选项
- //增加条件,修复全选页面,但是ctrl点选取消后,选中状态不准确问题
- if (index != -1)
- {
- //没有符合条件时 清空选中项
- ListSelectedIndex = -1;
- //20230714 没有符合条件的页面时候,控件内容不清空
- //没有符合条件的页面时,空间内容清空
- //await Task.Delay(30);
- //TbPageRange = "";
- }
- }
- }
- /// <summary>
- /// 是否显示页面尺寸
- /// </summary>
- /// <param name="show">是或否</param>
- private void ShowPageSize()
- {
- if (ShowedPageSize == Visibility.Visible)
- {
- IsShowPageSize = true;
- ShowedPageSize = Visibility.Collapsed;
- HidePageSize = Visibility.Visible;
- }
- else
- {
- IsShowPageSize = false;
- HidePageSize = Visibility.Collapsed;
- ShowedPageSize = Visibility.Visible;
- }
- ListSelectedIndex = -1;
- selectedPageList.Clear();
- //显示显示当前范围的item的页面尺寸,其他的Item在刷新图片时,再显示尺寸
- if (startRefreshedIndex <= endRefreshedIndex)
- {
- for (int i = startRefreshedIndex; i < endRefreshedIndex; i++)
- {
- if (i >= 0 && i <= PageEditItems.Count - 1)
- {
- PageEditItems[i].ShowPageSize = IsShowPageSize;
- }
- }
- }
- }
- /// <summary>
- /// 从PDFView获取所有Items集合
- /// </summary>
- public void GetSourceItems(bool isFirstLoad)
- {
- if (isFirstLoad || IsBOTAThumb == Visibility.Visible)
- {
- PageEditItems.Clear();
- for (int i = 0; i < PDFViewer.Document.PageCount; i++)
- {
- var item = GetNewPageEditItem(i);
- PageEditItems.Add(item);
- }
- }
- //else
- //{
- // //后续进来仅刷新图片即可
- // for (int i = 0; i < PageEditItems.Count; i++)
- // {
- // PageEditItems[i].IsGetImage = false;
- // }
- //}
- }
- /// <summary>
- /// 刷新书签列表
- /// </summary>
- public void RefreshBookMarkList()
- {
- if (PDFViewer != null)
- {
- var booklist = PDFViewer.Document.GetBookmarkList();
- if (booklist == null)
- {
- return;
- }
- //获取所有书签的Index集合
- List<int> marks = new List<int>();
- for (int i = 0; i < booklist.Count; i++)
- {
- marks.Add(booklist[i].PageIndex);
- }
- //不能只遍历marks集合,考虑书签集合元素删除的情况
- for (int k = 0; k < PageEditItems.Count; k++)
- {
- if (marks.Contains(k))
- PageEditItems[k].HaveBookMark = true;
- else
- PageEditItems[k].HaveBookMark = false;
- }
- }
- }
- /// <summary>
- /// 刷新指定范围的图片
- /// </summary>
- /// <param name="startIndex"></param>
- /// <param name="endIndex"></param>
- private void RefreshItemImage(int startIndex, int endIndex)
- {
- startRefreshedIndex = startIndex;
- endRefreshedIndex = endIndex;
- if (PDFViewer == null || PDFViewer.Document == null)
- {
- return;
- }
- //一个拿图比例系数,减少拿图耗时,尽量确保缩放后图片清晰度不会很差
- int rate = (int)ItemSizes[2].Height;
- //230628 缩略图需要根据当前 的缩略值
- //int rate = (int)ItemSizes[ZoomIndex + 1].Height;
- for (int i = startIndex; i <= endIndex; i++)
- {
- if (i <= PageEditItems.Count - 1 && i >= 0 && PageEditItems.Count > 0 && PDFViewer.Document != null && rate > 0)
- {
- //先更新一次每个页面的尺寸 确保图的方向正确
- PageEditItems[i].Size = PDFViewer.Document.GetPageSize(i);
- if (PageEditItems[i].Size.Width <= 0 || PageEditItems[i].Size.Height <= 0)
- {
- //补充判空逻辑,避免崩溃
- continue;
- }
- //不能一次性显示页面大小,页数较多时会导致界面卡死
- //每次刷新图片时,根据右键菜单状态(是否显示页面大小)来控制每个Item的页面尺寸显示
- PageEditItems[i].ShowPageSize = IsShowPageSize;
- //宽高为样式中图片控件宽高
- if (PageEditItems[i].isVertical)
- {
- //等比例缩小
- if (PageEditItems[i].Size.Height > rate)
- {
- int index = Convert.ToInt32(PageEditItems[i].Size.Width / (PageEditItems[i].Size.Height / rate));
- SetThumbnailImage(i, index, rate, true);
- }
- else
- {
- int index = Convert.ToInt32(PageEditItems[i].Size.Width * (rate / (int)PageEditItems[i].Size.Height));
- //尺寸大小的图片 等比例放大 避免页面放大后内容模糊
- SetThumbnailImage(i, index, rate, true);
- }
- }
- else
- {
- if (PageEditItems[i].Size.Width > rate)
- {
- int index = Convert.ToInt32(PageEditItems[i].Size.Height / (PageEditItems[i].Size.Width / rate));
- SetThumbnailImage(i, index, rate, false);
- }
- else
- {
- int index = Convert.ToInt32(PageEditItems[i].Size.Height * (rate / (int)(PageEditItems[i].Size.Width)));
- SetThumbnailImage(i, index, rate, false);
- }
- }
- }
- }
- }
- private async void SetThumbnailImage(int i, int index, int rate, bool isVertical)
- {
- if (viewContentViewModel.IsHiddenAnnot)
- {
- if (isVertical)
- {
- //显示=1, 隐藏=0注释
- await PDFViewer.GetThumbnail(i, index, rate, 0);
- }
- else
- {
- await PDFViewer.GetThumbnail(i, rate, index, 0);
- }
- }
- else
- {
- if (isVertical)
- {
- await PDFViewer.GetThumbnail(i, index, rate, 1);
- }
- else
- {
- await PDFViewer.GetThumbnail(i, rate, index, 1);
- }
- }
- }
- /// <summary>
- /// 拖拽排序功能
- /// </summary>
- /// <param name="targetIndex"></param>
- /// <param name="pageIndexs"></param>
- public void DragToSort(int targetIndex, List<int> pageIndexs, bool IsFromUndoRedo = false)
- {
- //拖拽排序后需要重新选中项的集合
- List<int> selectedPages = new List<int>();
- //记录原位置和目标位置的字典,用于Undo,Redo恢复
- Dictionary<int, int> SourceTargetValue = new Dictionary<int, int>();
- bool result = false;
- //排序前,先对所有页码排序
- pageIndexs.Sort();
- //要考虑每一次交换都会导致局部页码发生改变
- //每次整体往后移动时,先移动大页码;整体往前移动时,先移动小页码;往中间移动时,再按上述两种情况分别移动
- if (targetIndex <= pageIndexs[0])
- {
- for (int i = 0; i < pageIndexs.Count; i++)
- {
- // list.Add(PageEditListBox.Items[pageIndexs[i]] as ListBoxItem);
- //sourceindex.Add(pageIndexs[i]);
- result = MoveItemToIndex(pageIndexs[i], targetIndex + i);
- if (!result)
- {
- return;
- }
- SourceTargetValue.Add(pageIndexs[i], targetIndex + i);
- selectedPages.Add(targetIndex + i + 1);
- }
- }
- else if (targetIndex > pageIndexs[pageIndexs.Count - 1])
- {
- //目标位置在所有选中内容右边 整体后移
- for (int i = 0; i < pageIndexs.Count; i++)
- {
- result = MoveItemToIndex(pageIndexs[pageIndexs.Count - 1 - i], targetIndex - 1 - i);
- if (!result)
- {
- return;
- }
- SourceTargetValue.Add(pageIndexs[pageIndexs.Count - 1 - i], targetIndex - 1 - i);
- selectedPages.Add(targetIndex - i);
- }
- }
- else//目标位置在所有选中项中间
- {
- int i, j, k;
- //找出PageEditListBox.Items中页码等于destpage的下标
- for (k = 0; k < pageIndexs.Count - 1; k++)
- {
- //这里要算入K---即前面部分的页面个数
- if (pageIndexs[k] < targetIndex && pageIndexs[k + 1] >= targetIndex)
- {
- break;
- }
- }
- //局部往后移动
- for (i = 0; i <= k; i++)
- {
- result = MoveItemToIndex(pageIndexs[k - i], targetIndex - 1 - i);
- if (!result)
- {
- return;
- }
- SourceTargetValue.Add(pageIndexs[k - i], targetIndex - 1 - i);
- selectedPages.Add(targetIndex - i);
- }
- int newIndex = targetIndex;
- //局部往前移动
- for (j = i; j < pageIndexs.Count; j++)
- {
- result = MoveItemToIndex(pageIndexs[j], newIndex);
- if (!result)
- {
- return;
- }
- SourceTargetValue.Add(pageIndexs[j], newIndex);
- selectedPages.Add(newIndex + 1);
- newIndex++;
- }
- }
- //刷新页码和图片
- ReloadAfterOption(true, false, new Tuple<int, int>(0, PDFViewer.Document.PageCount));
- //先刷新页码再选中item,顶部的选中页面更准确
- //通知UI选中Items
- NotifyUIToRefresh(selectedPages);
- if (!IsFromUndoRedo)
- {
- //存入Undo栈
- PageEditHistory history = new PageEditHistory();
- history.Type = ActionType.DragSort;
- history.SourceTargetValue = SourceTargetValue;
- //用于Redo恢复
- history.InsertIndex = targetIndex;
- history.viewmodel = this;
- PDFViewer.UndoManager.AddHistory(history);
- }
- }
- /// <summary>
- /// 移动某个Item到指定位置
- /// </summary>
- private bool MoveItemToIndex(int sourceindex, int targetindex)
- {
- if (targetindex == sourceindex || targetindex < 0)
- {
- return false;
- }
- //文档层移动
- var result = PDFViewer.Document.MovePage(sourceindex, targetindex);
- if (!result)
- {
- return false;
- }
- //UI层移动
- var source = PageEditItems[sourceindex];
- PageEditItems.RemoveAt(sourceindex);
- PageEditItems.Insert(targetindex, source);
- if (PDFViewer.CurrentIndex == sourceindex)
- {
- PDFViewer.GoToPage(targetindex);
- }
- return true;
- }
- private void PDFViewer_InfoChanged(object sender, KeyValuePair<string, object> e)
- {
- if (PDFViewer.Parent is ContentControl ui)
- {
- //判断鼠标焦点 是否在控件上
- if (ui.IsMouseOver)
- {
- //缩略图 复制粘贴后会选择第一项的问题
- if (e.Key == "PageNum" && !viewContentViewModel.isInPageEdit)
- {
- int index = (e.Value as ComPDFKitViewer.RenderData).PageIndex - 1;
- //注释掉 该方法有许多联动,避免联动影响
- //NotifyUIToRefresh(new List<int> { (e.Value as ComPDFKitViewer.RenderData).PageIndex });
- eventor.GetEvent<PageEditSelectedItemEvent>().Publish(new PageEditSelectedItemEventArgs() { Unicode = unicode, SelectedItemIndex = index, IsSingle = true });
- }
- }
- }
- //不准确 有时候会触发两次,就无法判断
- //if (IsAddPages == false)
- //{
- // //缩略图 复制粘贴后会选择第一项的问题
- // if (e.Key == "PageNum" && !viewContentViewModel.isInPageEdit)
- // {
- // int index = (e.Value as ComPDFKitViewer.RenderData).PageIndex - 1;
- // //注释掉 该方法有许多联动,避免联动影响
- // //NotifyUIToRefresh(new List<int> { (e.Value as ComPDFKitViewer.RenderData).PageIndex });
- // eventor.GetEvent<PageEditSelectedItemEvent>().Publish(new PageEditSelectedItemEventArgs() { Unicode = unicode, SelectedItemIndex = index, IsSingle = true });
- // }
- //}
- //else
- //{
- // IsAddPages = false;
- // return;
- //}
- }
- /// <summary>
- /// 从底层库获取对应页面的图片
- /// </summary>
- /// <param name="pageIndex"></param>
- /// <param name="thumb"></param>
- /// <param name="w"></param>
- /// <param name="h"></param>
- private void PDFViewer_OnThumbnailGenerated(int pageIndex, byte[] thumb, int w, int h)
- {
- try
- {
- if (PageEditItems.Count >= pageIndex + 1)
- {
- PixelFormat fmt = PixelFormats.Bgra32;
- BitmapSource bps = BitmapSource.Create(w, h, 96.0, 96.0, fmt, null, thumb, (w * fmt.BitsPerPixel + 7) / 8);
- PageEditItems[pageIndex].Image = bps;
- PageEditItems[pageIndex].IsGetImage = true;
- }
- }
- catch
- {
- }
- }
- #endregion 方法
- #region Navigate
- public bool IsNavigationTarget(NavigationContext navigationContext)
- {
- return true;
- }
- public void OnNavigatedFrom(NavigationContext navigationContext)
- {
- }
- /// <summary>
- /// 从其他页面导航过来的时候会触发
- /// 考虑只有在页面编辑的时候会进行页面的删减,可以尝试逻辑优化:仅第一次进入页面编辑时重新刷新页面
- /// </summary>
- /// <param name="navigationContext"></param>
- public void OnNavigatedTo(NavigationContext navigationContext)
- {
- navigationContext.Parameters.TryGetValue<ViewContentViewModel>(ParameterNames.ViewContentViewModel, out viewContentViewModel);
- navigationContext.Parameters.TryGetValue<CPDFViewer>(ParameterNames.PDFViewer, out PDFViewer);
- bool isBOTA = false;
- navigationContext.Parameters.TryGetValue<bool>(ParameterNames.BOTAThumb, out isBOTA);
- if (PDFViewer != null)
- {
- Initializing = true;
- if (isFirstLoad)
- {
- PDFViewer.OnThumbnailGenerated -= PDFViewer_OnThumbnailGenerated;
- PDFViewer.OnThumbnailGenerated += PDFViewer_OnThumbnailGenerated;
- PDFViewer.InfoChanged -= PDFViewer_InfoChanged;
- PDFViewer.InfoChanged += PDFViewer_InfoChanged;
- PDFViewer.AnnotEditHandler -= PDFViewer_AnnotEditHandler;
- PDFViewer.AnnotEditHandler += PDFViewer_AnnotEditHandler;
- ZoomIndex = 0;
- }
- //BOTA缩略图时,显示不同的菜单栏
- if (isBOTA)
- {
- IsBOTAThumb = Visibility.Visible;
- //ShowedPageSize = Visibility.Collapsed;
- //HidePageSize = Visibility.Collapsed;
- }
- else
- {
- IsBOTAThumb = Visibility.Collapsed;
- //进入页面编辑 滚动到选中页面
- //NotifyUIToRefresh();
- }
- //每次进入页面编辑都刷新item个数,缩略图删减时,可以更新item
- //需要留意大文档性能
- GetSourceItems(true);
- // 暂时 bota 和页面编辑不联动,切换后,是重新获取数据,不会获得之前的状态
- IsShowPageSize = false;
- ShowedPageSize = Visibility.Visible;
- HidePageSize = Visibility.Collapsed;
- //清空一下选中项,修复进入页面编辑后仍然选中多页的问题
- ListSelectedIndex = -1;
- ListSelectedIndex = PDFViewer.CurrentIndex;
- //页面编辑取消显示书签Icon
- //RefreshBookMarkList();
- isFirstLoad = false;
- Initializing = false;
- if (PageEditItems.Count > 0)
- {
- if (PageEditItems.IndexOf(PageEditItems[PDFViewer.CurrentIndex]) > -1)
- {
- //记录 进页面编辑是这一页内容
- CurrentPageEditItem = PageEditItems[PDFViewer.CurrentIndex];
- }
- }
- }
- }
- private void PDFViewer_AnnotEditHandler(object sender, List<ComPDFKitViewer.AnnotEvent.AnnotEditEvent> e)
- {
- if (e != null && e.Count > 0 && IsBOTAThumb == Visibility.Visible)
- {
- //缩略图模式下 刷新页面
- int pageIndex = e[0].PageIndex;
- RefreshItemImage(pageIndex, pageIndex);
- }
- }
- #endregion Navigate
- }
- }
|