Cpdf.php 214 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466
  1. <?php
  2. /**
  3. * A PHP class to provide the basic functionality to create a pdf document without
  4. * any requirement for additional modules.
  5. *
  6. * Extended by Orion Richardson to support Unicode / UTF-8 characters using
  7. * TCPDF and others as a guide.
  8. *
  9. * @author Wayne Munro <pdf@ros.co.nz>
  10. * @author Orion Richardson <orionr@yahoo.com>
  11. * @author Helmut Tischer <htischer@weihenstephan.org>
  12. * @author Ryan H. Masten <ryan.masten@gmail.com>
  13. * @author Brian Sweeney <eclecticgeek@gmail.com>
  14. * @author Fabien Ménager <fabien.menager@gmail.com>
  15. * @license Public Domain http://creativecommons.org/licenses/publicdomain/
  16. * @package Cpdf
  17. */
  18. namespace Dompdf;
  19. use FontLib\Exception\FontNotFoundException;
  20. use FontLib\Font;
  21. use FontLib\BinaryStream;
  22. class Cpdf
  23. {
  24. const ACROFORM_SIG_SIGNATURESEXISTS = 0x0001;
  25. const ACROFORM_SIG_APPENDONLY = 0x0002;
  26. const ACROFORM_FIELD_BUTTON = 'Btn';
  27. const ACROFORM_FIELD_TEXT = 'Tx';
  28. const ACROFORM_FIELD_CHOICE = 'Ch';
  29. const ACROFORM_FIELD_SIG = 'Sig';
  30. const ACROFORM_FIELD_READONLY = 0x0001;
  31. const ACROFORM_FIELD_REQUIRED = 0x0002;
  32. const ACROFORM_FIELD_TEXT_MULTILINE = 0x1000;
  33. const ACROFORM_FIELD_TEXT_PASSWORD = 0x2000;
  34. const ACROFORM_FIELD_TEXT_RICHTEXT = 0x10000;
  35. const ACROFORM_FIELD_CHOICE_COMBO = 0x20000;
  36. const ACROFORM_FIELD_CHOICE_EDIT = 0x40000;
  37. const ACROFORM_FIELD_CHOICE_SORT = 0x80000;
  38. const ACROFORM_FIELD_CHOICE_MULTISELECT = 0x200000;
  39. const XOBJECT_SUBTYPE_FORM = 'Form';
  40. /**
  41. * @var integer The current number of pdf objects in the document
  42. */
  43. public $numObj = 0;
  44. /**
  45. * @var array This array contains all of the pdf objects, ready for final assembly
  46. */
  47. public $objects = [];
  48. /**
  49. * @var integer The objectId (number within the objects array) of the document catalog
  50. */
  51. public $catalogId;
  52. /**
  53. * @var integer The objectId (number within the objects array) of indirect references (Javascript EmbeddedFiles)
  54. */
  55. protected $indirectReferenceId = 0;
  56. /**
  57. * @var integer The objectId (number within the objects array)
  58. */
  59. protected $embeddedFilesId = 0;
  60. /**
  61. * AcroForm objectId
  62. *
  63. * @var integer
  64. */
  65. public $acroFormId;
  66. /**
  67. * @var int
  68. */
  69. public $signatureMaxLen = 5000;
  70. /**
  71. * @var array Array carrying information about the fonts that the system currently knows about
  72. * Used to ensure that a font is not loaded twice, among other things
  73. */
  74. public $fonts = [];
  75. /**
  76. * @var string The default font metrics file to use if no other font has been loaded.
  77. * The path to the directory containing the font metrics should be included
  78. */
  79. public $defaultFont = './fonts/Helvetica.afm';
  80. /**
  81. * @string A record of the current font
  82. */
  83. public $currentFont = '';
  84. /**
  85. * @var string The current base font
  86. */
  87. public $currentBaseFont = '';
  88. /**
  89. * @var integer The number of the current font within the font array
  90. */
  91. public $currentFontNum = 0;
  92. /**
  93. * @var integer
  94. */
  95. public $currentNode;
  96. /**
  97. * @var integer Object number of the current page
  98. */
  99. public $currentPage;
  100. /**
  101. * @var integer Object number of the currently active contents block
  102. */
  103. public $currentContents;
  104. /**
  105. * @var integer Number of fonts within the system
  106. */
  107. public $numFonts = 0;
  108. /**
  109. * @var integer Number of graphic state resources used
  110. */
  111. private $numStates = 0;
  112. /**
  113. * @var array Number of graphic state resources used
  114. */
  115. private $gstates = [];
  116. /**
  117. * @var array Current color for fill operations, defaults to inactive value,
  118. * all three components should be between 0 and 1 inclusive when active
  119. */
  120. public $currentColor = null;
  121. /**
  122. * @var array Current color for stroke operations (lines etc.)
  123. */
  124. public $currentStrokeColor = null;
  125. /**
  126. * @var string Fill rule (nonzero or evenodd)
  127. */
  128. public $fillRule = "nonzero";
  129. /**
  130. * @var string Current style that lines are drawn in
  131. */
  132. public $currentLineStyle = '';
  133. /**
  134. * @var array Current line transparency (partial graphics state)
  135. */
  136. public $currentLineTransparency = ["mode" => "Normal", "opacity" => 1.0];
  137. /**
  138. * array Current fill transparency (partial graphics state)
  139. */
  140. public $currentFillTransparency = ["mode" => "Normal", "opacity" => 1.0];
  141. /**
  142. * @var array An array which is used to save the state of the document, mainly the colors and styles
  143. * it is used to temporarily change to another state, then change back to what it was before
  144. */
  145. public $stateStack = [];
  146. /**
  147. * @var integer Number of elements within the state stack
  148. */
  149. public $nStateStack = 0;
  150. /**
  151. * @var integer Number of page objects within the document
  152. */
  153. public $numPages = 0;
  154. /**
  155. * @var array Object Id storage stack
  156. */
  157. public $stack = [];
  158. /**
  159. * @var integer Number of elements within the object Id storage stack
  160. */
  161. public $nStack = 0;
  162. /**
  163. * an array which contains information about the objects which are not firmly attached to pages
  164. * these have been added with the addObject function
  165. */
  166. public $looseObjects = [];
  167. /**
  168. * array contains information about how the loose objects are to be added to the document
  169. */
  170. public $addLooseObjects = [];
  171. /**
  172. * @var integer The objectId of the information object for the document
  173. * this contains authorship, title etc.
  174. */
  175. public $infoObject = 0;
  176. /**
  177. * @var integer Number of images being tracked within the document
  178. */
  179. public $numImages = 0;
  180. /**
  181. * @var array An array containing options about the document
  182. * it defaults to turning on the compression of the objects
  183. */
  184. public $options = ['compression' => true];
  185. /**
  186. * @var integer The objectId of the first page of the document
  187. */
  188. public $firstPageId;
  189. /**
  190. * @var integer The object Id of the procset object
  191. */
  192. public $procsetObjectId;
  193. /**
  194. * @var array Store the information about the relationship between font families
  195. * this used so that the code knows which font is the bold version of another font, etc.
  196. * the value of this array is initialised in the constructor function.
  197. */
  198. public $fontFamilies = [];
  199. /**
  200. * @var string Folder for php serialized formats of font metrics files.
  201. * If empty string, use same folder as original metrics files.
  202. * This can be passed in from class creator.
  203. * If this folder does not exist or is not writable, Cpdf will be **much** slower.
  204. * Because of potential trouble with php safe mode, folder cannot be created at runtime.
  205. */
  206. public $fontcache = '';
  207. /**
  208. * @var integer The version of the font metrics cache file.
  209. * This value must be manually incremented whenever the internal font data structure is modified.
  210. */
  211. public $fontcacheVersion = 6;
  212. /**
  213. * @var string Temporary folder.
  214. * If empty string, will attempt system tmp folder.
  215. * This can be passed in from class creator.
  216. */
  217. public $tmp = '';
  218. /**
  219. * @var string Track if the current font is bolded or italicised
  220. */
  221. public $currentTextState = '';
  222. /**
  223. * @var string Messages are stored here during processing, these can be selected afterwards to give some useful debug information
  224. */
  225. public $messages = '';
  226. /**
  227. * @var string The encryption array for the document encryption is stored here
  228. */
  229. public $arc4 = '';
  230. /**
  231. * @var integer The object Id of the encryption information
  232. */
  233. public $arc4_objnum = 0;
  234. /**
  235. * @var string The file identifier, used to uniquely identify a pdf document
  236. */
  237. public $fileIdentifier = '';
  238. /**
  239. * @var boolean A flag to say if a document is to be encrypted or not
  240. */
  241. public $encrypted = false;
  242. /**
  243. * @var string The encryption key for the encryption of all the document content (structure is not encrypted)
  244. */
  245. public $encryptionKey = '';
  246. /**
  247. * @var array Array which forms a stack to keep track of nested callback functions
  248. */
  249. public $callback = [];
  250. /**
  251. * @var integer The number of callback functions in the callback array
  252. */
  253. public $nCallback = 0;
  254. /**
  255. * @var array Store label->id pairs for named destinations, these will be used to replace internal links
  256. * done this way so that destinations can be defined after the location that links to them
  257. */
  258. public $destinations = [];
  259. /**
  260. * @var array Store the stack for the transaction commands, each item in here is a record of the values of all the
  261. * publiciables within the class, so that the user can rollback at will (from each 'start' command)
  262. * note that this includes the objects array, so these can be large.
  263. */
  264. public $checkpoint = '';
  265. /**
  266. * @var array Table of Image origin filenames and image labels which were already added with o_image().
  267. * Allows to merge identical images
  268. */
  269. public $imagelist = [];
  270. /**
  271. * @var boolean Whether the text passed in should be treated as Unicode or just local character set.
  272. */
  273. public $isUnicode = false;
  274. /**
  275. * @var string the JavaScript code of the document
  276. */
  277. public $javascript = '';
  278. /**
  279. * @var boolean whether the compression is possible
  280. */
  281. protected $compressionReady = false;
  282. /**
  283. * @var array Current page size
  284. */
  285. protected $currentPageSize = ["width" => 0, "height" => 0];
  286. /**
  287. * @var array All the chars that will be required in the font subsets
  288. */
  289. protected $stringSubsets = [];
  290. /**
  291. * @var string The target internal encoding
  292. */
  293. protected static $targetEncoding = 'Windows-1252';
  294. /**
  295. * @var array
  296. */
  297. protected $byteRange = array();
  298. /**
  299. * @var array The list of the core fonts
  300. */
  301. protected static $coreFonts = [
  302. 'courier',
  303. 'courier-bold',
  304. 'courier-oblique',
  305. 'courier-boldoblique',
  306. 'helvetica',
  307. 'helvetica-bold',
  308. 'helvetica-oblique',
  309. 'helvetica-boldoblique',
  310. 'times-roman',
  311. 'times-bold',
  312. 'times-italic',
  313. 'times-bolditalic',
  314. 'symbol',
  315. 'zapfdingbats'
  316. ];
  317. /**
  318. * Class constructor
  319. * This will start a new document
  320. *
  321. * @param array $pageSize Array of 4 numbers, defining the bottom left and upper right corner of the page. first two are normally zero.
  322. * @param boolean $isUnicode Whether text will be treated as Unicode or not.
  323. * @param string $fontcache The font cache folder
  324. * @param string $tmp The temporary folder
  325. */
  326. function __construct($pageSize = [0, 0, 612, 792], $isUnicode = false, $fontcache = '', $tmp = '')
  327. {
  328. $this->isUnicode = $isUnicode;
  329. $this->fontcache = rtrim($fontcache, DIRECTORY_SEPARATOR."/\\");
  330. $this->tmp = ($tmp !== '' ? $tmp : sys_get_temp_dir());
  331. $this->newDocument($pageSize);
  332. $this->compressionReady = function_exists('gzcompress');
  333. if (in_array('Windows-1252', mb_list_encodings())) {
  334. self::$targetEncoding = 'Windows-1252';
  335. }
  336. // also initialize the font families that are known about already
  337. $this->setFontFamily('init');
  338. }
  339. /**
  340. * Document object methods (internal use only)
  341. *
  342. * There is about one object method for each type of object in the pdf document
  343. * Each function has the same call list ($id,$action,$options).
  344. * $id = the object ID of the object, or what it is to be if it is being created
  345. * $action = a string specifying the action to be performed, though ALL must support:
  346. * 'new' - create the object with the id $id
  347. * 'out' - produce the output for the pdf object
  348. * $options = optional, a string or array containing the various parameters for the object
  349. *
  350. * These, in conjunction with the output function are the ONLY way for output to be produced
  351. * within the pdf 'file'.
  352. */
  353. /**
  354. * Destination object, used to specify the location for the user to jump to, presently on opening
  355. *
  356. * @param $id
  357. * @param $action
  358. * @param string $options
  359. * @return string|null
  360. */
  361. protected function o_destination($id, $action, $options = '')
  362. {
  363. switch ($action) {
  364. case 'new':
  365. $this->objects[$id] = ['t' => 'destination', 'info' => []];
  366. $tmp = '';
  367. switch ($options['type']) {
  368. case 'XYZ':
  369. /** @noinspection PhpMissingBreakStatementInspection */
  370. case 'FitR':
  371. $tmp = ' ' . $options['p3'] . $tmp;
  372. case 'FitH':
  373. case 'FitV':
  374. case 'FitBH':
  375. /** @noinspection PhpMissingBreakStatementInspection */
  376. case 'FitBV':
  377. $tmp = ' ' . $options['p1'] . ' ' . $options['p2'] . $tmp;
  378. case 'Fit':
  379. case 'FitB':
  380. $tmp = $options['type'] . $tmp;
  381. $this->objects[$id]['info']['string'] = $tmp;
  382. $this->objects[$id]['info']['page'] = $options['page'];
  383. }
  384. break;
  385. case 'out':
  386. $o = &$this->objects[$id];
  387. $tmp = $o['info'];
  388. $res = "\n$id 0 obj\n" . '[' . $tmp['page'] . ' 0 R /' . $tmp['string'] . "]\nendobj";
  389. return $res;
  390. }
  391. return null;
  392. }
  393. /**
  394. * set the viewer preferences
  395. *
  396. * @param $id
  397. * @param $action
  398. * @param string|array $options
  399. * @return string|null
  400. */
  401. protected function o_viewerPreferences($id, $action, $options = '')
  402. {
  403. switch ($action) {
  404. case 'new':
  405. $this->objects[$id] = ['t' => 'viewerPreferences', 'info' => []];
  406. break;
  407. case 'add':
  408. $o = &$this->objects[$id];
  409. foreach ($options as $k => $v) {
  410. switch ($k) {
  411. // Boolean keys
  412. case 'HideToolbar':
  413. case 'HideMenubar':
  414. case 'HideWindowUI':
  415. case 'FitWindow':
  416. case 'CenterWindow':
  417. case 'DisplayDocTitle':
  418. case 'PickTrayByPDFSize':
  419. $o['info'][$k] = (bool)$v;
  420. break;
  421. // Integer keys
  422. case 'NumCopies':
  423. $o['info'][$k] = (int)$v;
  424. break;
  425. // Name keys
  426. case 'ViewArea':
  427. case 'ViewClip':
  428. case 'PrintClip':
  429. case 'PrintArea':
  430. $o['info'][$k] = (string)$v;
  431. break;
  432. // Named with limited valid values
  433. case 'NonFullScreenPageMode':
  434. if (!in_array($v, ['UseNone', 'UseOutlines', 'UseThumbs', 'UseOC'])) {
  435. break;
  436. }
  437. $o['info'][$k] = $v;
  438. break;
  439. case 'Direction':
  440. if (!in_array($v, ['L2R', 'R2L'])) {
  441. break;
  442. }
  443. $o['info'][$k] = $v;
  444. break;
  445. case 'PrintScaling':
  446. if (!in_array($v, ['None', 'AppDefault'])) {
  447. break;
  448. }
  449. $o['info'][$k] = $v;
  450. break;
  451. case 'Duplex':
  452. if (!in_array($v, ['None', 'Simplex', 'DuplexFlipShortEdge', 'DuplexFlipLongEdge'])) {
  453. break;
  454. }
  455. $o['info'][$k] = $v;
  456. break;
  457. // Integer array
  458. case 'PrintPageRange':
  459. // Cast to integer array
  460. foreach ($v as $vK => $vV) {
  461. $v[$vK] = (int)$vV;
  462. }
  463. $o['info'][$k] = array_values($v);
  464. break;
  465. }
  466. }
  467. break;
  468. case 'out':
  469. $o = &$this->objects[$id];
  470. $res = "\n$id 0 obj\n<< ";
  471. foreach ($o['info'] as $k => $v) {
  472. if (is_string($v)) {
  473. $v = '/' . $v;
  474. } elseif (is_int($v)) {
  475. $v = (string) $v;
  476. } elseif (is_bool($v)) {
  477. $v = ($v ? 'true' : 'false');
  478. } elseif (is_array($v)) {
  479. $v = '[' . implode(' ', $v) . ']';
  480. }
  481. $res .= "\n/$k $v";
  482. }
  483. $res .= "\n>>\nendobj";
  484. return $res;
  485. }
  486. return null;
  487. }
  488. /**
  489. * define the document catalog, the overall controller for the document
  490. *
  491. * @param $id
  492. * @param $action
  493. * @param string|array $options
  494. * @return string|null
  495. */
  496. protected function o_catalog($id, $action, $options = '')
  497. {
  498. if ($action !== 'new') {
  499. $o = &$this->objects[$id];
  500. }
  501. switch ($action) {
  502. case 'new':
  503. $this->objects[$id] = ['t' => 'catalog', 'info' => []];
  504. $this->catalogId = $id;
  505. break;
  506. case 'acroform':
  507. case 'outlines':
  508. case 'pages':
  509. case 'openHere':
  510. case 'names':
  511. $o['info'][$action] = $options;
  512. break;
  513. case 'viewerPreferences':
  514. if (!isset($o['info']['viewerPreferences'])) {
  515. $this->numObj++;
  516. $this->o_viewerPreferences($this->numObj, 'new');
  517. $o['info']['viewerPreferences'] = $this->numObj;
  518. }
  519. $vp = $o['info']['viewerPreferences'];
  520. $this->o_viewerPreferences($vp, 'add', $options);
  521. break;
  522. case 'out':
  523. $res = "\n$id 0 obj\n<< /Type /Catalog";
  524. foreach ($o['info'] as $k => $v) {
  525. switch ($k) {
  526. case 'outlines':
  527. $res .= "\n/Outlines $v 0 R";
  528. break;
  529. case 'pages':
  530. $res .= "\n/Pages $v 0 R";
  531. break;
  532. case 'viewerPreferences':
  533. $res .= "\n/ViewerPreferences $v 0 R";
  534. break;
  535. case 'openHere':
  536. $res .= "\n/OpenAction $v 0 R";
  537. break;
  538. case 'names':
  539. $res .= "\n/Names $v 0 R";
  540. break;
  541. case 'acroform':
  542. $res .= "\n/AcroForm $v 0 R";
  543. break;
  544. }
  545. }
  546. $res .= " >>\nendobj";
  547. return $res;
  548. }
  549. return null;
  550. }
  551. /**
  552. * object which is a parent to the pages in the document
  553. *
  554. * @param $id
  555. * @param $action
  556. * @param string $options
  557. * @return string|null
  558. */
  559. protected function o_pages($id, $action, $options = '')
  560. {
  561. if ($action !== 'new') {
  562. $o = &$this->objects[$id];
  563. }
  564. switch ($action) {
  565. case 'new':
  566. $this->objects[$id] = ['t' => 'pages', 'info' => []];
  567. $this->o_catalog($this->catalogId, 'pages', $id);
  568. break;
  569. case 'page':
  570. if (!is_array($options)) {
  571. // then it will just be the id of the new page
  572. $o['info']['pages'][] = $options;
  573. } else {
  574. // then it should be an array having 'id','rid','pos', where rid=the page to which this one will be placed relative
  575. // and pos is either 'before' or 'after', saying where this page will fit.
  576. if (isset($options['id']) && isset($options['rid']) && isset($options['pos'])) {
  577. $i = array_search($options['rid'], $o['info']['pages']);
  578. if (isset($o['info']['pages'][$i]) && $o['info']['pages'][$i] == $options['rid']) {
  579. // then there is a match
  580. // make a space
  581. switch ($options['pos']) {
  582. case 'before':
  583. $k = $i;
  584. break;
  585. case 'after':
  586. $k = $i + 1;
  587. break;
  588. default:
  589. $k = -1;
  590. break;
  591. }
  592. if ($k >= 0) {
  593. for ($j = count($o['info']['pages']) - 1; $j >= $k; $j--) {
  594. $o['info']['pages'][$j + 1] = $o['info']['pages'][$j];
  595. }
  596. $o['info']['pages'][$k] = $options['id'];
  597. }
  598. }
  599. }
  600. }
  601. break;
  602. case 'procset':
  603. $o['info']['procset'] = $options;
  604. break;
  605. case 'mediaBox':
  606. $o['info']['mediaBox'] = $options;
  607. // which should be an array of 4 numbers
  608. $this->currentPageSize = ['width' => $options[2], 'height' => $options[3]];
  609. break;
  610. case 'font':
  611. $o['info']['fonts'][] = ['objNum' => $options['objNum'], 'fontNum' => $options['fontNum']];
  612. break;
  613. case 'extGState':
  614. $o['info']['extGStates'][] = ['objNum' => $options['objNum'], 'stateNum' => $options['stateNum']];
  615. break;
  616. case 'xObject':
  617. $o['info']['xObjects'][] = ['objNum' => $options['objNum'], 'label' => $options['label']];
  618. break;
  619. case 'out':
  620. if (count($o['info']['pages'])) {
  621. $res = "\n$id 0 obj\n<< /Type /Pages\n/Kids [";
  622. foreach ($o['info']['pages'] as $v) {
  623. $res .= "$v 0 R\n";
  624. }
  625. $res .= "]\n/Count " . count($this->objects[$id]['info']['pages']);
  626. if ((isset($o['info']['fonts']) && count($o['info']['fonts'])) ||
  627. isset($o['info']['procset']) ||
  628. (isset($o['info']['extGStates']) && count($o['info']['extGStates']))
  629. ) {
  630. $res .= "\n/Resources <<";
  631. if (isset($o['info']['procset'])) {
  632. $res .= "\n/ProcSet " . $o['info']['procset'] . " 0 R";
  633. }
  634. if (isset($o['info']['fonts']) && count($o['info']['fonts'])) {
  635. $res .= "\n/Font << ";
  636. foreach ($o['info']['fonts'] as $finfo) {
  637. $res .= "\n/F" . $finfo['fontNum'] . " " . $finfo['objNum'] . " 0 R";
  638. }
  639. $res .= "\n>>";
  640. }
  641. if (isset($o['info']['xObjects']) && count($o['info']['xObjects'])) {
  642. $res .= "\n/XObject << ";
  643. foreach ($o['info']['xObjects'] as $finfo) {
  644. $res .= "\n/" . $finfo['label'] . " " . $finfo['objNum'] . " 0 R";
  645. }
  646. $res .= "\n>>";
  647. }
  648. if (isset($o['info']['extGStates']) && count($o['info']['extGStates'])) {
  649. $res .= "\n/ExtGState << ";
  650. foreach ($o['info']['extGStates'] as $gstate) {
  651. $res .= "\n/GS" . $gstate['stateNum'] . " " . $gstate['objNum'] . " 0 R";
  652. }
  653. $res .= "\n>>";
  654. }
  655. $res .= "\n>>";
  656. if (isset($o['info']['mediaBox'])) {
  657. $tmp = $o['info']['mediaBox'];
  658. $res .= "\n/MediaBox [" . sprintf(
  659. '%.3F %.3F %.3F %.3F',
  660. $tmp[0],
  661. $tmp[1],
  662. $tmp[2],
  663. $tmp[3]
  664. ) . ']';
  665. }
  666. }
  667. $res .= "\n >>\nendobj";
  668. } else {
  669. $res = "\n$id 0 obj\n<< /Type /Pages\n/Count 0\n>>\nendobj";
  670. }
  671. return $res;
  672. }
  673. return null;
  674. }
  675. /**
  676. * define the outlines in the doc, empty for now
  677. *
  678. * @param $id
  679. * @param $action
  680. * @param string $options
  681. * @return string|null
  682. */
  683. protected function o_outlines($id, $action, $options = '')
  684. {
  685. if ($action !== 'new') {
  686. $o = &$this->objects[$id];
  687. }
  688. switch ($action) {
  689. case 'new':
  690. $this->objects[$id] = ['t' => 'outlines', 'info' => ['outlines' => []]];
  691. $this->o_catalog($this->catalogId, 'outlines', $id);
  692. break;
  693. case 'outline':
  694. $o['info']['outlines'][] = $options;
  695. break;
  696. case 'out':
  697. if (count($o['info']['outlines'])) {
  698. $res = "\n$id 0 obj\n<< /Type /Outlines /Kids [";
  699. foreach ($o['info']['outlines'] as $v) {
  700. $res .= "$v 0 R ";
  701. }
  702. $res .= "] /Count " . count($o['info']['outlines']) . " >>\nendobj";
  703. } else {
  704. $res = "\n$id 0 obj\n<< /Type /Outlines /Count 0 >>\nendobj";
  705. }
  706. return $res;
  707. }
  708. return null;
  709. }
  710. /**
  711. * an object to hold the font description
  712. *
  713. * @param $id
  714. * @param $action
  715. * @param string|array $options
  716. * @return string|null
  717. * @throws FontNotFoundException
  718. */
  719. protected function o_font($id, $action, $options = '')
  720. {
  721. if ($action !== 'new') {
  722. $o = &$this->objects[$id];
  723. }
  724. switch ($action) {
  725. case 'new':
  726. $this->objects[$id] = [
  727. 't' => 'font',
  728. 'info' => [
  729. 'name' => $options['name'],
  730. 'fontFileName' => $options['fontFileName'],
  731. 'SubType' => 'Type1',
  732. 'isSubsetting' => $options['isSubsetting']
  733. ]
  734. ];
  735. $fontNum = $this->numFonts;
  736. $this->objects[$id]['info']['fontNum'] = $fontNum;
  737. // deal with the encoding and the differences
  738. if (isset($options['differences'])) {
  739. // then we'll need an encoding dictionary
  740. $this->numObj++;
  741. $this->o_fontEncoding($this->numObj, 'new', $options);
  742. $this->objects[$id]['info']['encodingDictionary'] = $this->numObj;
  743. } else {
  744. if (isset($options['encoding'])) {
  745. // we can specify encoding here
  746. switch ($options['encoding']) {
  747. case 'WinAnsiEncoding':
  748. case 'MacRomanEncoding':
  749. case 'MacExpertEncoding':
  750. $this->objects[$id]['info']['encoding'] = $options['encoding'];
  751. break;
  752. case 'none':
  753. break;
  754. default:
  755. $this->objects[$id]['info']['encoding'] = 'WinAnsiEncoding';
  756. break;
  757. }
  758. } else {
  759. $this->objects[$id]['info']['encoding'] = 'WinAnsiEncoding';
  760. }
  761. }
  762. if ($this->fonts[$options['fontFileName']]['isUnicode']) {
  763. // For Unicode fonts, we need to incorporate font data into
  764. // sub-sections that are linked from the primary font section.
  765. // Look at o_fontGIDtoCID and o_fontDescendentCID functions
  766. // for more information.
  767. //
  768. // All of this code is adapted from the excellent changes made to
  769. // transform FPDF to TCPDF (http://tcpdf.sourceforge.net/)
  770. $toUnicodeId = ++$this->numObj;
  771. $this->o_toUnicode($toUnicodeId, 'new');
  772. $this->objects[$id]['info']['toUnicode'] = $toUnicodeId;
  773. $cidFontId = ++$this->numObj;
  774. $this->o_fontDescendentCID($cidFontId, 'new', $options);
  775. $this->objects[$id]['info']['cidFont'] = $cidFontId;
  776. }
  777. // also tell the pages node about the new font
  778. $this->o_pages($this->currentNode, 'font', ['fontNum' => $fontNum, 'objNum' => $id]);
  779. break;
  780. case 'add':
  781. $font_options = $this->processFont($id, $o['info']);
  782. if ($font_options !== false) {
  783. foreach ($font_options as $k => $v) {
  784. switch ($k) {
  785. case 'BaseFont':
  786. $o['info']['name'] = $v;
  787. break;
  788. case 'FirstChar':
  789. case 'LastChar':
  790. case 'Widths':
  791. case 'FontDescriptor':
  792. case 'SubType':
  793. $this->addMessage('o_font ' . $k . " : " . $v);
  794. $o['info'][$k] = $v;
  795. break;
  796. }
  797. }
  798. // pass values down to descendent font
  799. if (isset($o['info']['cidFont'])) {
  800. $this->o_fontDescendentCID($o['info']['cidFont'], 'add', $font_options);
  801. }
  802. }
  803. break;
  804. case 'out':
  805. if ($this->fonts[$this->objects[$id]['info']['fontFileName']]['isUnicode']) {
  806. // For Unicode fonts, we need to incorporate font data into
  807. // sub-sections that are linked from the primary font section.
  808. // Look at o_fontGIDtoCID and o_fontDescendentCID functions
  809. // for more information.
  810. //
  811. // All of this code is adapted from the excellent changes made to
  812. // transform FPDF to TCPDF (http://tcpdf.sourceforge.net/)
  813. $res = "\n$id 0 obj\n<</Type /Font\n/Subtype /Type0\n";
  814. $res .= "/BaseFont /" . $o['info']['name'] . "\n";
  815. // The horizontal identity mapping for 2-byte CIDs; may be used
  816. // with CIDFonts using any Registry, Ordering, and Supplement values.
  817. $res .= "/Encoding /Identity-H\n";
  818. $res .= "/DescendantFonts [" . $o['info']['cidFont'] . " 0 R]\n";
  819. $res .= "/ToUnicode " . $o['info']['toUnicode'] . " 0 R\n";
  820. $res .= ">>\n";
  821. $res .= "endobj";
  822. } else {
  823. $res = "\n$id 0 obj\n<< /Type /Font\n/Subtype /" . $o['info']['SubType'] . "\n";
  824. $res .= "/Name /F" . $o['info']['fontNum'] . "\n";
  825. $res .= "/BaseFont /" . $o['info']['name'] . "\n";
  826. if (isset($o['info']['encodingDictionary'])) {
  827. // then place a reference to the dictionary
  828. $res .= "/Encoding " . $o['info']['encodingDictionary'] . " 0 R\n";
  829. } else {
  830. if (isset($o['info']['encoding'])) {
  831. // use the specified encoding
  832. $res .= "/Encoding /" . $o['info']['encoding'] . "\n";
  833. }
  834. }
  835. if (isset($o['info']['FirstChar'])) {
  836. $res .= "/FirstChar " . $o['info']['FirstChar'] . "\n";
  837. }
  838. if (isset($o['info']['LastChar'])) {
  839. $res .= "/LastChar " . $o['info']['LastChar'] . "\n";
  840. }
  841. if (isset($o['info']['Widths'])) {
  842. $res .= "/Widths " . $o['info']['Widths'] . " 0 R\n";
  843. }
  844. if (isset($o['info']['FontDescriptor'])) {
  845. $res .= "/FontDescriptor " . $o['info']['FontDescriptor'] . " 0 R\n";
  846. }
  847. $res .= ">>\n";
  848. $res .= "endobj";
  849. }
  850. return $res;
  851. }
  852. return null;
  853. }
  854. protected function getFontSubsettingTag(array $font): string
  855. {
  856. // convert font num to hexavigesimal numeral system letters A - Z only
  857. $base_26 = strtoupper(base_convert($font['fontNum'], 10, 26));
  858. for ($i = 0; $i < strlen($base_26); $i++) {
  859. $char = $base_26[$i];
  860. if ($char <= "9") {
  861. $base_26[$i] = chr(65 + intval($char));
  862. } else {
  863. $base_26[$i] = chr(ord($char) + 10);
  864. }
  865. }
  866. return 'SUB' . str_pad($base_26,3 , 'A', STR_PAD_LEFT);
  867. }
  868. /**
  869. * @param int $fontObjId
  870. * @param array $object_info
  871. * @return array|false
  872. * @throws FontNotFoundException
  873. */
  874. private function processFont(int $fontObjId, array $object_info)
  875. {
  876. $fontFileName = $object_info['fontFileName'];
  877. if (!isset($this->fonts[$fontFileName])) {
  878. return false;
  879. }
  880. $font = &$this->fonts[$fontFileName];
  881. $fileSuffix = $font['fileSuffix'];
  882. $fileSuffixLower = strtolower($font['fileSuffix']);
  883. $fbfile = "$fontFileName.$fileSuffix";
  884. $isTtfFont = $fileSuffixLower === 'ttf';
  885. $isPfbFont = $fileSuffixLower === 'pfb';
  886. $this->addMessage('selectFont: checking for - ' . $fbfile);
  887. if (!$fileSuffix) {
  888. $this->addMessage(
  889. 'selectFont: pfb or ttf file not found, ok if this is one of the 14 standard fonts'
  890. );
  891. return false;
  892. } else {
  893. $adobeFontName = isset($font['PostScriptName']) ? $font['PostScriptName'] : $font['FontName'];
  894. // $fontObj = $this->numObj;
  895. $this->addMessage("selectFont: adding font file - $fbfile - $adobeFontName");
  896. // find the array of font widths, and put that into an object.
  897. $firstChar = -1;
  898. $lastChar = 0;
  899. $widths = [];
  900. $cid_widths = [];
  901. foreach ($font['C'] as $num => $d) {
  902. if (intval($num) > 0 || $num == '0') {
  903. if (!$font['isUnicode']) {
  904. // With Unicode, widths array isn't used
  905. if ($lastChar > 0 && $num > $lastChar + 1) {
  906. for ($i = $lastChar + 1; $i < $num; $i++) {
  907. $widths[] = 0;
  908. }
  909. }
  910. }
  911. $widths[] = $d;
  912. if ($font['isUnicode']) {
  913. $cid_widths[$num] = $d;
  914. }
  915. if ($firstChar == -1) {
  916. $firstChar = $num;
  917. }
  918. $lastChar = $num;
  919. }
  920. }
  921. // also need to adjust the widths for the differences array
  922. if (isset($object['differences'])) {
  923. foreach ($object['differences'] as $charNum => $charName) {
  924. if ($charNum > $lastChar) {
  925. if (!$object['isUnicode']) {
  926. // With Unicode, widths array isn't used
  927. for ($i = $lastChar + 1; $i <= $charNum; $i++) {
  928. $widths[] = 0;
  929. }
  930. }
  931. $lastChar = $charNum;
  932. }
  933. if (isset($font['C'][$charName])) {
  934. $widths[$charNum - $firstChar] = $font['C'][$charName];
  935. if ($font['isUnicode']) {
  936. $cid_widths[$charName] = $font['C'][$charName];
  937. }
  938. }
  939. }
  940. }
  941. if ($font['isUnicode']) {
  942. $font['CIDWidths'] = $cid_widths;
  943. }
  944. $this->addMessage('selectFont: FirstChar = ' . $firstChar);
  945. $this->addMessage('selectFont: LastChar = ' . $lastChar);
  946. $widthid = -1;
  947. if (!$font['isUnicode']) {
  948. // With Unicode, widths array isn't used
  949. $this->numObj++;
  950. $this->o_contents($this->numObj, 'new', 'raw');
  951. $this->objects[$this->numObj]['c'] .= '[' . implode(' ', $widths) . ']';
  952. $widthid = $this->numObj;
  953. }
  954. $missing_width = 500;
  955. $stemV = 70;
  956. if (isset($font['MissingWidth'])) {
  957. $missing_width = $font['MissingWidth'];
  958. }
  959. if (isset($font['StdVW'])) {
  960. $stemV = $font['StdVW'];
  961. } else {
  962. if (isset($font['Weight']) && preg_match('!(bold|black)!i', $font['Weight'])) {
  963. $stemV = 120;
  964. }
  965. }
  966. // load the pfb file, and put that into an object too.
  967. // note that pdf supports only binary format type 1 font files, though there is a
  968. // simple utility to convert them from pfa to pfb.
  969. if (!$font['isSubsetting']) {
  970. $data = file_get_contents($fbfile);
  971. } else {
  972. $adobeFontName = $this->getFontSubsettingTag($font) . '+' . $adobeFontName;
  973. $this->stringSubsets[$fontFileName][] = 32; // Force space if not in yet
  974. $subset = $this->stringSubsets[$fontFileName];
  975. sort($subset);
  976. // Load font
  977. $font_obj = Font::load($fbfile);
  978. $font_obj->parse();
  979. // Define subset
  980. $font_obj->setSubset($subset);
  981. $font_obj->reduce();
  982. // Write new font
  983. $tmp_name = $this->tmp . "/" . basename($fbfile) . ".tmp." . uniqid();
  984. touch($tmp_name);
  985. $font_obj->open($tmp_name, BinaryStream::modeReadWrite);
  986. $font_obj->encode(["OS/2"]);
  987. $font_obj->close();
  988. // Parse the new font to get cid2gid and widths
  989. $font_obj = Font::load($tmp_name);
  990. // Find Unicode char map table
  991. $subtable = null;
  992. foreach ($font_obj->getData("cmap", "subtables") as $_subtable) {
  993. if ($_subtable["platformID"] == 0 || $_subtable["platformID"] == 3 && $_subtable["platformSpecificID"] == 1) {
  994. $subtable = $_subtable;
  995. break;
  996. }
  997. }
  998. if ($subtable) {
  999. $glyphIndexArray = $subtable["glyphIndexArray"];
  1000. $hmtx = $font_obj->getData("hmtx");
  1001. unset($glyphIndexArray[0xFFFF]);
  1002. $cidtogid = str_pad('', max(array_keys($glyphIndexArray)) * 2 + 1, "\x00");
  1003. $font['CIDWidths'] = [];
  1004. foreach ($glyphIndexArray as $cid => $gid) {
  1005. if ($cid >= 0 && $cid < 0xFFFF && $gid) {
  1006. $cidtogid[$cid * 2] = chr($gid >> 8);
  1007. $cidtogid[$cid * 2 + 1] = chr($gid & 0xFF);
  1008. }
  1009. $width = $font_obj->normalizeFUnit(isset($hmtx[$gid]) ? $hmtx[$gid][0] : $hmtx[0][0]);
  1010. $font['CIDWidths'][$cid] = $width;
  1011. }
  1012. $font['CIDtoGID'] = base64_encode(gzcompress($cidtogid));
  1013. $font['CIDtoGID_Compressed'] = true;
  1014. $data = file_get_contents($tmp_name);
  1015. } else {
  1016. $data = file_get_contents($fbfile);
  1017. }
  1018. $font_obj->close();
  1019. unlink($tmp_name);
  1020. }
  1021. // create the font descriptor
  1022. $this->numObj++;
  1023. $fontDescriptorId = $this->numObj;
  1024. $this->numObj++;
  1025. $pfbid = $this->numObj;
  1026. // determine flags (more than a little flakey, hopefully will not matter much)
  1027. $flags = 0;
  1028. if ($font['ItalicAngle'] != 0) {
  1029. $flags += pow(2, 6);
  1030. }
  1031. if ($font['IsFixedPitch'] === 'true') {
  1032. $flags += 1;
  1033. }
  1034. $flags += pow(2, 5); // assume non-sybolic
  1035. $list = [
  1036. 'Ascent' => 'Ascender',
  1037. 'CapHeight' => 'Ascender', //FIXME: php-font-lib is not grabbing this value, so we'll fake it and use the Ascender value // 'CapHeight'
  1038. 'MissingWidth' => 'MissingWidth',
  1039. 'Descent' => 'Descender',
  1040. 'FontBBox' => 'FontBBox',
  1041. 'ItalicAngle' => 'ItalicAngle'
  1042. ];
  1043. $fdopt = [
  1044. 'Flags' => $flags,
  1045. 'FontName' => $adobeFontName,
  1046. 'StemV' => $stemV
  1047. ];
  1048. foreach ($list as $k => $v) {
  1049. if (isset($font[$v])) {
  1050. $fdopt[$k] = $font[$v];
  1051. }
  1052. }
  1053. if ($isPfbFont) {
  1054. $fdopt['FontFile'] = $pfbid;
  1055. } elseif ($isTtfFont) {
  1056. $fdopt['FontFile2'] = $pfbid;
  1057. }
  1058. $this->o_fontDescriptor($fontDescriptorId, 'new', $fdopt);
  1059. // embed the font program
  1060. $this->o_contents($this->numObj, 'new');
  1061. $this->objects[$pfbid]['c'] .= $data;
  1062. // determine the cruicial lengths within this file
  1063. if ($isPfbFont) {
  1064. $l1 = strpos($data, 'eexec') + 6;
  1065. $l2 = strpos($data, '00000000') - $l1;
  1066. $l3 = mb_strlen($data, '8bit') - $l2 - $l1;
  1067. $this->o_contents(
  1068. $this->numObj,
  1069. 'add',
  1070. ['Length1' => $l1, 'Length2' => $l2, 'Length3' => $l3]
  1071. );
  1072. } elseif ($isTtfFont) {
  1073. $l1 = mb_strlen($data, '8bit');
  1074. $this->o_contents($this->numObj, 'add', ['Length1' => $l1]);
  1075. }
  1076. // tell the font object about all this new stuff
  1077. $options = [
  1078. 'BaseFont' => $adobeFontName,
  1079. 'MissingWidth' => $missing_width,
  1080. 'Widths' => $widthid,
  1081. 'FirstChar' => $firstChar,
  1082. 'LastChar' => $lastChar,
  1083. 'FontDescriptor' => $fontDescriptorId
  1084. ];
  1085. if ($isTtfFont) {
  1086. $options['SubType'] = 'TrueType';
  1087. }
  1088. $this->addMessage("adding extra info to font.($fontObjId)");
  1089. foreach ($options as $fk => $fv) {
  1090. $this->addMessage("$fk : $fv");
  1091. }
  1092. }
  1093. return $options;
  1094. }
  1095. /**
  1096. * A toUnicode section, needed for unicode fonts
  1097. *
  1098. * @param $id
  1099. * @param $action
  1100. * @return null|string
  1101. */
  1102. protected function o_toUnicode($id, $action)
  1103. {
  1104. switch ($action) {
  1105. case 'new':
  1106. $this->objects[$id] = [
  1107. 't' => 'toUnicode'
  1108. ];
  1109. break;
  1110. case 'add':
  1111. break;
  1112. case 'out':
  1113. $ordering = 'UCS';
  1114. $registry = 'Adobe';
  1115. if ($this->encrypted) {
  1116. $this->encryptInit($id);
  1117. $ordering = $this->ARC4($ordering);
  1118. $registry = $this->filterText($this->ARC4($registry), false, false);
  1119. }
  1120. $stream = <<<EOT
  1121. /CIDInit /ProcSet findresource begin
  1122. 12 dict begin
  1123. begincmap
  1124. /CIDSystemInfo
  1125. <</Registry ($registry)
  1126. /Ordering ($ordering)
  1127. /Supplement 0
  1128. >> def
  1129. /CMapName /Adobe-Identity-UCS def
  1130. /CMapType 2 def
  1131. 1 begincodespacerange
  1132. <0000> <FFFF>
  1133. endcodespacerange
  1134. 1 beginbfrange
  1135. <0000> <FFFF> <0000>
  1136. endbfrange
  1137. endcmap
  1138. CMapName currentdict /CMap defineresource pop
  1139. end
  1140. end
  1141. EOT;
  1142. $res = "\n$id 0 obj\n";
  1143. $res .= "<</Length " . mb_strlen($stream, '8bit') . " >>\n";
  1144. $res .= "stream\n" . $stream . "\nendstream" . "\nendobj";;
  1145. return $res;
  1146. }
  1147. return null;
  1148. }
  1149. /**
  1150. * a font descriptor, needed for including additional fonts
  1151. *
  1152. * @param $id
  1153. * @param $action
  1154. * @param string $options
  1155. * @return null|string
  1156. */
  1157. protected function o_fontDescriptor($id, $action, $options = '')
  1158. {
  1159. if ($action !== 'new') {
  1160. $o = &$this->objects[$id];
  1161. }
  1162. switch ($action) {
  1163. case 'new':
  1164. $this->objects[$id] = ['t' => 'fontDescriptor', 'info' => $options];
  1165. break;
  1166. case 'out':
  1167. $res = "\n$id 0 obj\n<< /Type /FontDescriptor\n";
  1168. foreach ($o['info'] as $label => $value) {
  1169. switch ($label) {
  1170. case 'Ascent':
  1171. case 'CapHeight':
  1172. case 'Descent':
  1173. case 'Flags':
  1174. case 'ItalicAngle':
  1175. case 'StemV':
  1176. case 'AvgWidth':
  1177. case 'Leading':
  1178. case 'MaxWidth':
  1179. case 'MissingWidth':
  1180. case 'StemH':
  1181. case 'XHeight':
  1182. case 'CharSet':
  1183. if (mb_strlen($value, '8bit')) {
  1184. $res .= "/$label $value\n";
  1185. }
  1186. break;
  1187. case 'FontFile':
  1188. case 'FontFile2':
  1189. case 'FontFile3':
  1190. $res .= "/$label $value 0 R\n";
  1191. break;
  1192. case 'FontBBox':
  1193. $res .= "/$label [$value[0] $value[1] $value[2] $value[3]]\n";
  1194. break;
  1195. case 'FontName':
  1196. $res .= "/$label /$value\n";
  1197. break;
  1198. }
  1199. }
  1200. $res .= ">>\nendobj";
  1201. return $res;
  1202. }
  1203. return null;
  1204. }
  1205. /**
  1206. * the font encoding
  1207. *
  1208. * @param $id
  1209. * @param $action
  1210. * @param string $options
  1211. * @return null|string
  1212. */
  1213. protected function o_fontEncoding($id, $action, $options = '')
  1214. {
  1215. if ($action !== 'new') {
  1216. $o = &$this->objects[$id];
  1217. }
  1218. switch ($action) {
  1219. case 'new':
  1220. // the options array should contain 'differences' and maybe 'encoding'
  1221. $this->objects[$id] = ['t' => 'fontEncoding', 'info' => $options];
  1222. break;
  1223. case 'out':
  1224. $res = "\n$id 0 obj\n<< /Type /Encoding\n";
  1225. if (!isset($o['info']['encoding'])) {
  1226. $o['info']['encoding'] = 'WinAnsiEncoding';
  1227. }
  1228. if ($o['info']['encoding'] !== 'none') {
  1229. $res .= "/BaseEncoding /" . $o['info']['encoding'] . "\n";
  1230. }
  1231. $res .= "/Differences \n[";
  1232. $onum = -100;
  1233. foreach ($o['info']['differences'] as $num => $label) {
  1234. if ($num != $onum + 1) {
  1235. // we cannot make use of consecutive numbering
  1236. $res .= "\n$num /$label";
  1237. } else {
  1238. $res .= " /$label";
  1239. }
  1240. $onum = $num;
  1241. }
  1242. $res .= "\n]\n>>\nendobj";
  1243. return $res;
  1244. }
  1245. return null;
  1246. }
  1247. /**
  1248. * a descendent cid font, needed for unicode fonts
  1249. *
  1250. * @param $id
  1251. * @param $action
  1252. * @param string|array $options
  1253. * @return null|string
  1254. */
  1255. protected function o_fontDescendentCID($id, $action, $options = '')
  1256. {
  1257. if ($action !== 'new') {
  1258. $o = &$this->objects[$id];
  1259. }
  1260. switch ($action) {
  1261. case 'new':
  1262. $this->objects[$id] = ['t' => 'fontDescendentCID', 'info' => $options];
  1263. // we need a CID system info section
  1264. $cidSystemInfoId = ++$this->numObj;
  1265. $this->o_cidSystemInfo($cidSystemInfoId, 'new');
  1266. $this->objects[$id]['info']['cidSystemInfo'] = $cidSystemInfoId;
  1267. // and a CID to GID map
  1268. $cidToGidMapId = ++$this->numObj;
  1269. $this->o_fontGIDtoCIDMap($cidToGidMapId, 'new', $options);
  1270. $this->objects[$id]['info']['cidToGidMap'] = $cidToGidMapId;
  1271. break;
  1272. case 'add':
  1273. foreach ($options as $k => $v) {
  1274. switch ($k) {
  1275. case 'BaseFont':
  1276. $o['info']['name'] = $v;
  1277. break;
  1278. case 'FirstChar':
  1279. case 'LastChar':
  1280. case 'MissingWidth':
  1281. case 'FontDescriptor':
  1282. case 'SubType':
  1283. $this->addMessage("o_fontDescendentCID $k : $v");
  1284. $o['info'][$k] = $v;
  1285. break;
  1286. }
  1287. }
  1288. // pass values down to cid to gid map
  1289. $this->o_fontGIDtoCIDMap($o['info']['cidToGidMap'], 'add', $options);
  1290. break;
  1291. case 'out':
  1292. $res = "\n$id 0 obj\n";
  1293. $res .= "<</Type /Font\n";
  1294. $res .= "/Subtype /CIDFontType2\n";
  1295. $res .= "/BaseFont /" . $o['info']['name'] . "\n";
  1296. $res .= "/CIDSystemInfo " . $o['info']['cidSystemInfo'] . " 0 R\n";
  1297. // if (isset($o['info']['FirstChar'])) {
  1298. // $res.= "/FirstChar ".$o['info']['FirstChar']."\n";
  1299. // }
  1300. // if (isset($o['info']['LastChar'])) {
  1301. // $res.= "/LastChar ".$o['info']['LastChar']."\n";
  1302. // }
  1303. if (isset($o['info']['FontDescriptor'])) {
  1304. $res .= "/FontDescriptor " . $o['info']['FontDescriptor'] . " 0 R\n";
  1305. }
  1306. if (isset($o['info']['MissingWidth'])) {
  1307. $res .= "/DW " . $o['info']['MissingWidth'] . "\n";
  1308. }
  1309. if (isset($o['info']['fontFileName']) && isset($this->fonts[$o['info']['fontFileName']]['CIDWidths'])) {
  1310. $cid_widths = &$this->fonts[$o['info']['fontFileName']]['CIDWidths'];
  1311. $w = '';
  1312. foreach ($cid_widths as $cid => $width) {
  1313. $w .= "$cid [$width] ";
  1314. }
  1315. $res .= "/W [$w]\n";
  1316. }
  1317. $res .= "/CIDToGIDMap " . $o['info']['cidToGidMap'] . " 0 R\n";
  1318. $res .= ">>\n";
  1319. $res .= "endobj";
  1320. return $res;
  1321. }
  1322. return null;
  1323. }
  1324. /**
  1325. * CID system info section, needed for unicode fonts
  1326. *
  1327. * @param $id
  1328. * @param $action
  1329. * @return null|string
  1330. */
  1331. protected function o_cidSystemInfo($id, $action)
  1332. {
  1333. switch ($action) {
  1334. case 'new':
  1335. $this->objects[$id] = [
  1336. 't' => 'cidSystemInfo'
  1337. ];
  1338. break;
  1339. case 'add':
  1340. break;
  1341. case 'out':
  1342. $ordering = 'UCS';
  1343. $registry = 'Adobe';
  1344. if ($this->encrypted) {
  1345. $this->encryptInit($id);
  1346. $ordering = $this->ARC4($ordering);
  1347. $registry = $this->ARC4($registry);
  1348. }
  1349. $res = "\n$id 0 obj\n";
  1350. $res .= '<</Registry (' . $registry . ")\n"; // A string identifying an issuer of character collections
  1351. $res .= '/Ordering (' . $ordering . ")\n"; // A string that uniquely names a character collection issued by a specific registry
  1352. $res .= "/Supplement 0\n"; // The supplement number of the character collection.
  1353. $res .= ">>";
  1354. $res .= "\nendobj";
  1355. return $res;
  1356. }
  1357. return null;
  1358. }
  1359. /**
  1360. * a font glyph to character map, needed for unicode fonts
  1361. *
  1362. * @param $id
  1363. * @param $action
  1364. * @param string $options
  1365. * @return null|string
  1366. */
  1367. protected function o_fontGIDtoCIDMap($id, $action, $options = '')
  1368. {
  1369. if ($action !== 'new') {
  1370. $o = &$this->objects[$id];
  1371. }
  1372. switch ($action) {
  1373. case 'new':
  1374. $this->objects[$id] = ['t' => 'fontGIDtoCIDMap', 'info' => $options];
  1375. break;
  1376. case 'out':
  1377. $res = "\n$id 0 obj\n";
  1378. $fontFileName = $o['info']['fontFileName'];
  1379. $tmp = $this->fonts[$fontFileName]['CIDtoGID'] = base64_decode($this->fonts[$fontFileName]['CIDtoGID']);
  1380. $compressed = isset($this->fonts[$fontFileName]['CIDtoGID_Compressed']) &&
  1381. $this->fonts[$fontFileName]['CIDtoGID_Compressed'];
  1382. if (!$compressed && isset($o['raw'])) {
  1383. $res .= $tmp;
  1384. } else {
  1385. $res .= "<<";
  1386. if (!$compressed && $this->compressionReady && $this->options['compression']) {
  1387. // then implement ZLIB based compression on this content stream
  1388. $compressed = true;
  1389. $tmp = gzcompress($tmp, 6);
  1390. }
  1391. if ($compressed) {
  1392. $res .= "\n/Filter /FlateDecode";
  1393. }
  1394. if ($this->encrypted) {
  1395. $this->encryptInit($id);
  1396. $tmp = $this->ARC4($tmp);
  1397. }
  1398. $res .= "\n/Length " . mb_strlen($tmp, '8bit') . ">>\nstream\n$tmp\nendstream";
  1399. }
  1400. $res .= "\nendobj";
  1401. return $res;
  1402. }
  1403. return null;
  1404. }
  1405. /**
  1406. * the document procset, solves some problems with printing to old PS printers
  1407. *
  1408. * @param $id
  1409. * @param $action
  1410. * @param string $options
  1411. * @return null|string
  1412. */
  1413. protected function o_procset($id, $action, $options = '')
  1414. {
  1415. if ($action !== 'new') {
  1416. $o = &$this->objects[$id];
  1417. }
  1418. switch ($action) {
  1419. case 'new':
  1420. $this->objects[$id] = ['t' => 'procset', 'info' => ['PDF' => 1, 'Text' => 1]];
  1421. $this->o_pages($this->currentNode, 'procset', $id);
  1422. $this->procsetObjectId = $id;
  1423. break;
  1424. case 'add':
  1425. // this is to add new items to the procset list, despite the fact that this is considered
  1426. // obsolete, the items are required for printing to some postscript printers
  1427. switch ($options) {
  1428. case 'ImageB':
  1429. case 'ImageC':
  1430. case 'ImageI':
  1431. $o['info'][$options] = 1;
  1432. break;
  1433. }
  1434. break;
  1435. case 'out':
  1436. $res = "\n$id 0 obj\n[";
  1437. foreach ($o['info'] as $label => $val) {
  1438. $res .= "/$label ";
  1439. }
  1440. $res .= "]\nendobj";
  1441. return $res;
  1442. }
  1443. return null;
  1444. }
  1445. /**
  1446. * define the document information
  1447. *
  1448. * @param $id
  1449. * @param $action
  1450. * @param string $options
  1451. * @return null|string
  1452. */
  1453. protected function o_info($id, $action, $options = '')
  1454. {
  1455. switch ($action) {
  1456. case 'new':
  1457. $this->infoObject = $id;
  1458. $date = 'D:' . @date('Ymd');
  1459. $this->objects[$id] = [
  1460. 't' => 'info',
  1461. 'info' => [
  1462. 'Producer' => 'CPDF (dompdf)',
  1463. 'CreationDate' => $date
  1464. ]
  1465. ];
  1466. break;
  1467. case 'Title':
  1468. case 'Author':
  1469. case 'Subject':
  1470. case 'Keywords':
  1471. case 'Creator':
  1472. case 'Producer':
  1473. case 'CreationDate':
  1474. case 'ModDate':
  1475. case 'Trapped':
  1476. $this->objects[$id]['info'][$action] = $options;
  1477. break;
  1478. case 'out':
  1479. $encrypted = $this->encrypted;
  1480. if ($encrypted) {
  1481. $this->encryptInit($id);
  1482. }
  1483. $res = "\n$id 0 obj\n<<\n";
  1484. $o = &$this->objects[$id];
  1485. foreach ($o['info'] as $k => $v) {
  1486. $res .= "/$k (";
  1487. // dates must be outputted as-is, without Unicode transformations
  1488. if ($k !== 'CreationDate' && $k !== 'ModDate') {
  1489. $v = $this->filterText($v, true, false);
  1490. }
  1491. if ($encrypted) {
  1492. $v = $this->ARC4($v);
  1493. }
  1494. $res .= $v;
  1495. $res .= ")\n";
  1496. }
  1497. $res .= ">>\nendobj";
  1498. return $res;
  1499. }
  1500. return null;
  1501. }
  1502. /**
  1503. * an action object, used to link to URLS initially
  1504. *
  1505. * @param $id
  1506. * @param $action
  1507. * @param string $options
  1508. * @return null|string
  1509. */
  1510. protected function o_action($id, $action, $options = '')
  1511. {
  1512. if ($action !== 'new') {
  1513. $o = &$this->objects[$id];
  1514. }
  1515. switch ($action) {
  1516. case 'new':
  1517. if (is_array($options)) {
  1518. $this->objects[$id] = ['t' => 'action', 'info' => $options, 'type' => $options['type']];
  1519. } else {
  1520. // then assume a URI action
  1521. $this->objects[$id] = ['t' => 'action', 'info' => $options, 'type' => 'URI'];
  1522. }
  1523. break;
  1524. case 'out':
  1525. if ($this->encrypted) {
  1526. $this->encryptInit($id);
  1527. }
  1528. $res = "\n$id 0 obj\n<< /Type /Action";
  1529. switch ($o['type']) {
  1530. case 'ilink':
  1531. if (!isset($this->destinations[(string)$o['info']['label']])) {
  1532. break;
  1533. }
  1534. // there will be an 'label' setting, this is the name of the destination
  1535. $res .= "\n/S /GoTo\n/D " . $this->destinations[(string)$o['info']['label']] . " 0 R";
  1536. break;
  1537. case 'URI':
  1538. $res .= "\n/S /URI\n/URI (";
  1539. if ($this->encrypted) {
  1540. $res .= $this->filterText($this->ARC4($o['info']), false, false);
  1541. } else {
  1542. $res .= $this->filterText($o['info'], false, false);
  1543. }
  1544. $res .= ")";
  1545. break;
  1546. }
  1547. $res .= "\n>>\nendobj";
  1548. return $res;
  1549. }
  1550. return null;
  1551. }
  1552. /**
  1553. * an annotation object, this will add an annotation to the current page.
  1554. * initially will support just link annotations
  1555. *
  1556. * @param $id
  1557. * @param $action
  1558. * @param string $options
  1559. * @return null|string
  1560. */
  1561. protected function o_annotation($id, $action, $options = '')
  1562. {
  1563. if ($action !== 'new') {
  1564. $o = &$this->objects[$id];
  1565. }
  1566. switch ($action) {
  1567. case 'new':
  1568. // add the annotation to the current page
  1569. $pageId = $this->currentPage;
  1570. $this->o_page($pageId, 'annot', $id);
  1571. // and add the action object which is going to be required
  1572. switch ($options['type']) {
  1573. case 'link':
  1574. $this->objects[$id] = ['t' => 'annotation', 'info' => $options];
  1575. $this->numObj++;
  1576. $this->o_action($this->numObj, 'new', $options['url']);
  1577. $this->objects[$id]['info']['actionId'] = $this->numObj;
  1578. break;
  1579. case 'ilink':
  1580. // this is to a named internal link
  1581. $label = $options['label'];
  1582. $this->objects[$id] = ['t' => 'annotation', 'info' => $options];
  1583. $this->numObj++;
  1584. $this->o_action($this->numObj, 'new', ['type' => 'ilink', 'label' => $label]);
  1585. $this->objects[$id]['info']['actionId'] = $this->numObj;
  1586. break;
  1587. }
  1588. break;
  1589. case 'out':
  1590. $res = "\n$id 0 obj\n<< /Type /Annot";
  1591. switch ($o['info']['type']) {
  1592. case 'link':
  1593. case 'ilink':
  1594. $res .= "\n/Subtype /Link";
  1595. break;
  1596. }
  1597. $res .= "\n/A " . $o['info']['actionId'] . " 0 R";
  1598. $res .= "\n/Border [0 0 0]";
  1599. $res .= "\n/H /I";
  1600. $res .= "\n/Rect [ ";
  1601. foreach ($o['info']['rect'] as $v) {
  1602. $res .= sprintf("%.4F ", $v);
  1603. }
  1604. $res .= "]";
  1605. $res .= "\n>>\nendobj";
  1606. return $res;
  1607. }
  1608. return null;
  1609. }
  1610. /**
  1611. * a page object, it also creates a contents object to hold its contents
  1612. *
  1613. * @param $id
  1614. * @param $action
  1615. * @param string $options
  1616. * @return null|string
  1617. */
  1618. protected function o_page($id, $action, $options = '')
  1619. {
  1620. if ($action !== 'new') {
  1621. $o = &$this->objects[$id];
  1622. }
  1623. switch ($action) {
  1624. case 'new':
  1625. $this->numPages++;
  1626. $this->objects[$id] = [
  1627. 't' => 'page',
  1628. 'info' => [
  1629. 'parent' => $this->currentNode,
  1630. 'pageNum' => $this->numPages,
  1631. 'mediaBox' => $this->objects[$this->currentNode]['info']['mediaBox']
  1632. ]
  1633. ];
  1634. if (is_array($options)) {
  1635. // then this must be a page insertion, array should contain 'rid','pos'=[before|after]
  1636. $options['id'] = $id;
  1637. $this->o_pages($this->currentNode, 'page', $options);
  1638. } else {
  1639. $this->o_pages($this->currentNode, 'page', $id);
  1640. }
  1641. $this->currentPage = $id;
  1642. //make a contents object to go with this page
  1643. $this->numObj++;
  1644. $this->o_contents($this->numObj, 'new', $id);
  1645. $this->currentContents = $this->numObj;
  1646. $this->objects[$id]['info']['contents'] = [];
  1647. $this->objects[$id]['info']['contents'][] = $this->numObj;
  1648. $match = ($this->numPages % 2 ? 'odd' : 'even');
  1649. foreach ($this->addLooseObjects as $oId => $target) {
  1650. if ($target === 'all' || $match === $target) {
  1651. $this->objects[$id]['info']['contents'][] = $oId;
  1652. }
  1653. }
  1654. break;
  1655. case 'content':
  1656. $o['info']['contents'][] = $options;
  1657. break;
  1658. case 'annot':
  1659. // add an annotation to this page
  1660. if (!isset($o['info']['annot'])) {
  1661. $o['info']['annot'] = [];
  1662. }
  1663. // $options should contain the id of the annotation dictionary
  1664. $o['info']['annot'][] = $options;
  1665. break;
  1666. case 'out':
  1667. $res = "\n$id 0 obj\n<< /Type /Page";
  1668. if (isset($o['info']['mediaBox'])) {
  1669. $tmp = $o['info']['mediaBox'];
  1670. $res .= "\n/MediaBox [" . sprintf(
  1671. '%.3F %.3F %.3F %.3F',
  1672. $tmp[0],
  1673. $tmp[1],
  1674. $tmp[2],
  1675. $tmp[3]
  1676. ) . ']';
  1677. }
  1678. $res .= "\n/Parent " . $o['info']['parent'] . " 0 R";
  1679. if (isset($o['info']['annot'])) {
  1680. $res .= "\n/Annots [";
  1681. foreach ($o['info']['annot'] as $aId) {
  1682. $res .= " $aId 0 R";
  1683. }
  1684. $res .= " ]";
  1685. }
  1686. $count = count($o['info']['contents']);
  1687. if ($count == 1) {
  1688. $res .= "\n/Contents " . $o['info']['contents'][0] . " 0 R";
  1689. } else {
  1690. if ($count > 1) {
  1691. $res .= "\n/Contents [\n";
  1692. // reverse the page contents so added objects are below normal content
  1693. //foreach (array_reverse($o['info']['contents']) as $cId) {
  1694. // Back to normal now that I've got transparency working --Benj
  1695. foreach ($o['info']['contents'] as $cId) {
  1696. $res .= "$cId 0 R\n";
  1697. }
  1698. $res .= "]";
  1699. }
  1700. }
  1701. $res .= "\n>>\nendobj";
  1702. return $res;
  1703. }
  1704. return null;
  1705. }
  1706. /**
  1707. * the contents objects hold all of the content which appears on pages
  1708. *
  1709. * @param $id
  1710. * @param $action
  1711. * @param string|array $options
  1712. * @return null|string
  1713. */
  1714. protected function o_contents($id, $action, $options = '')
  1715. {
  1716. if ($action !== 'new') {
  1717. $o = &$this->objects[$id];
  1718. }
  1719. switch ($action) {
  1720. case 'new':
  1721. $this->objects[$id] = ['t' => 'contents', 'c' => '', 'info' => []];
  1722. if (mb_strlen($options, '8bit') && intval($options)) {
  1723. // then this contents is the primary for a page
  1724. $this->objects[$id]['onPage'] = $options;
  1725. } else {
  1726. if ($options === 'raw') {
  1727. // then this page contains some other type of system object
  1728. $this->objects[$id]['raw'] = 1;
  1729. }
  1730. }
  1731. break;
  1732. case 'add':
  1733. // add more options to the declaration
  1734. foreach ($options as $k => $v) {
  1735. $o['info'][$k] = $v;
  1736. }
  1737. case 'out':
  1738. $tmp = $o['c'];
  1739. $res = "\n$id 0 obj\n";
  1740. if (isset($this->objects[$id]['raw'])) {
  1741. $res .= $tmp;
  1742. } else {
  1743. $res .= "<<";
  1744. if ($this->compressionReady && $this->options['compression']) {
  1745. // then implement ZLIB based compression on this content stream
  1746. $res .= " /Filter /FlateDecode";
  1747. $tmp = gzcompress($tmp, 6);
  1748. }
  1749. if ($this->encrypted) {
  1750. $this->encryptInit($id);
  1751. $tmp = $this->ARC4($tmp);
  1752. }
  1753. foreach ($o['info'] as $k => $v) {
  1754. $res .= "\n/$k $v";
  1755. }
  1756. $res .= "\n/Length " . mb_strlen($tmp, '8bit') . " >>\nstream\n$tmp\nendstream";
  1757. }
  1758. $res .= "\nendobj";
  1759. return $res;
  1760. }
  1761. return null;
  1762. }
  1763. /**
  1764. * @param $id
  1765. * @param $action
  1766. * @return string|null
  1767. */
  1768. protected function o_embedjs($id, $action)
  1769. {
  1770. switch ($action) {
  1771. case 'new':
  1772. $this->objects[$id] = [
  1773. 't' => 'embedjs',
  1774. 'info' => [
  1775. 'Names' => '[(EmbeddedJS) ' . ($id + 1) . ' 0 R]'
  1776. ]
  1777. ];
  1778. break;
  1779. case 'out':
  1780. $o = &$this->objects[$id];
  1781. $res = "\n$id 0 obj\n<< ";
  1782. foreach ($o['info'] as $k => $v) {
  1783. $res .= "\n/$k $v";
  1784. }
  1785. $res .= "\n>>\nendobj";
  1786. return $res;
  1787. }
  1788. return null;
  1789. }
  1790. /**
  1791. * @param $id
  1792. * @param $action
  1793. * @param string $code
  1794. * @return null|string
  1795. */
  1796. protected function o_javascript($id, $action, $code = '')
  1797. {
  1798. switch ($action) {
  1799. case 'new':
  1800. $this->objects[$id] = [
  1801. 't' => 'javascript',
  1802. 'info' => [
  1803. 'S' => '/JavaScript',
  1804. 'JS' => '(' . $this->filterText($code, true, false) . ')',
  1805. ]
  1806. ];
  1807. break;
  1808. case 'out':
  1809. $o = &$this->objects[$id];
  1810. $res = "\n$id 0 obj\n<< ";
  1811. foreach ($o['info'] as $k => $v) {
  1812. $res .= "\n/$k $v";
  1813. }
  1814. $res .= "\n>>\nendobj";
  1815. return $res;
  1816. }
  1817. return null;
  1818. }
  1819. /**
  1820. * an image object, will be an XObject in the document, includes description and data
  1821. *
  1822. * @param $id
  1823. * @param $action
  1824. * @param string $options
  1825. * @return null|string
  1826. */
  1827. protected function o_image($id, $action, $options = '')
  1828. {
  1829. switch ($action) {
  1830. case 'new':
  1831. // make the new object
  1832. $this->objects[$id] = ['t' => 'image', 'data' => &$options['data'], 'info' => []];
  1833. $info =& $this->objects[$id]['info'];
  1834. $info['Type'] = '/XObject';
  1835. $info['Subtype'] = '/Image';
  1836. $info['Width'] = $options['iw'];
  1837. $info['Height'] = $options['ih'];
  1838. if (isset($options['masked']) && $options['masked']) {
  1839. $info['SMask'] = ($this->numObj - 1) . ' 0 R';
  1840. }
  1841. if (!isset($options['type']) || $options['type'] === 'jpg') {
  1842. if (!isset($options['channels'])) {
  1843. $options['channels'] = 3;
  1844. }
  1845. switch ($options['channels']) {
  1846. case 1:
  1847. $info['ColorSpace'] = '/DeviceGray';
  1848. break;
  1849. case 4:
  1850. $info['ColorSpace'] = '/DeviceCMYK';
  1851. break;
  1852. default:
  1853. $info['ColorSpace'] = '/DeviceRGB';
  1854. break;
  1855. }
  1856. if ($info['ColorSpace'] === '/DeviceCMYK') {
  1857. $info['Decode'] = '[1 0 1 0 1 0 1 0]';
  1858. }
  1859. $info['Filter'] = '/DCTDecode';
  1860. $info['BitsPerComponent'] = 8;
  1861. } else {
  1862. if ($options['type'] === 'png') {
  1863. $info['Filter'] = '/FlateDecode';
  1864. $info['DecodeParms'] = '<< /Predictor 15 /Colors ' . $options['ncolor'] . ' /Columns ' . $options['iw'] . ' /BitsPerComponent ' . $options['bitsPerComponent'] . '>>';
  1865. if ($options['isMask']) {
  1866. $info['ColorSpace'] = '/DeviceGray';
  1867. } else {
  1868. if (mb_strlen($options['pdata'], '8bit')) {
  1869. $tmp = ' [ /Indexed /DeviceRGB ' . (mb_strlen($options['pdata'], '8bit') / 3 - 1) . ' ';
  1870. $this->numObj++;
  1871. $this->o_contents($this->numObj, 'new');
  1872. $this->objects[$this->numObj]['c'] = $options['pdata'];
  1873. $tmp .= $this->numObj . ' 0 R';
  1874. $tmp .= ' ]';
  1875. $info['ColorSpace'] = $tmp;
  1876. if (isset($options['transparency'])) {
  1877. $transparency = $options['transparency'];
  1878. switch ($transparency['type']) {
  1879. case 'indexed':
  1880. $tmp = ' [ ' . $transparency['data'] . ' ' . $transparency['data'] . '] ';
  1881. $info['Mask'] = $tmp;
  1882. break;
  1883. case 'color-key':
  1884. $tmp = ' [ ' .
  1885. $transparency['r'] . ' ' . $transparency['r'] .
  1886. $transparency['g'] . ' ' . $transparency['g'] .
  1887. $transparency['b'] . ' ' . $transparency['b'] .
  1888. ' ] ';
  1889. $info['Mask'] = $tmp;
  1890. break;
  1891. }
  1892. }
  1893. } else {
  1894. if (isset($options['transparency'])) {
  1895. $transparency = $options['transparency'];
  1896. switch ($transparency['type']) {
  1897. case 'indexed':
  1898. $tmp = ' [ ' . $transparency['data'] . ' ' . $transparency['data'] . '] ';
  1899. $info['Mask'] = $tmp;
  1900. break;
  1901. case 'color-key':
  1902. $tmp = ' [ ' .
  1903. $transparency['r'] . ' ' . $transparency['r'] . ' ' .
  1904. $transparency['g'] . ' ' . $transparency['g'] . ' ' .
  1905. $transparency['b'] . ' ' . $transparency['b'] .
  1906. ' ] ';
  1907. $info['Mask'] = $tmp;
  1908. break;
  1909. }
  1910. }
  1911. $info['ColorSpace'] = '/' . $options['color'];
  1912. }
  1913. }
  1914. $info['BitsPerComponent'] = $options['bitsPerComponent'];
  1915. }
  1916. }
  1917. // assign it a place in the named resource dictionary as an external object, according to
  1918. // the label passed in with it.
  1919. $this->o_pages($this->currentNode, 'xObject', ['label' => $options['label'], 'objNum' => $id]);
  1920. // also make sure that we have the right procset object for it.
  1921. $this->o_procset($this->procsetObjectId, 'add', 'ImageC');
  1922. break;
  1923. case 'out':
  1924. $o = &$this->objects[$id];
  1925. $tmp = &$o['data'];
  1926. $res = "\n$id 0 obj\n<<";
  1927. foreach ($o['info'] as $k => $v) {
  1928. $res .= "\n/$k $v";
  1929. }
  1930. if ($this->encrypted) {
  1931. $this->encryptInit($id);
  1932. $tmp = $this->ARC4($tmp);
  1933. }
  1934. $res .= "\n/Length " . mb_strlen($tmp, '8bit') . ">>\nstream\n$tmp\nendstream\nendobj";
  1935. return $res;
  1936. }
  1937. return null;
  1938. }
  1939. /**
  1940. * graphics state object
  1941. *
  1942. * @param $id
  1943. * @param $action
  1944. * @param string $options
  1945. * @return null|string
  1946. */
  1947. protected function o_extGState($id, $action, $options = "")
  1948. {
  1949. static $valid_params = [
  1950. "LW",
  1951. "LC",
  1952. "LC",
  1953. "LJ",
  1954. "ML",
  1955. "D",
  1956. "RI",
  1957. "OP",
  1958. "op",
  1959. "OPM",
  1960. "Font",
  1961. "BG",
  1962. "BG2",
  1963. "UCR",
  1964. "TR",
  1965. "TR2",
  1966. "HT",
  1967. "FL",
  1968. "SM",
  1969. "SA",
  1970. "BM",
  1971. "SMask",
  1972. "CA",
  1973. "ca",
  1974. "AIS",
  1975. "TK"
  1976. ];
  1977. switch ($action) {
  1978. case "new":
  1979. $this->objects[$id] = ['t' => 'extGState', 'info' => $options];
  1980. // Tell the pages about the new resource
  1981. $this->numStates++;
  1982. $this->o_pages($this->currentNode, 'extGState', ["objNum" => $id, "stateNum" => $this->numStates]);
  1983. break;
  1984. case "out":
  1985. $o = &$this->objects[$id];
  1986. $res = "\n$id 0 obj\n<< /Type /ExtGState\n";
  1987. foreach ($o["info"] as $k => $v) {
  1988. if (!in_array($k, $valid_params)) {
  1989. continue;
  1990. }
  1991. $res .= "/$k $v\n";
  1992. }
  1993. $res .= ">>\nendobj";
  1994. return $res;
  1995. }
  1996. return null;
  1997. }
  1998. /**
  1999. * @param integer $id
  2000. * @param string $action
  2001. * @param mixed $options
  2002. * @return string
  2003. */
  2004. protected function o_xobject($id, $action, $options = '')
  2005. {
  2006. switch ($action) {
  2007. case 'new':
  2008. $this->objects[$id] = ['t' => 'xobject', 'info' => $options, 'c' => ''];
  2009. break;
  2010. case 'procset':
  2011. $this->objects[$id]['procset'] = $options;
  2012. break;
  2013. case 'font':
  2014. $this->objects[$id]['fonts'][$options['fontNum']] = [
  2015. 'objNum' => $options['objNum'],
  2016. 'fontNum' => $options['fontNum']
  2017. ];
  2018. break;
  2019. case 'xObject':
  2020. $this->objects[$id]['xObjects'][] = ['objNum' => $options['objNum'], 'label' => $options['label']];
  2021. break;
  2022. case 'out':
  2023. $o = &$this->objects[$id];
  2024. $res = "\n$id 0 obj\n<< /Type /XObject\n";
  2025. foreach ($o["info"] as $k => $v) {
  2026. switch($k)
  2027. {
  2028. case 'Subtype':
  2029. $res .= "/Subtype /$v\n";
  2030. break;
  2031. case 'bbox':
  2032. $res .= "/BBox [";
  2033. foreach ($v as $value) {
  2034. $res .= sprintf("%.4F ", $value);
  2035. }
  2036. $res .= "]\n";
  2037. break;
  2038. default:
  2039. $res .= "/$k $v\n";
  2040. break;
  2041. }
  2042. }
  2043. $res .= "/Matrix[1.0 0.0 0.0 1.0 0.0 0.0]\n";
  2044. $res .= "/Resources <<";
  2045. if (isset($o['procset'])) {
  2046. $res .= "\n/ProcSet " . $o['procset'] . " 0 R";
  2047. } else {
  2048. $res .= "\n/ProcSet [/PDF /Text /ImageB /ImageC /ImageI]";
  2049. }
  2050. if (isset($o['fonts']) && count($o['fonts'])) {
  2051. $res .= "\n/Font << ";
  2052. foreach ($o['fonts'] as $finfo) {
  2053. $res .= "\n/F" . $finfo['fontNum'] . " " . $finfo['objNum'] . " 0 R";
  2054. }
  2055. $res .= "\n>>";
  2056. }
  2057. if (isset($o['xObjects']) && count($o['xObjects'])) {
  2058. $res .= "\n/XObject << ";
  2059. foreach ($o['xObjects'] as $finfo) {
  2060. $res .= "\n/" . $finfo['label'] . " " . $finfo['objNum'] . " 0 R";
  2061. }
  2062. $res .= "\n>>";
  2063. }
  2064. $res .= "\n>>\n";
  2065. $tmp = $o["c"];
  2066. if ($this->compressionReady && $this->options['compression']) {
  2067. // then implement ZLIB based compression on this content stream
  2068. $res .= " /Filter /FlateDecode\n";
  2069. $tmp = gzcompress($tmp, 6);
  2070. }
  2071. if ($this->encrypted) {
  2072. $this->encryptInit($id);
  2073. $tmp = $this->ARC4($tmp);
  2074. }
  2075. $res .= "/Length " . mb_strlen($tmp, '8bit') . " >>\n";
  2076. $res .= "stream\n" . $tmp . "\nendstream" . "\nendobj";;
  2077. return $res;
  2078. }
  2079. return null;
  2080. }
  2081. /**
  2082. * @param $id
  2083. * @param $action
  2084. * @param string $options
  2085. * @return null|string
  2086. */
  2087. protected function o_acroform($id, $action, $options = '')
  2088. {
  2089. switch ($action) {
  2090. case "new":
  2091. $this->o_catalog($this->catalogId, 'acroform', $id);
  2092. $this->objects[$id] = array('t' => 'acroform', 'info' => $options);
  2093. break;
  2094. case 'addfield':
  2095. $this->objects[$id]['info']['Fields'][] = $options;
  2096. break;
  2097. case 'font':
  2098. $this->objects[$id]['fonts'][$options['fontNum']] = [
  2099. 'objNum' => $options['objNum'],
  2100. 'fontNum' => $options['fontNum']
  2101. ];
  2102. break;
  2103. case "out":
  2104. $o = &$this->objects[$id];
  2105. $res = "\n$id 0 obj\n<<";
  2106. foreach ($o["info"] as $k => $v) {
  2107. switch($k) {
  2108. case 'Fields':
  2109. $res .= " /Fields [";
  2110. foreach ($v as $i) {
  2111. $res .= "$i 0 R ";
  2112. }
  2113. $res .= "]\n";
  2114. break;
  2115. default:
  2116. $res .= "/$k $v\n";
  2117. }
  2118. }
  2119. $res .= "/DR <<\n";
  2120. if (isset($o['fonts']) && count($o['fonts'])) {
  2121. $res .= "/Font << \n";
  2122. foreach ($o['fonts'] as $finfo) {
  2123. $res .= "/F" . $finfo['fontNum'] . " " . $finfo['objNum'] . " 0 R\n";
  2124. }
  2125. $res .= ">>\n";
  2126. }
  2127. $res .= ">>\n";
  2128. $res .= ">>\nendobj";
  2129. return $res;
  2130. }
  2131. return null;
  2132. }
  2133. /**
  2134. * @param $id
  2135. * @param $action
  2136. * @param mixed $options
  2137. * @return null|string
  2138. */
  2139. protected function o_field($id, $action, $options = '')
  2140. {
  2141. switch ($action) {
  2142. case "new":
  2143. $this->o_page($options['pageid'], 'annot', $id);
  2144. $this->o_acroform($this->acroFormId, 'addfield', $id);
  2145. $this->objects[$id] = ['t' => 'field', 'info' => $options];
  2146. break;
  2147. case 'set':
  2148. $this->objects[$id]['info'] = array_merge($this->objects[$id]['info'], $options);
  2149. break;
  2150. case "out":
  2151. $o = &$this->objects[$id];
  2152. $res = "\n$id 0 obj\n<< /Type /Annot /Subtype /Widget \n";
  2153. $encrypted = $this->encrypted;
  2154. if ($encrypted) {
  2155. $this->encryptInit($id);
  2156. }
  2157. foreach ($o["info"] as $k => $v) {
  2158. switch ($k) {
  2159. case 'pageid':
  2160. $res .= "/P $v 0 R\n";
  2161. break;
  2162. case 'value':
  2163. if ($encrypted) {
  2164. $v = $this->filterText($this->ARC4($v), false, false);
  2165. }
  2166. $res .= "/V ($v)\n";
  2167. break;
  2168. case 'refvalue':
  2169. $res .= "/V $v 0 R\n";
  2170. break;
  2171. case 'da':
  2172. if ($encrypted) {
  2173. $v = $this->filterText($this->ARC4($v), false, false);
  2174. }
  2175. $res .= "/DA ($v)\n";
  2176. break;
  2177. case 'options':
  2178. $res .= "/Opt [\n";
  2179. foreach ($v as $opt) {
  2180. if ($encrypted) {
  2181. $opt = $this->filterText($this->ARC4($opt), false, false);
  2182. }
  2183. $res .= "($opt)\n";
  2184. }
  2185. $res .= "]\n";
  2186. break;
  2187. case 'rect':
  2188. $res .= "/Rect [";
  2189. foreach ($v as $value) {
  2190. $res .= sprintf("%.4F ", $value);
  2191. }
  2192. $res .= "]\n";
  2193. break;
  2194. case 'appearance':
  2195. $res .= "/AP << ";
  2196. foreach ($v as $a => $ref) {
  2197. $res .= "/$a $ref 0 R ";
  2198. }
  2199. $res .= ">>\n";
  2200. break;
  2201. case 'T':
  2202. if($encrypted) {
  2203. $v = $this->filterText($this->ARC4($v), false, false);
  2204. }
  2205. $res .= "/T ($v)\n";
  2206. break;
  2207. default:
  2208. $res .= "/$k $v\n";
  2209. }
  2210. }
  2211. $res .= ">>\nendobj";
  2212. return $res;
  2213. }
  2214. return null;
  2215. }
  2216. /**
  2217. *
  2218. * @param $id
  2219. * @param $action
  2220. * @param string $options
  2221. * @return null|string
  2222. */
  2223. protected function o_sig($id, $action, $options = '')
  2224. {
  2225. $sign_maxlen = $this->signatureMaxLen;
  2226. switch ($action) {
  2227. case "new":
  2228. $this->objects[$id] = array('t' => 'sig', 'info' => $options);
  2229. $this->byteRange[$id] = ['t' => 'sig'];
  2230. break;
  2231. case 'byterange':
  2232. $o = &$this->objects[$id];
  2233. $content =& $options['content'];
  2234. $content_len = strlen($content);
  2235. $pos = strpos($content, sprintf("/ByteRange [ %'.010d", $id));
  2236. $len = strlen('/ByteRange [ ********** ********** ********** ********** ]');
  2237. $rangeStartPos = $pos + $len + 1 + 10; // before '<'
  2238. $content = substr_replace($content, str_pad(sprintf('/ByteRange [ 0 %u %u %u ]', $rangeStartPos, $rangeStartPos + $sign_maxlen + 2, $content_len - 2 - $sign_maxlen - $rangeStartPos ), $len, ' ', STR_PAD_RIGHT), $pos, $len);
  2239. $fuid = uniqid();
  2240. $tmpInput = $this->tmp . "/pkcs7.tmp." . $fuid . '.in';
  2241. $tmpOutput = $this->tmp . "/pkcs7.tmp." . $fuid . '.out';
  2242. if (file_put_contents($tmpInput, substr($content, 0, $rangeStartPos)) === false) {
  2243. throw new \Exception("Unable to write temporary file for signing.");
  2244. }
  2245. if (file_put_contents($tmpInput, substr($content, $rangeStartPos + 2 + $sign_maxlen),
  2246. FILE_APPEND) === false) {
  2247. throw new \Exception("Unable to write temporary file for signing.");
  2248. }
  2249. if (openssl_pkcs7_sign($tmpInput, $tmpOutput,
  2250. $o['info']['SignCert'],
  2251. array($o['info']['PrivKey'], $o['info']['Password']),
  2252. array(), PKCS7_BINARY | PKCS7_DETACHED) === false) {
  2253. throw new \Exception("Failed to prepare signature.");
  2254. }
  2255. $signature = file_get_contents($tmpOutput);
  2256. unlink($tmpInput);
  2257. unlink($tmpOutput);
  2258. $sign = substr($signature, (strpos($signature, "%%EOF\n\n------") + 13));
  2259. list($head, $signature) = explode("\n\n", $sign);
  2260. $signature = base64_decode(trim($signature));
  2261. $signature = current(unpack('H*', $signature));
  2262. $signature = str_pad($signature, $sign_maxlen, '0');
  2263. $siglen = strlen($signature);
  2264. if (strlen($signature) > $sign_maxlen) {
  2265. throw new \Exception("Signature length ($siglen) exceeds the $sign_maxlen limit.");
  2266. }
  2267. $content = substr_replace($content, $signature, $rangeStartPos + 1, $sign_maxlen);
  2268. break;
  2269. case "out":
  2270. $res = "\n$id 0 obj\n<<\n";
  2271. $encrypted = $this->encrypted;
  2272. if ($encrypted) {
  2273. $this->encryptInit($id);
  2274. }
  2275. $res .= "/ByteRange " .sprintf("[ %'.010d ********** ********** ********** ]\n", $id);
  2276. $res .= "/Contents <" . str_pad('', $sign_maxlen, '0') . ">\n";
  2277. $res .= "/Filter/Adobe.PPKLite\n"; //PPKMS \n";
  2278. $res .= "/Type/Sig/SubFilter/adbe.pkcs7.detached \n";
  2279. $date = "D:" . substr_replace(date('YmdHisO'), '\'', -2, 0) . '\'';
  2280. if ($encrypted) {
  2281. $date = $this->ARC4($date);
  2282. }
  2283. $res .= "/M ($date)\n";
  2284. $res .= "/Prop_Build << /App << /Name /DomPDF >> /Filter << /Name /Adobe.PPKLite >> >>\n";
  2285. $o = &$this->objects[$id];
  2286. foreach ($o['info'] as $k => $v) {
  2287. switch($k) {
  2288. case 'Name':
  2289. case 'Location':
  2290. case 'Reason':
  2291. case 'ContactInfo':
  2292. if ($v !== null && $v !== '') {
  2293. $res .= "/$k (" .
  2294. ($encrypted ? $this->filterText($this->ARC4($v), false, false) : $v) . ") \n";
  2295. }
  2296. break;
  2297. }
  2298. }
  2299. $res .= ">>\nendobj";
  2300. return $res;
  2301. }
  2302. return null;
  2303. }
  2304. /**
  2305. * encryption object.
  2306. *
  2307. * @param $id
  2308. * @param $action
  2309. * @param string $options
  2310. * @return string|null
  2311. */
  2312. protected function o_encryption($id, $action, $options = '')
  2313. {
  2314. switch ($action) {
  2315. case 'new':
  2316. // make the new object
  2317. $this->objects[$id] = ['t' => 'encryption', 'info' => $options];
  2318. $this->arc4_objnum = $id;
  2319. break;
  2320. case 'keys':
  2321. // figure out the additional parameters required
  2322. $pad = chr(0x28) . chr(0xBF) . chr(0x4E) . chr(0x5E) . chr(0x4E) . chr(0x75) . chr(0x8A) . chr(0x41)
  2323. . chr(0x64) . chr(0x00) . chr(0x4E) . chr(0x56) . chr(0xFF) . chr(0xFA) . chr(0x01) . chr(0x08)
  2324. . chr(0x2E) . chr(0x2E) . chr(0x00) . chr(0xB6) . chr(0xD0) . chr(0x68) . chr(0x3E) . chr(0x80)
  2325. . chr(0x2F) . chr(0x0C) . chr(0xA9) . chr(0xFE) . chr(0x64) . chr(0x53) . chr(0x69) . chr(0x7A);
  2326. $info = $this->objects[$id]['info'];
  2327. $len = mb_strlen($info['owner'], '8bit');
  2328. if ($len > 32) {
  2329. $owner = substr($info['owner'], 0, 32);
  2330. } else {
  2331. if ($len < 32) {
  2332. $owner = $info['owner'] . substr($pad, 0, 32 - $len);
  2333. } else {
  2334. $owner = $info['owner'];
  2335. }
  2336. }
  2337. $len = mb_strlen($info['user'], '8bit');
  2338. if ($len > 32) {
  2339. $user = substr($info['user'], 0, 32);
  2340. } else {
  2341. if ($len < 32) {
  2342. $user = $info['user'] . substr($pad, 0, 32 - $len);
  2343. } else {
  2344. $user = $info['user'];
  2345. }
  2346. }
  2347. $tmp = $this->md5_16($owner);
  2348. $okey = substr($tmp, 0, 5);
  2349. $this->ARC4_init($okey);
  2350. $ovalue = $this->ARC4($user);
  2351. $this->objects[$id]['info']['O'] = $ovalue;
  2352. // now make the u value, phew.
  2353. $tmp = $this->md5_16(
  2354. $user . $ovalue . chr($info['p']) . chr(255) . chr(255) . chr(255) . hex2bin($this->fileIdentifier)
  2355. );
  2356. $ukey = substr($tmp, 0, 5);
  2357. $this->ARC4_init($ukey);
  2358. $this->encryptionKey = $ukey;
  2359. $this->encrypted = true;
  2360. $uvalue = $this->ARC4($pad);
  2361. $this->objects[$id]['info']['U'] = $uvalue;
  2362. // initialize the arc4 array
  2363. break;
  2364. case 'out':
  2365. $o = &$this->objects[$id];
  2366. $res = "\n$id 0 obj\n<<";
  2367. $res .= "\n/Filter /Standard";
  2368. $res .= "\n/V 1";
  2369. $res .= "\n/R 2";
  2370. $res .= "\n/O (" . $this->filterText($o['info']['O'], false, false) . ')';
  2371. $res .= "\n/U (" . $this->filterText($o['info']['U'], false, false) . ')';
  2372. // and the p-value needs to be converted to account for the twos-complement approach
  2373. $o['info']['p'] = (($o['info']['p'] ^ 255) + 1) * -1;
  2374. $res .= "\n/P " . ($o['info']['p']);
  2375. $res .= "\n>>\nendobj";
  2376. return $res;
  2377. }
  2378. return null;
  2379. }
  2380. protected function o_indirect_references($id, $action, $options = null)
  2381. {
  2382. switch ($action) {
  2383. case 'new':
  2384. case 'add':
  2385. if ($id === 0) {
  2386. $id = ++$this->numObj;
  2387. $this->o_catalog($this->catalogId, 'names', $id);
  2388. $this->objects[$id] = ['t' => 'indirect_references', 'info' => $options];
  2389. $this->indirectReferenceId = $id;
  2390. } else {
  2391. $this->objects[$id]['info'] = array_merge($this->objects[$id]['info'], $options);
  2392. }
  2393. break;
  2394. case 'out':
  2395. $res = "\n$id 0 obj << ";
  2396. foreach($this->objects[$id]['info'] as $referenceObjName => $referenceObjId) {
  2397. $res .= "/$referenceObjName $referenceObjId 0 R ";
  2398. }
  2399. $res .= ">> endobj";
  2400. return $res;
  2401. }
  2402. return null;
  2403. }
  2404. protected function o_names($id, $action, $options = null)
  2405. {
  2406. switch ($action) {
  2407. case 'new':
  2408. case 'add':
  2409. if ($id === 0) {
  2410. $id = ++$this->numObj;
  2411. $this->objects[$id] = ['t' => 'names', 'info' => [$options]];
  2412. $this->o_indirect_references($this->indirectReferenceId, 'add', ['EmbeddedFiles' => $id]);
  2413. $this->embeddedFilesId = $id;
  2414. } else {
  2415. $this->objects[$id]['info'][] = $options;
  2416. }
  2417. break;
  2418. case 'out':
  2419. $info = &$this->objects[$id]['info'];
  2420. $res = '';
  2421. if (count($info) > 0) {
  2422. $res = "\n$id 0 obj << /Names [ ";
  2423. if ($this->encrypted) {
  2424. $this->encryptInit($id);
  2425. }
  2426. foreach ($info as $entry) {
  2427. if ($this->encrypted) {
  2428. $filename = $this->ARC4($entry['filename']);
  2429. } else {
  2430. $filename = $entry['filename'];
  2431. }
  2432. $res .= "($filename) " . $entry['dict_reference'] . " 0 R ";
  2433. }
  2434. $res .= "] >> endobj";
  2435. }
  2436. return $res;
  2437. }
  2438. return null;
  2439. }
  2440. protected function o_embedded_file_dictionary($id, $action, $options = null)
  2441. {
  2442. switch ($action) {
  2443. case 'new':
  2444. $embeddedFileId = ++$this->numObj;
  2445. $options['embedded_reference'] = $embeddedFileId;
  2446. $this->objects[$id] = ['t' => 'embedded_file_dictionary', 'info' => $options];
  2447. $this->o_embedded_file($embeddedFileId, 'new', $options);
  2448. $options['dict_reference'] = $id;
  2449. $this->o_names($this->embeddedFilesId, 'add', $options);
  2450. break;
  2451. case 'out':
  2452. $info = &$this->objects[$id]['info'];
  2453. if ($this->encrypted) {
  2454. $this->encryptInit($id);
  2455. $filename = $this->ARC4($info['filename']);
  2456. $description = $this->ARC4($info['description']);
  2457. } else {
  2458. $filename = $info['filename'];
  2459. $description = $info['description'];
  2460. }
  2461. $res = "\n$id 0 obj <</Type /Filespec /EF";
  2462. $res .= " <</F " . $info['embedded_reference'] . " 0 R >>";
  2463. $res .= " /F ($filename) /UF ($filename) /Desc ($description)";
  2464. $res .= " >> endobj";
  2465. return $res;
  2466. }
  2467. return null;
  2468. }
  2469. protected function o_embedded_file($id, $action, $options = null): ?string
  2470. {
  2471. switch ($action) {
  2472. case 'new':
  2473. $this->objects[$id] = ['t' => 'embedded_file', 'info' => $options];
  2474. break;
  2475. case 'out':
  2476. $info = &$this->objects[$id]['info'];
  2477. if ($this->compressionReady) {
  2478. $filepath = $info['filepath'];
  2479. $checksum = md5_file($filepath);
  2480. $f = fopen($filepath, "rb");
  2481. $file_content_compressed = '';
  2482. $deflateContext = deflate_init(ZLIB_ENCODING_DEFLATE, ['level' => 6]);
  2483. while (($block = fread($f, 8192))) {
  2484. $file_content_compressed .= deflate_add($deflateContext, $block, ZLIB_NO_FLUSH);
  2485. }
  2486. $file_content_compressed .= deflate_add($deflateContext, '', ZLIB_FINISH);
  2487. $file_size_uncompressed = ftell($f);
  2488. fclose($f);
  2489. } else {
  2490. $file_content = file_get_contents($info['filepath']);
  2491. $file_size_uncompressed = mb_strlen($file_content, '8bit');
  2492. $checksum = md5($file_content);
  2493. }
  2494. if ($this->encrypted) {
  2495. $this->encryptInit($id);
  2496. $checksum = $this->ARC4($checksum);
  2497. $file_content_compressed = $this->ARC4($file_content_compressed);
  2498. }
  2499. $file_size_compressed = mb_strlen($file_content_compressed, '8bit');
  2500. $res = "\n$id 0 obj <</Params <</Size $file_size_uncompressed /CheckSum ($checksum) >>" .
  2501. " /Type/EmbeddedFile /Filter/FlateDecode" .
  2502. " /Length $file_size_compressed >> stream\n$file_content_compressed\nendstream\nendobj";
  2503. return $res;
  2504. }
  2505. return null;
  2506. }
  2507. /**
  2508. * ARC4 functions
  2509. * A series of function to implement ARC4 encoding in PHP
  2510. */
  2511. /**
  2512. * calculate the 16 byte version of the 128 bit md5 digest of the string
  2513. *
  2514. * @param $string
  2515. * @return string
  2516. */
  2517. function md5_16($string)
  2518. {
  2519. $tmp = md5($string);
  2520. $out = '';
  2521. for ($i = 0; $i <= 30; $i = $i + 2) {
  2522. $out .= chr(hexdec(substr($tmp, $i, 2)));
  2523. }
  2524. return $out;
  2525. }
  2526. /**
  2527. * initialize the encryption for processing a particular object
  2528. *
  2529. * @param $id
  2530. */
  2531. function encryptInit($id)
  2532. {
  2533. $tmp = $this->encryptionKey;
  2534. $hex = dechex($id);
  2535. if (mb_strlen($hex, '8bit') < 6) {
  2536. $hex = substr('000000', 0, 6 - mb_strlen($hex, '8bit')) . $hex;
  2537. }
  2538. $tmp .= chr(hexdec(substr($hex, 4, 2)))
  2539. . chr(hexdec(substr($hex, 2, 2)))
  2540. . chr(hexdec(substr($hex, 0, 2)))
  2541. . chr(0)
  2542. . chr(0)
  2543. ;
  2544. $key = $this->md5_16($tmp);
  2545. $this->ARC4_init(substr($key, 0, 10));
  2546. }
  2547. /**
  2548. * initialize the ARC4 encryption
  2549. *
  2550. * @param string $key
  2551. */
  2552. function ARC4_init($key = '')
  2553. {
  2554. $this->arc4 = '';
  2555. // setup the control array
  2556. if (mb_strlen($key, '8bit') == 0) {
  2557. return;
  2558. }
  2559. $k = '';
  2560. while (mb_strlen($k, '8bit') < 256) {
  2561. $k .= $key;
  2562. }
  2563. $k = substr($k, 0, 256);
  2564. for ($i = 0; $i < 256; $i++) {
  2565. $this->arc4 .= chr($i);
  2566. }
  2567. $j = 0;
  2568. for ($i = 0; $i < 256; $i++) {
  2569. $t = $this->arc4[$i];
  2570. $j = ($j + ord($t) + ord($k[$i])) % 256;
  2571. $this->arc4[$i] = $this->arc4[$j];
  2572. $this->arc4[$j] = $t;
  2573. }
  2574. }
  2575. /**
  2576. * ARC4 encrypt a text string
  2577. *
  2578. * @param $text
  2579. * @return string
  2580. */
  2581. function ARC4($text)
  2582. {
  2583. $len = mb_strlen($text, '8bit');
  2584. $a = 0;
  2585. $b = 0;
  2586. $c = $this->arc4;
  2587. $out = '';
  2588. for ($i = 0; $i < $len; $i++) {
  2589. $a = ($a + 1) % 256;
  2590. $t = $c[$a];
  2591. $b = ($b + ord($t)) % 256;
  2592. $c[$a] = $c[$b];
  2593. $c[$b] = $t;
  2594. $k = ord($c[(ord($c[$a]) + ord($c[$b])) % 256]);
  2595. $out .= chr(ord($text[$i]) ^ $k);
  2596. }
  2597. return $out;
  2598. }
  2599. /**
  2600. * functions which can be called to adjust or add to the document
  2601. */
  2602. /**
  2603. * add a link in the document to an external URL
  2604. *
  2605. * @param $url
  2606. * @param $x0
  2607. * @param $y0
  2608. * @param $x1
  2609. * @param $y1
  2610. */
  2611. function addLink($url, $x0, $y0, $x1, $y1)
  2612. {
  2613. $this->numObj++;
  2614. $info = ['type' => 'link', 'url' => $url, 'rect' => [$x0, $y0, $x1, $y1]];
  2615. $this->o_annotation($this->numObj, 'new', $info);
  2616. }
  2617. /**
  2618. * add a link in the document to an internal destination (ie. within the document)
  2619. *
  2620. * @param $label
  2621. * @param $x0
  2622. * @param $y0
  2623. * @param $x1
  2624. * @param $y1
  2625. */
  2626. function addInternalLink($label, $x0, $y0, $x1, $y1)
  2627. {
  2628. $this->numObj++;
  2629. $info = ['type' => 'ilink', 'label' => $label, 'rect' => [$x0, $y0, $x1, $y1]];
  2630. $this->o_annotation($this->numObj, 'new', $info);
  2631. }
  2632. /**
  2633. * set the encryption of the document
  2634. * can be used to turn it on and/or set the passwords which it will have.
  2635. * also the functions that the user will have are set here, such as print, modify, add
  2636. *
  2637. * @param string $userPass
  2638. * @param string $ownerPass
  2639. * @param array $pc
  2640. */
  2641. function setEncryption($userPass = '', $ownerPass = '', $pc = [])
  2642. {
  2643. $p = bindec("11000000");
  2644. $options = ['print' => 4, 'modify' => 8, 'copy' => 16, 'add' => 32];
  2645. foreach ($pc as $k => $v) {
  2646. if ($v && isset($options[$k])) {
  2647. $p += $options[$k];
  2648. } else {
  2649. if (isset($options[$v])) {
  2650. $p += $options[$v];
  2651. }
  2652. }
  2653. }
  2654. // implement encryption on the document
  2655. if ($this->arc4_objnum == 0) {
  2656. // then the block does not exist already, add it.
  2657. $this->numObj++;
  2658. if (mb_strlen($ownerPass) == 0) {
  2659. $ownerPass = $userPass;
  2660. }
  2661. $this->o_encryption($this->numObj, 'new', ['user' => $userPass, 'owner' => $ownerPass, 'p' => $p]);
  2662. }
  2663. }
  2664. /**
  2665. * should be used for internal checks, not implemented as yet
  2666. */
  2667. function checkAllHere()
  2668. {
  2669. }
  2670. /**
  2671. * return the pdf stream as a string returned from the function
  2672. *
  2673. * @param bool $debug
  2674. * @return string
  2675. */
  2676. function output($debug = false)
  2677. {
  2678. if ($debug) {
  2679. // turn compression off
  2680. $this->options['compression'] = false;
  2681. }
  2682. if ($this->javascript) {
  2683. $this->numObj++;
  2684. $js_id = $this->numObj;
  2685. $this->o_embedjs($js_id, 'new');
  2686. $this->o_javascript(++$this->numObj, 'new', $this->javascript);
  2687. $id = $this->catalogId;
  2688. $this->o_indirect_references($this->indirectReferenceId, 'add', ['Javascript' => $js_id]);
  2689. }
  2690. if ($this->fileIdentifier === '') {
  2691. $tmp = implode('', $this->objects[$this->infoObject]['info']);
  2692. $this->fileIdentifier = md5('DOMPDF' . __FILE__ . $tmp . microtime() . mt_rand());
  2693. }
  2694. if ($this->arc4_objnum) {
  2695. $this->o_encryption($this->arc4_objnum, 'keys');
  2696. $this->ARC4_init($this->encryptionKey);
  2697. }
  2698. $this->checkAllHere();
  2699. $xref = [];
  2700. $content = '%PDF-1.7';
  2701. $pos = mb_strlen($content, '8bit');
  2702. // pre-process o_font objects before output of all objects
  2703. foreach ($this->objects as $k => $v) {
  2704. if ($v['t'] === 'font') {
  2705. $this->o_font($k, 'add');
  2706. }
  2707. }
  2708. foreach ($this->objects as $k => $v) {
  2709. $tmp = 'o_' . $v['t'];
  2710. $cont = $this->$tmp($k, 'out');
  2711. $content .= $cont;
  2712. $xref[] = $pos + 1; //+1 to account for \n at the start of each object
  2713. $pos += mb_strlen($cont, '8bit');
  2714. }
  2715. $content .= "\nxref\n0 " . (count($xref) + 1) . "\n0000000000 65535 f \n";
  2716. foreach ($xref as $p) {
  2717. $content .= str_pad($p, 10, "0", STR_PAD_LEFT) . " 00000 n \n";
  2718. }
  2719. $content .= "trailer\n<<\n" .
  2720. '/Size ' . (count($xref) + 1) . "\n" .
  2721. '/Root 1 0 R' . "\n" .
  2722. '/Info ' . $this->infoObject . " 0 R\n"
  2723. ;
  2724. // if encryption has been applied to this document then add the marker for this dictionary
  2725. if ($this->arc4_objnum > 0) {
  2726. $content .= '/Encrypt ' . $this->arc4_objnum . " 0 R\n";
  2727. }
  2728. $content .= '/ID[<' . $this->fileIdentifier . '><' . $this->fileIdentifier . ">]\n";
  2729. // account for \n added at start of xref table
  2730. $pos++;
  2731. $content .= ">>\nstartxref\n$pos\n%%EOF\n";
  2732. if (count($this->byteRange) > 0) {
  2733. foreach ($this->byteRange as $k => $v) {
  2734. $tmp = 'o_' . $v['t'];
  2735. $this->$tmp($k, 'byterange', ['content' => &$content]);
  2736. }
  2737. }
  2738. return $content;
  2739. }
  2740. /**
  2741. * initialize a new document
  2742. * if this is called on an existing document results may be unpredictable, but the existing document would be lost at minimum
  2743. * this function is called automatically by the constructor function
  2744. *
  2745. * @param array $pageSize
  2746. */
  2747. private function newDocument($pageSize = [0, 0, 612, 792])
  2748. {
  2749. $this->numObj = 0;
  2750. $this->objects = [];
  2751. $this->numObj++;
  2752. $this->o_catalog($this->numObj, 'new');
  2753. $this->numObj++;
  2754. $this->o_outlines($this->numObj, 'new');
  2755. $this->numObj++;
  2756. $this->o_pages($this->numObj, 'new');
  2757. $this->o_pages($this->numObj, 'mediaBox', $pageSize);
  2758. $this->currentNode = 3;
  2759. $this->numObj++;
  2760. $this->o_procset($this->numObj, 'new');
  2761. $this->numObj++;
  2762. $this->o_info($this->numObj, 'new');
  2763. $this->numObj++;
  2764. $this->o_page($this->numObj, 'new');
  2765. // need to store the first page id as there is no way to get it to the user during
  2766. // startup
  2767. $this->firstPageId = $this->currentContents;
  2768. }
  2769. /**
  2770. * open the font file and return a php structure containing it.
  2771. * first check if this one has been done before and saved in a form more suited to php
  2772. * note that if a php serialized version does not exist it will try and make one, but will
  2773. * require write access to the directory to do it... it is MUCH faster to have these serialized
  2774. * files.
  2775. *
  2776. * @param $font
  2777. */
  2778. private function openFont($font)
  2779. {
  2780. // assume that $font contains the path and file but not the extension
  2781. $name = basename($font);
  2782. $dir = dirname($font) . '/';
  2783. $fontcache = $this->fontcache;
  2784. if ($fontcache == '') {
  2785. $fontcache = rtrim($dir, DIRECTORY_SEPARATOR."/\\");
  2786. }
  2787. //$name filename without folder and extension of font metrics
  2788. //$dir folder of font metrics
  2789. //$fontcache folder of runtime created php serialized version of font metrics.
  2790. // If this is not given, the same folder as the font metrics will be used.
  2791. // Storing and reusing serialized versions improves speed much
  2792. $this->addMessage("openFont: $font - $name");
  2793. if (!$this->isUnicode || in_array(mb_strtolower(basename($name)), self::$coreFonts)) {
  2794. $metrics_name = "$name.afm";
  2795. } else {
  2796. $metrics_name = "$name.ufm";
  2797. }
  2798. $cache_name = "$metrics_name.php";
  2799. $this->addMessage("metrics: $metrics_name, cache: $cache_name");
  2800. if (file_exists($fontcache . '/' . $cache_name)) {
  2801. $this->addMessage("openFont: php file exists $fontcache/$cache_name");
  2802. $this->fonts[$font] = require($fontcache . '/' . $cache_name);
  2803. if (!isset($this->fonts[$font]['_version_']) || $this->fonts[$font]['_version_'] != $this->fontcacheVersion) {
  2804. // if the font file is old, then clear it out and prepare for re-creation
  2805. $this->addMessage('openFont: clear out, make way for new version.');
  2806. $this->fonts[$font] = null;
  2807. unset($this->fonts[$font]);
  2808. }
  2809. } else {
  2810. $old_cache_name = "php_$metrics_name";
  2811. if (file_exists($fontcache . '/' . $old_cache_name)) {
  2812. $this->addMessage(
  2813. "openFont: php file doesn't exist $fontcache/$cache_name, creating it from the old format"
  2814. );
  2815. $old_cache = file_get_contents($fontcache . '/' . $old_cache_name);
  2816. file_put_contents($fontcache . '/' . $cache_name, '<?php return ' . $old_cache . ';');
  2817. $this->openFont($font);
  2818. return;
  2819. }
  2820. }
  2821. if (!isset($this->fonts[$font]) && file_exists($dir . $metrics_name)) {
  2822. // then rebuild the php_<font>.afm file from the <font>.afm file
  2823. $this->addMessage("openFont: build php file from $dir$metrics_name");
  2824. $data = [];
  2825. // 20 => 'space'
  2826. $data['codeToName'] = [];
  2827. // Since we're not going to enable Unicode for the core fonts we need to use a font-based
  2828. // setting for Unicode support rather than a global setting.
  2829. $data['isUnicode'] = (strtolower(substr($metrics_name, -3)) !== 'afm');
  2830. $cidtogid = '';
  2831. if ($data['isUnicode']) {
  2832. $cidtogid = str_pad('', 256 * 256 * 2, "\x00");
  2833. }
  2834. $file = file($dir . $metrics_name);
  2835. foreach ($file as $rowA) {
  2836. $row = trim($rowA);
  2837. $pos = strpos($row, ' ');
  2838. if ($pos) {
  2839. // then there must be some keyword
  2840. $key = substr($row, 0, $pos);
  2841. switch ($key) {
  2842. case 'FontName':
  2843. case 'FullName':
  2844. case 'FamilyName':
  2845. case 'PostScriptName':
  2846. case 'Weight':
  2847. case 'ItalicAngle':
  2848. case 'IsFixedPitch':
  2849. case 'CharacterSet':
  2850. case 'UnderlinePosition':
  2851. case 'UnderlineThickness':
  2852. case 'Version':
  2853. case 'EncodingScheme':
  2854. case 'CapHeight':
  2855. case 'XHeight':
  2856. case 'Ascender':
  2857. case 'Descender':
  2858. case 'StdHW':
  2859. case 'StdVW':
  2860. case 'StartCharMetrics':
  2861. case 'FontHeightOffset': // OAR - Added so we can offset the height calculation of a Windows font. Otherwise it's too big.
  2862. $data[$key] = trim(substr($row, $pos));
  2863. break;
  2864. case 'FontBBox':
  2865. $data[$key] = explode(' ', trim(substr($row, $pos)));
  2866. break;
  2867. //C 39 ; WX 222 ; N quoteright ; B 53 463 157 718 ;
  2868. case 'C': // Found in AFM files
  2869. $bits = explode(';', trim($row));
  2870. $dtmp = ['C' => null, 'N' => null, 'WX' => null, 'B' => []];
  2871. foreach ($bits as $bit) {
  2872. $bits2 = explode(' ', trim($bit));
  2873. if (mb_strlen($bits2[0], '8bit') == 0) {
  2874. continue;
  2875. }
  2876. if (count($bits2) > 2) {
  2877. $dtmp[$bits2[0]] = [];
  2878. for ($i = 1; $i < count($bits2); $i++) {
  2879. $dtmp[$bits2[0]][] = $bits2[$i];
  2880. }
  2881. } else {
  2882. if (count($bits2) == 2) {
  2883. $dtmp[$bits2[0]] = $bits2[1];
  2884. }
  2885. }
  2886. }
  2887. $c = (int)$dtmp['C'];
  2888. $n = $dtmp['N'];
  2889. $width = floatval($dtmp['WX']);
  2890. if ($c >= 0) {
  2891. if (!ctype_xdigit($n) || $c != hexdec($n)) {
  2892. $data['codeToName'][$c] = $n;
  2893. }
  2894. $data['C'][$c] = $width;
  2895. } elseif (isset($n)) {
  2896. $data['C'][$n] = $width;
  2897. }
  2898. if (!isset($data['MissingWidth']) && $c === -1 && $n === '.notdef') {
  2899. $data['MissingWidth'] = $width;
  2900. }
  2901. break;
  2902. // U 827 ; WX 0 ; N squaresubnosp ; G 675 ;
  2903. case 'U': // Found in UFM files
  2904. if (!$data['isUnicode']) {
  2905. break;
  2906. }
  2907. $bits = explode(';', trim($row));
  2908. $dtmp = ['G' => null, 'N' => null, 'U' => null, 'WX' => null];
  2909. foreach ($bits as $bit) {
  2910. $bits2 = explode(' ', trim($bit));
  2911. if (mb_strlen($bits2[0], '8bit') === 0) {
  2912. continue;
  2913. }
  2914. if (count($bits2) > 2) {
  2915. $dtmp[$bits2[0]] = [];
  2916. for ($i = 1; $i < count($bits2); $i++) {
  2917. $dtmp[$bits2[0]][] = $bits2[$i];
  2918. }
  2919. } else {
  2920. if (count($bits2) == 2) {
  2921. $dtmp[$bits2[0]] = $bits2[1];
  2922. }
  2923. }
  2924. }
  2925. $c = (int)$dtmp['U'];
  2926. $n = $dtmp['N'];
  2927. $glyph = $dtmp['G'];
  2928. $width = floatval($dtmp['WX']);
  2929. if ($c >= 0) {
  2930. // Set values in CID to GID map
  2931. if ($c >= 0 && $c < 0xFFFF && $glyph) {
  2932. $cidtogid[$c * 2] = chr($glyph >> 8);
  2933. $cidtogid[$c * 2 + 1] = chr($glyph & 0xFF);
  2934. }
  2935. if (!ctype_xdigit($n) || $c != hexdec($n)) {
  2936. $data['codeToName'][$c] = $n;
  2937. }
  2938. $data['C'][$c] = $width;
  2939. } elseif (isset($n)) {
  2940. $data['C'][$n] = $width;
  2941. }
  2942. if (!isset($data['MissingWidth']) && $c === -1 && $n === '.notdef') {
  2943. $data['MissingWidth'] = $width;
  2944. }
  2945. break;
  2946. case 'KPX':
  2947. break; // don't include them as they are not used yet
  2948. //KPX Adieresis yacute -40
  2949. /*$bits = explode(' ', trim($row));
  2950. $data['KPX'][$bits[1]][$bits[2]] = $bits[3];
  2951. break;*/
  2952. }
  2953. }
  2954. }
  2955. if ($this->compressionReady && $this->options['compression']) {
  2956. // then implement ZLIB based compression on CIDtoGID string
  2957. $data['CIDtoGID_Compressed'] = true;
  2958. $cidtogid = gzcompress($cidtogid, 6);
  2959. }
  2960. $data['CIDtoGID'] = base64_encode($cidtogid);
  2961. $data['_version_'] = $this->fontcacheVersion;
  2962. $this->fonts[$font] = $data;
  2963. //Because of potential trouble with php safe mode, expect that the folder already exists.
  2964. //If not existing, this will hit performance because of missing cached results.
  2965. if (is_dir($fontcache) && is_writable($fontcache)) {
  2966. file_put_contents($fontcache . '/' . $cache_name, '<?php return ' . var_export($data, true) . ';');
  2967. }
  2968. $data = null;
  2969. }
  2970. if (!isset($this->fonts[$font])) {
  2971. $this->addMessage("openFont: no font file found for $font. Do you need to run load_font.php?");
  2972. }
  2973. //pre_r($this->messages);
  2974. }
  2975. /**
  2976. * if the font is not loaded then load it and make the required object
  2977. * else just make it the current font
  2978. * the encoding array can contain 'encoding'=> 'none','WinAnsiEncoding','MacRomanEncoding' or 'MacExpertEncoding'
  2979. * note that encoding='none' will need to be used for symbolic fonts
  2980. * and 'differences' => an array of mappings between numbers 0->255 and character names.
  2981. *
  2982. * @param $fontName
  2983. * @param string $encoding
  2984. * @param bool $set
  2985. * @param bool $isSubsetting
  2986. * @return int
  2987. * @throws FontNotFoundException
  2988. */
  2989. function selectFont($fontName, $encoding = '', $set = true, $isSubsetting = true)
  2990. {
  2991. $ext = substr($fontName, -4);
  2992. if ($ext === '.afm' || $ext === '.ufm') {
  2993. $fontName = substr($fontName, 0, mb_strlen($fontName) - 4);
  2994. }
  2995. if (!isset($this->fonts[$fontName])) {
  2996. $this->addMessage("selectFont: selecting - $fontName - $encoding, $set");
  2997. // load the file
  2998. $this->openFont($fontName);
  2999. if (isset($this->fonts[$fontName])) {
  3000. $this->numObj++;
  3001. $this->numFonts++;
  3002. $font = &$this->fonts[$fontName];
  3003. $name = basename($fontName);
  3004. $options = ['name' => $name, 'fontFileName' => $fontName, 'isSubsetting' => $isSubsetting];
  3005. if (is_array($encoding)) {
  3006. // then encoding and differences might be set
  3007. if (isset($encoding['encoding'])) {
  3008. $options['encoding'] = $encoding['encoding'];
  3009. }
  3010. if (isset($encoding['differences'])) {
  3011. $options['differences'] = $encoding['differences'];
  3012. }
  3013. } else {
  3014. if (mb_strlen($encoding, '8bit')) {
  3015. // then perhaps only the encoding has been set
  3016. $options['encoding'] = $encoding;
  3017. }
  3018. }
  3019. $this->o_font($this->numObj, 'new', $options);
  3020. if (file_exists("$fontName.ttf")) {
  3021. $fileSuffix = 'ttf';
  3022. } elseif (file_exists("$fontName.TTF")) {
  3023. $fileSuffix = 'TTF';
  3024. } elseif (file_exists("$fontName.pfb")) {
  3025. $fileSuffix = 'pfb';
  3026. } elseif (file_exists("$fontName.PFB")) {
  3027. $fileSuffix = 'PFB';
  3028. } else {
  3029. $fileSuffix = '';
  3030. }
  3031. $font['fileSuffix'] = $fileSuffix;
  3032. $font['fontNum'] = $this->numFonts;
  3033. $font['isSubsetting'] = $isSubsetting && $font['isUnicode'] && strtolower($fileSuffix) === 'ttf';
  3034. // also set the differences here, note that this means that these will take effect only the
  3035. //first time that a font is selected, else they are ignored
  3036. if (isset($options['differences'])) {
  3037. $font['differences'] = $options['differences'];
  3038. }
  3039. }
  3040. }
  3041. if ($set && isset($this->fonts[$fontName])) {
  3042. // so if for some reason the font was not set in the last one then it will not be selected
  3043. $this->currentBaseFont = $fontName;
  3044. // the next lines mean that if a new font is selected, then the current text state will be
  3045. // applied to it as well.
  3046. $this->currentFont = $this->currentBaseFont;
  3047. $this->currentFontNum = $this->fonts[$this->currentFont]['fontNum'];
  3048. }
  3049. return $this->currentFontNum;
  3050. }
  3051. /**
  3052. * sets up the current font, based on the font families, and the current text state
  3053. * note that this system is quite flexible, a bold-italic font can be completely different to a
  3054. * italic-bold font, and even bold-bold will have to be defined within the family to have meaning
  3055. * This function is to be called whenever the currentTextState is changed, it will update
  3056. * the currentFont setting to whatever the appropriate family one is.
  3057. * If the user calls selectFont themselves then that will reset the currentBaseFont, and the currentFont
  3058. * This function will change the currentFont to whatever it should be, but will not change the
  3059. * currentBaseFont.
  3060. */
  3061. private function setCurrentFont()
  3062. {
  3063. // if (strlen($this->currentBaseFont) == 0){
  3064. // // then assume an initial font
  3065. // $this->selectFont($this->defaultFont);
  3066. // }
  3067. // $cf = substr($this->currentBaseFont,strrpos($this->currentBaseFont,'/')+1);
  3068. // if (strlen($this->currentTextState)
  3069. // && isset($this->fontFamilies[$cf])
  3070. // && isset($this->fontFamilies[$cf][$this->currentTextState])){
  3071. // // then we are in some state or another
  3072. // // and this font has a family, and the current setting exists within it
  3073. // // select the font, then return it
  3074. // $nf = substr($this->currentBaseFont,0,strrpos($this->currentBaseFont,'/')+1).$this->fontFamilies[$cf][$this->currentTextState];
  3075. // $this->selectFont($nf,'',0);
  3076. // $this->currentFont = $nf;
  3077. // $this->currentFontNum = $this->fonts[$nf]['fontNum'];
  3078. // } else {
  3079. // // the this font must not have the right family member for the current state
  3080. // // simply assume the base font
  3081. $this->currentFont = $this->currentBaseFont;
  3082. $this->currentFontNum = $this->fonts[$this->currentFont]['fontNum'];
  3083. // }
  3084. }
  3085. /**
  3086. * function for the user to find out what the ID is of the first page that was created during
  3087. * startup - useful if they wish to add something to it later.
  3088. *
  3089. * @return int
  3090. */
  3091. function getFirstPageId()
  3092. {
  3093. return $this->firstPageId;
  3094. }
  3095. /**
  3096. * add content to the currently active object
  3097. *
  3098. * @param $content
  3099. */
  3100. private function addContent($content)
  3101. {
  3102. $this->objects[$this->currentContents]['c'] .= $content;
  3103. }
  3104. /**
  3105. * sets the color for fill operations
  3106. *
  3107. * @param $color
  3108. * @param bool $force
  3109. */
  3110. function setColor($color, $force = false)
  3111. {
  3112. $new_color = [$color[0], $color[1], $color[2], isset($color[3]) ? $color[3] : null];
  3113. if (!$force && $this->currentColor == $new_color) {
  3114. return;
  3115. }
  3116. if (isset($new_color[3])) {
  3117. $this->currentColor = $new_color;
  3118. $this->addContent(vsprintf("\n%.3F %.3F %.3F %.3F k", $this->currentColor));
  3119. } else {
  3120. if (isset($new_color[2])) {
  3121. $this->currentColor = $new_color;
  3122. $this->addContent(vsprintf("\n%.3F %.3F %.3F rg", $this->currentColor));
  3123. }
  3124. }
  3125. }
  3126. /**
  3127. * sets the color for fill operations
  3128. *
  3129. * @param $fillRule
  3130. */
  3131. function setFillRule($fillRule)
  3132. {
  3133. if (!in_array($fillRule, ["nonzero", "evenodd"])) {
  3134. return;
  3135. }
  3136. $this->fillRule = $fillRule;
  3137. }
  3138. /**
  3139. * sets the color for stroke operations
  3140. *
  3141. * @param $color
  3142. * @param bool $force
  3143. */
  3144. function setStrokeColor($color, $force = false)
  3145. {
  3146. $new_color = [$color[0], $color[1], $color[2], isset($color[3]) ? $color[3] : null];
  3147. if (!$force && $this->currentStrokeColor == $new_color) {
  3148. return;
  3149. }
  3150. if (isset($new_color[3])) {
  3151. $this->currentStrokeColor = $new_color;
  3152. $this->addContent(vsprintf("\n%.3F %.3F %.3F %.3F K", $this->currentStrokeColor));
  3153. } else {
  3154. if (isset($new_color[2])) {
  3155. $this->currentStrokeColor = $new_color;
  3156. $this->addContent(vsprintf("\n%.3F %.3F %.3F RG", $this->currentStrokeColor));
  3157. }
  3158. }
  3159. }
  3160. /**
  3161. * Set the graphics state for compositions
  3162. *
  3163. * @param $parameters
  3164. */
  3165. function setGraphicsState($parameters)
  3166. {
  3167. // Create a new graphics state object if necessary
  3168. if (($gstate = array_search($parameters, $this->gstates)) === false) {
  3169. $this->numObj++;
  3170. $this->o_extGState($this->numObj, 'new', $parameters);
  3171. $gstate = $this->numStates;
  3172. $this->gstates[$gstate] = $parameters;
  3173. }
  3174. $this->addContent("\n/GS$gstate gs");
  3175. }
  3176. /**
  3177. * Set current blend mode & opacity for lines.
  3178. *
  3179. * Valid blend modes are:
  3180. *
  3181. * Normal, Multiply, Screen, Overlay, Darken, Lighten,
  3182. * ColorDogde, ColorBurn, HardLight, SoftLight, Difference,
  3183. * Exclusion
  3184. *
  3185. * @param string $mode the blend mode to use
  3186. * @param float $opacity 0.0 fully transparent, 1.0 fully opaque
  3187. */
  3188. function setLineTransparency($mode, $opacity)
  3189. {
  3190. static $blend_modes = [
  3191. "Normal",
  3192. "Multiply",
  3193. "Screen",
  3194. "Overlay",
  3195. "Darken",
  3196. "Lighten",
  3197. "ColorDogde",
  3198. "ColorBurn",
  3199. "HardLight",
  3200. "SoftLight",
  3201. "Difference",
  3202. "Exclusion"
  3203. ];
  3204. if (!in_array($mode, $blend_modes)) {
  3205. $mode = "Normal";
  3206. }
  3207. // Only create a new graphics state if required
  3208. if ($mode === $this->currentLineTransparency["mode"] &&
  3209. $opacity == $this->currentLineTransparency["opacity"]
  3210. ) {
  3211. return;
  3212. }
  3213. $this->currentLineTransparency["mode"] = $mode;
  3214. $this->currentLineTransparency["opacity"] = $opacity;
  3215. $options = [
  3216. "BM" => "/$mode",
  3217. "CA" => (float)$opacity
  3218. ];
  3219. $this->setGraphicsState($options);
  3220. }
  3221. /**
  3222. * Set current blend mode & opacity for filled objects.
  3223. *
  3224. * Valid blend modes are:
  3225. *
  3226. * Normal, Multiply, Screen, Overlay, Darken, Lighten,
  3227. * ColorDogde, ColorBurn, HardLight, SoftLight, Difference,
  3228. * Exclusion
  3229. *
  3230. * @param string $mode the blend mode to use
  3231. * @param float $opacity 0.0 fully transparent, 1.0 fully opaque
  3232. */
  3233. function setFillTransparency($mode, $opacity)
  3234. {
  3235. static $blend_modes = [
  3236. "Normal",
  3237. "Multiply",
  3238. "Screen",
  3239. "Overlay",
  3240. "Darken",
  3241. "Lighten",
  3242. "ColorDogde",
  3243. "ColorBurn",
  3244. "HardLight",
  3245. "SoftLight",
  3246. "Difference",
  3247. "Exclusion"
  3248. ];
  3249. if (!in_array($mode, $blend_modes)) {
  3250. $mode = "Normal";
  3251. }
  3252. if ($mode === $this->currentFillTransparency["mode"] &&
  3253. $opacity == $this->currentFillTransparency["opacity"]
  3254. ) {
  3255. return;
  3256. }
  3257. $this->currentFillTransparency["mode"] = $mode;
  3258. $this->currentFillTransparency["opacity"] = $opacity;
  3259. $options = [
  3260. "BM" => "/$mode",
  3261. "ca" => (float)$opacity,
  3262. ];
  3263. $this->setGraphicsState($options);
  3264. }
  3265. /**
  3266. * draw a line from one set of coordinates to another
  3267. *
  3268. * @param $x1
  3269. * @param $y1
  3270. * @param $x2
  3271. * @param $y2
  3272. * @param bool $stroke
  3273. */
  3274. function line($x1, $y1, $x2, $y2, $stroke = true)
  3275. {
  3276. $this->addContent(sprintf("\n%.3F %.3F m %.3F %.3F l", $x1, $y1, $x2, $y2));
  3277. if ($stroke) {
  3278. $this->addContent(' S');
  3279. }
  3280. }
  3281. /**
  3282. * draw a bezier curve based on 4 control points
  3283. *
  3284. * @param $x0
  3285. * @param $y0
  3286. * @param $x1
  3287. * @param $y1
  3288. * @param $x2
  3289. * @param $y2
  3290. * @param $x3
  3291. * @param $y3
  3292. */
  3293. function curve($x0, $y0, $x1, $y1, $x2, $y2, $x3, $y3)
  3294. {
  3295. // in the current line style, draw a bezier curve from (x0,y0) to (x3,y3) using the other two points
  3296. // as the control points for the curve.
  3297. $this->addContent(
  3298. sprintf("\n%.3F %.3F m %.3F %.3F %.3F %.3F %.3F %.3F c S", $x0, $y0, $x1, $y1, $x2, $y2, $x3, $y3)
  3299. );
  3300. }
  3301. /**
  3302. * draw a part of an ellipse
  3303. *
  3304. * @param $x0
  3305. * @param $y0
  3306. * @param $astart
  3307. * @param $afinish
  3308. * @param $r1
  3309. * @param int $r2
  3310. * @param int $angle
  3311. * @param int $nSeg
  3312. */
  3313. function partEllipse($x0, $y0, $astart, $afinish, $r1, $r2 = 0, $angle = 0, $nSeg = 8)
  3314. {
  3315. $this->ellipse($x0, $y0, $r1, $r2, $angle, $nSeg, $astart, $afinish, false);
  3316. }
  3317. /**
  3318. * draw a filled ellipse
  3319. *
  3320. * @param $x0
  3321. * @param $y0
  3322. * @param $r1
  3323. * @param int $r2
  3324. * @param int $angle
  3325. * @param int $nSeg
  3326. * @param int $astart
  3327. * @param int $afinish
  3328. */
  3329. function filledEllipse($x0, $y0, $r1, $r2 = 0, $angle = 0, $nSeg = 8, $astart = 0, $afinish = 360)
  3330. {
  3331. $this->ellipse($x0, $y0, $r1, $r2, $angle, $nSeg, $astart, $afinish, true, true);
  3332. }
  3333. /**
  3334. * @param $x
  3335. * @param $y
  3336. */
  3337. function lineTo($x, $y)
  3338. {
  3339. $this->addContent(sprintf("\n%.3F %.3F l", $x, $y));
  3340. }
  3341. /**
  3342. * @param $x
  3343. * @param $y
  3344. */
  3345. function moveTo($x, $y)
  3346. {
  3347. $this->addContent(sprintf("\n%.3F %.3F m", $x, $y));
  3348. }
  3349. /**
  3350. * draw a bezier curve based on 4 control points
  3351. *
  3352. * @param $x1
  3353. * @param $y1
  3354. * @param $x2
  3355. * @param $y2
  3356. * @param $x3
  3357. * @param $y3
  3358. */
  3359. function curveTo($x1, $y1, $x2, $y2, $x3, $y3)
  3360. {
  3361. $this->addContent(sprintf("\n%.3F %.3F %.3F %.3F %.3F %.3F c", $x1, $y1, $x2, $y2, $x3, $y3));
  3362. }
  3363. /**
  3364. * draw a bezier curve based on 4 control points
  3365. */
  3366. function quadTo($cpx, $cpy, $x, $y)
  3367. {
  3368. $this->addContent(sprintf("\n%.3F %.3F %.3F %.3F v", $cpx, $cpy, $x, $y));
  3369. }
  3370. function closePath()
  3371. {
  3372. $this->addContent(' h');
  3373. }
  3374. function endPath()
  3375. {
  3376. $this->addContent(' n');
  3377. }
  3378. /**
  3379. * draw an ellipse
  3380. * note that the part and filled ellipse are just special cases of this function
  3381. *
  3382. * draws an ellipse in the current line style
  3383. * centered at $x0,$y0, radii $r1,$r2
  3384. * if $r2 is not set, then a circle is drawn
  3385. * from $astart to $afinish, measured in degrees, running anti-clockwise from the right hand side of the ellipse.
  3386. * nSeg is not allowed to be less than 2, as this will simply draw a line (and will even draw a
  3387. * pretty crappy shape at 2, as we are approximating with bezier curves.
  3388. *
  3389. * @param $x0
  3390. * @param $y0
  3391. * @param $r1
  3392. * @param int $r2
  3393. * @param int $angle
  3394. * @param int $nSeg
  3395. * @param int $astart
  3396. * @param int $afinish
  3397. * @param bool $close
  3398. * @param bool $fill
  3399. * @param bool $stroke
  3400. * @param bool $incomplete
  3401. */
  3402. function ellipse(
  3403. $x0,
  3404. $y0,
  3405. $r1,
  3406. $r2 = 0,
  3407. $angle = 0,
  3408. $nSeg = 8,
  3409. $astart = 0,
  3410. $afinish = 360,
  3411. $close = true,
  3412. $fill = false,
  3413. $stroke = true,
  3414. $incomplete = false
  3415. ) {
  3416. if ($r1 == 0) {
  3417. return;
  3418. }
  3419. if ($r2 == 0) {
  3420. $r2 = $r1;
  3421. }
  3422. if ($nSeg < 2) {
  3423. $nSeg = 2;
  3424. }
  3425. $astart = deg2rad((float)$astart);
  3426. $afinish = deg2rad((float)$afinish);
  3427. $totalAngle = $afinish - $astart;
  3428. $dt = $totalAngle / $nSeg;
  3429. $dtm = $dt / 3;
  3430. if ($angle != 0) {
  3431. $a = -1 * deg2rad((float)$angle);
  3432. $this->addContent(
  3433. sprintf("\n q %.3F %.3F %.3F %.3F %.3F %.3F cm", cos($a), -sin($a), sin($a), cos($a), $x0, $y0)
  3434. );
  3435. $x0 = 0;
  3436. $y0 = 0;
  3437. }
  3438. $t1 = $astart;
  3439. $a0 = $x0 + $r1 * cos($t1);
  3440. $b0 = $y0 + $r2 * sin($t1);
  3441. $c0 = -$r1 * sin($t1);
  3442. $d0 = $r2 * cos($t1);
  3443. if (!$incomplete) {
  3444. $this->addContent(sprintf("\n%.3F %.3F m ", $a0, $b0));
  3445. }
  3446. for ($i = 1; $i <= $nSeg; $i++) {
  3447. // draw this bit of the total curve
  3448. $t1 = $i * $dt + $astart;
  3449. $a1 = $x0 + $r1 * cos($t1);
  3450. $b1 = $y0 + $r2 * sin($t1);
  3451. $c1 = -$r1 * sin($t1);
  3452. $d1 = $r2 * cos($t1);
  3453. $this->addContent(
  3454. sprintf(
  3455. "\n%.3F %.3F %.3F %.3F %.3F %.3F c",
  3456. ($a0 + $c0 * $dtm),
  3457. ($b0 + $d0 * $dtm),
  3458. ($a1 - $c1 * $dtm),
  3459. ($b1 - $d1 * $dtm),
  3460. $a1,
  3461. $b1
  3462. )
  3463. );
  3464. $a0 = $a1;
  3465. $b0 = $b1;
  3466. $c0 = $c1;
  3467. $d0 = $d1;
  3468. }
  3469. if (!$incomplete) {
  3470. if ($fill) {
  3471. $this->addContent(' f');
  3472. }
  3473. if ($stroke) {
  3474. if ($close) {
  3475. $this->addContent(' s'); // small 's' signifies closing the path as well
  3476. } else {
  3477. $this->addContent(' S');
  3478. }
  3479. }
  3480. }
  3481. if ($angle != 0) {
  3482. $this->addContent(' Q');
  3483. }
  3484. }
  3485. /**
  3486. * this sets the line drawing style.
  3487. * width, is the thickness of the line in user units
  3488. * cap is the type of cap to put on the line, values can be 'butt','round','square'
  3489. * where the diffference between 'square' and 'butt' is that 'square' projects a flat end past the
  3490. * end of the line.
  3491. * join can be 'miter', 'round', 'bevel'
  3492. * dash is an array which sets the dash pattern, is a series of length values, which are the lengths of the
  3493. * on and off dashes.
  3494. * (2) represents 2 on, 2 off, 2 on , 2 off ...
  3495. * (2,1) is 2 on, 1 off, 2 on, 1 off.. etc
  3496. * phase is a modifier on the dash pattern which is used to shift the point at which the pattern starts.
  3497. *
  3498. * @param int $width
  3499. * @param string $cap
  3500. * @param string $join
  3501. * @param string $dash
  3502. * @param int $phase
  3503. */
  3504. function setLineStyle($width = 1, $cap = '', $join = '', $dash = '', $phase = 0)
  3505. {
  3506. // this is quite inefficient in that it sets all the parameters whenever 1 is changed, but will fix another day
  3507. $string = '';
  3508. if ($width > 0) {
  3509. $string .= "$width w";
  3510. }
  3511. $ca = ['butt' => 0, 'round' => 1, 'square' => 2];
  3512. if (isset($ca[$cap])) {
  3513. $string .= " $ca[$cap] J";
  3514. }
  3515. $ja = ['miter' => 0, 'round' => 1, 'bevel' => 2];
  3516. if (isset($ja[$join])) {
  3517. $string .= " $ja[$join] j";
  3518. }
  3519. if (is_array($dash)) {
  3520. $string .= ' [ ' . implode(' ', $dash) . " ] $phase d";
  3521. }
  3522. $this->currentLineStyle = $string;
  3523. $this->addContent("\n$string");
  3524. }
  3525. /**
  3526. * draw a polygon, the syntax for this is similar to the GD polygon command
  3527. *
  3528. * @param $p
  3529. * @param $np
  3530. * @param bool $f
  3531. */
  3532. function polygon($p, $np, $f = false)
  3533. {
  3534. $this->addContent(sprintf("\n%.3F %.3F m ", $p[0], $p[1]));
  3535. for ($i = 2; $i < $np * 2; $i = $i + 2) {
  3536. $this->addContent(sprintf("%.3F %.3F l ", $p[$i], $p[$i + 1]));
  3537. }
  3538. if ($f) {
  3539. $this->addContent(' f');
  3540. } else {
  3541. $this->addContent(' S');
  3542. }
  3543. }
  3544. /**
  3545. * a filled rectangle, note that it is the width and height of the rectangle which are the secondary parameters, not
  3546. * the coordinates of the upper-right corner
  3547. *
  3548. * @param $x1
  3549. * @param $y1
  3550. * @param $width
  3551. * @param $height
  3552. */
  3553. function filledRectangle($x1, $y1, $width, $height)
  3554. {
  3555. $this->addContent(sprintf("\n%.3F %.3F %.3F %.3F re f", $x1, $y1, $width, $height));
  3556. }
  3557. /**
  3558. * draw a rectangle, note that it is the width and height of the rectangle which are the secondary parameters, not
  3559. * the coordinates of the upper-right corner
  3560. *
  3561. * @param $x1
  3562. * @param $y1
  3563. * @param $width
  3564. * @param $height
  3565. */
  3566. function rectangle($x1, $y1, $width, $height)
  3567. {
  3568. $this->addContent(sprintf("\n%.3F %.3F %.3F %.3F re S", $x1, $y1, $width, $height));
  3569. }
  3570. /**
  3571. * draw a rectangle, note that it is the width and height of the rectangle which are the secondary parameters, not
  3572. * the coordinates of the upper-right corner
  3573. *
  3574. * @param $x1
  3575. * @param $y1
  3576. * @param $width
  3577. * @param $height
  3578. */
  3579. function rect($x1, $y1, $width, $height)
  3580. {
  3581. $this->addContent(sprintf("\n%.3F %.3F %.3F %.3F re", $x1, $y1, $width, $height));
  3582. }
  3583. function stroke()
  3584. {
  3585. $this->addContent("\nS");
  3586. }
  3587. function fill()
  3588. {
  3589. $this->addContent("\nf" . ($this->fillRule === "evenodd" ? "*" : ""));
  3590. }
  3591. function fillStroke()
  3592. {
  3593. $this->addContent("\nb" . ($this->fillRule === "evenodd" ? "*" : ""));
  3594. }
  3595. /**
  3596. * @param string $subtype
  3597. * @param integer $x
  3598. * @param integer $y
  3599. * @param integer $w
  3600. * @param integer $h
  3601. * @return int
  3602. */
  3603. function addXObject($subtype, $x, $y, $w, $h)
  3604. {
  3605. $id = ++$this->numObj;
  3606. $this->o_xobject($id, 'new', ['Subtype' => $subtype, 'bbox' => [$x, $y, $w, $h]]);
  3607. return $id;
  3608. }
  3609. /**
  3610. * @param integer $numXObject
  3611. * @param string $type
  3612. * @param array $options
  3613. */
  3614. function setXObjectResource($numXObject, $type, $options)
  3615. {
  3616. if (in_array($type, ['procset', 'font', 'xObject'])) {
  3617. $this->o_xobject($numXObject, $type, $options);
  3618. }
  3619. }
  3620. /**
  3621. * add signature
  3622. *
  3623. * $fieldSigId = $cpdf->addFormField(Cpdf::ACROFORM_FIELD_SIG, 'Signature1', 0, 0, 0, 0, 0);
  3624. *
  3625. * $signatureId = $cpdf->addSignature([
  3626. * 'signcert' => file_get_contents('dompdf.crt'),
  3627. * 'privkey' => file_get_contents('dompdf.key'),
  3628. * 'password' => 'password',
  3629. * 'name' => 'DomPDF DEMO',
  3630. * 'location' => 'Home',
  3631. * 'reason' => 'First Form',
  3632. * 'contactinfo' => 'info'
  3633. * ]);
  3634. * $cpdf->setFormFieldValue($fieldSigId, "$signatureId 0 R");
  3635. *
  3636. * @param string $signcert
  3637. * @param string $privkey
  3638. * @param string $password
  3639. * @param string|null $name
  3640. * @param string|null $location
  3641. * @param string|null $reason
  3642. * @param string|null $contactinfo
  3643. * @return int
  3644. */
  3645. function addSignature($signcert, $privkey, $password = '',
  3646. $name = null, $location = null, $reason = null, $contactinfo = null
  3647. ) {
  3648. $sigId = ++$this->numObj;
  3649. $this->o_sig($sigId, 'new', [
  3650. 'SignCert' => $signcert,
  3651. 'PrivKey' => $privkey,
  3652. 'Password' => $password,
  3653. 'Name' => $name,
  3654. 'Location' => $location,
  3655. 'Reason' => $reason,
  3656. 'ContactInfo' => $contactinfo
  3657. ]);
  3658. return $sigId;
  3659. }
  3660. /**
  3661. * add field to form
  3662. *
  3663. * @param string $type ACROFORM_FIELD_*
  3664. * @param string $name
  3665. * @param $x0
  3666. * @param $y0
  3667. * @param $x1
  3668. * @param $y1
  3669. * @param integer $ff Field Flag ACROFORM_FIELD_*_*
  3670. * @param float $size
  3671. * @param array $color
  3672. * @return int
  3673. */
  3674. public function addFormField($type, $name, $x0, $y0, $x1, $y1, $ff = 0, $size = 10.0, $color = [0, 0, 0])
  3675. {
  3676. if (!$this->numFonts) {
  3677. $this->selectFont($this->defaultFont);
  3678. }
  3679. $color = implode(' ', $color) . ' rg';
  3680. $currentFontNum = $this->currentFontNum;
  3681. $font = array_filter($this->objects[$this->currentNode]['info']['fonts'],
  3682. function($item) use ($currentFontNum) { return $item['fontNum'] == $currentFontNum; });
  3683. $this->o_acroform($this->acroFormId, 'font',
  3684. ['objNum' => $font[0]['objNum'], 'fontNum' => $font[0]['fontNum']]);
  3685. $fieldId = ++$this->numObj;
  3686. $this->o_field($fieldId, 'new', [
  3687. 'rect' => [$x0, $y0, $x1, $y1],
  3688. 'F' => 4,
  3689. 'FT' => "/$type",
  3690. 'T' => $name,
  3691. 'Ff' => $ff,
  3692. 'pageid' => $this->currentPage,
  3693. 'da' => "$color /F$this->currentFontNum " . sprintf('%.1F Tf ', $size)
  3694. ]);
  3695. return $fieldId;
  3696. }
  3697. /**
  3698. * set Field value
  3699. *
  3700. * @param integer $numFieldObj
  3701. * @param string $value
  3702. */
  3703. public function setFormFieldValue($numFieldObj, $value)
  3704. {
  3705. $this->o_field($numFieldObj, 'set', ['value' => $value]);
  3706. }
  3707. /**
  3708. * set Field value (reference)
  3709. *
  3710. * @param integer $numFieldObj
  3711. * @param integer $numObj Object number
  3712. */
  3713. public function setFormFieldRefValue($numFieldObj, $numObj)
  3714. {
  3715. $this->o_field($numFieldObj, 'set', ['refvalue' => $numObj]);
  3716. }
  3717. /**
  3718. * set Field Appearanc (reference)
  3719. *
  3720. * @param integer $numFieldObj
  3721. * @param integer $normalNumObj
  3722. * @param integer|null $rolloverNumObj
  3723. * @param integer|null $downNumObj
  3724. */
  3725. public function setFormFieldAppearance($numFieldObj, $normalNumObj, $rolloverNumObj = null, $downNumObj = null)
  3726. {
  3727. $appearance['N'] = $normalNumObj;
  3728. if ($rolloverNumObj !== null) {
  3729. $appearance['R'] = $rolloverNumObj;
  3730. }
  3731. if ($downNumObj !== null) {
  3732. $appearance['D'] = $downNumObj;
  3733. }
  3734. $this->o_field($numFieldObj, 'set', ['appearance' => $appearance]);
  3735. }
  3736. /**
  3737. * set Choice Field option values
  3738. *
  3739. * @param integer $numFieldObj
  3740. * @param array $value
  3741. */
  3742. public function setFormFieldOpt($numFieldObj, $value)
  3743. {
  3744. $this->o_field($numFieldObj, 'set', ['options' => $value]);
  3745. }
  3746. /**
  3747. * add form to document
  3748. *
  3749. * @param integer $sigFlags
  3750. * @param boolean $needAppearances
  3751. */
  3752. public function addForm($sigFlags = 0, $needAppearances = false)
  3753. {
  3754. $this->acroFormId = ++$this->numObj;
  3755. $this->o_acroform($this->acroFormId, 'new', [
  3756. 'NeedAppearances' => $needAppearances ? 'true' : 'false',
  3757. 'SigFlags' => $sigFlags
  3758. ]);
  3759. }
  3760. /**
  3761. * save the current graphic state
  3762. */
  3763. function save()
  3764. {
  3765. // we must reset the color cache or it will keep bad colors after clipping
  3766. $this->currentColor = null;
  3767. $this->currentStrokeColor = null;
  3768. $this->addContent("\nq");
  3769. }
  3770. /**
  3771. * restore the last graphic state
  3772. */
  3773. function restore()
  3774. {
  3775. // we must reset the color cache or it will keep bad colors after clipping
  3776. $this->currentColor = null;
  3777. $this->currentStrokeColor = null;
  3778. $this->addContent("\nQ");
  3779. }
  3780. /**
  3781. * draw a clipping rectangle, all the elements added after this will be clipped
  3782. *
  3783. * @param $x1
  3784. * @param $y1
  3785. * @param $width
  3786. * @param $height
  3787. */
  3788. function clippingRectangle($x1, $y1, $width, $height)
  3789. {
  3790. $this->save();
  3791. $this->addContent(sprintf("\n%.3F %.3F %.3F %.3F re W n", $x1, $y1, $width, $height));
  3792. }
  3793. /**
  3794. * draw a clipping rounded rectangle, all the elements added after this will be clipped
  3795. *
  3796. * @param $x1
  3797. * @param $y1
  3798. * @param $w
  3799. * @param $h
  3800. * @param $rTL
  3801. * @param $rTR
  3802. * @param $rBR
  3803. * @param $rBL
  3804. */
  3805. function clippingRectangleRounded($x1, $y1, $w, $h, $rTL, $rTR, $rBR, $rBL)
  3806. {
  3807. $this->save();
  3808. // start: top edge, left end
  3809. $this->addContent(sprintf("\n%.3F %.3F m ", $x1, $y1 - $rTL + $h));
  3810. // line: bottom edge, left end
  3811. $this->addContent(sprintf("\n%.3F %.3F l ", $x1, $y1 + $rBL));
  3812. // curve: bottom-left corner
  3813. $this->ellipse($x1 + $rBL, $y1 + $rBL, $rBL, 0, 0, 8, 180, 270, false, false, false, true);
  3814. // line: right edge, bottom end
  3815. $this->addContent(sprintf("\n%.3F %.3F l ", $x1 + $w - $rBR, $y1));
  3816. // curve: bottom-right corner
  3817. $this->ellipse($x1 + $w - $rBR, $y1 + $rBR, $rBR, 0, 0, 8, 270, 360, false, false, false, true);
  3818. // line: right edge, top end
  3819. $this->addContent(sprintf("\n%.3F %.3F l ", $x1 + $w, $y1 + $h - $rTR));
  3820. // curve: bottom-right corner
  3821. $this->ellipse($x1 + $w - $rTR, $y1 + $h - $rTR, $rTR, 0, 0, 8, 0, 90, false, false, false, true);
  3822. // line: bottom edge, right end
  3823. $this->addContent(sprintf("\n%.3F %.3F l ", $x1 + $rTL, $y1 + $h));
  3824. // curve: top-right corner
  3825. $this->ellipse($x1 + $rTL, $y1 + $h - $rTL, $rTL, 0, 0, 8, 90, 180, false, false, false, true);
  3826. // line: top edge, left end
  3827. $this->addContent(sprintf("\n%.3F %.3F l ", $x1 + $rBL, $y1));
  3828. // Close & clip
  3829. $this->addContent(" W n");
  3830. }
  3831. /**
  3832. * ends the last clipping shape
  3833. */
  3834. function clippingEnd()
  3835. {
  3836. $this->restore();
  3837. }
  3838. /**
  3839. * scale
  3840. *
  3841. * @param float $s_x scaling factor for width as percent
  3842. * @param float $s_y scaling factor for height as percent
  3843. * @param float $x Origin abscissa
  3844. * @param float $y Origin ordinate
  3845. */
  3846. function scale($s_x, $s_y, $x, $y)
  3847. {
  3848. $y = $this->currentPageSize["height"] - $y;
  3849. $tm = [
  3850. $s_x,
  3851. 0,
  3852. 0,
  3853. $s_y,
  3854. $x * (1 - $s_x),
  3855. $y * (1 - $s_y)
  3856. ];
  3857. $this->transform($tm);
  3858. }
  3859. /**
  3860. * translate
  3861. *
  3862. * @param float $t_x movement to the right
  3863. * @param float $t_y movement to the bottom
  3864. */
  3865. function translate($t_x, $t_y)
  3866. {
  3867. $tm = [
  3868. 1,
  3869. 0,
  3870. 0,
  3871. 1,
  3872. $t_x,
  3873. -$t_y
  3874. ];
  3875. $this->transform($tm);
  3876. }
  3877. /**
  3878. * rotate
  3879. *
  3880. * @param float $angle angle in degrees for counter-clockwise rotation
  3881. * @param float $x Origin abscissa
  3882. * @param float $y Origin ordinate
  3883. */
  3884. function rotate($angle, $x, $y)
  3885. {
  3886. $y = $this->currentPageSize["height"] - $y;
  3887. $a = deg2rad($angle);
  3888. $cos_a = cos($a);
  3889. $sin_a = sin($a);
  3890. $tm = [
  3891. $cos_a,
  3892. -$sin_a,
  3893. $sin_a,
  3894. $cos_a,
  3895. $x - $sin_a * $y - $cos_a * $x,
  3896. $y - $cos_a * $y + $sin_a * $x,
  3897. ];
  3898. $this->transform($tm);
  3899. }
  3900. /**
  3901. * skew
  3902. *
  3903. * @param float $angle_x
  3904. * @param float $angle_y
  3905. * @param float $x Origin abscissa
  3906. * @param float $y Origin ordinate
  3907. */
  3908. function skew($angle_x, $angle_y, $x, $y)
  3909. {
  3910. $y = $this->currentPageSize["height"] - $y;
  3911. $tan_x = tan(deg2rad($angle_x));
  3912. $tan_y = tan(deg2rad($angle_y));
  3913. $tm = [
  3914. 1,
  3915. -$tan_y,
  3916. -$tan_x,
  3917. 1,
  3918. $tan_x * $y,
  3919. $tan_y * $x,
  3920. ];
  3921. $this->transform($tm);
  3922. }
  3923. /**
  3924. * apply graphic transformations
  3925. *
  3926. * @param array $tm transformation matrix
  3927. */
  3928. function transform($tm)
  3929. {
  3930. $this->addContent(vsprintf("\n %.3F %.3F %.3F %.3F %.3F %.3F cm", $tm));
  3931. }
  3932. /**
  3933. * add a new page to the document
  3934. * this also makes the new page the current active object
  3935. *
  3936. * @param int $insert
  3937. * @param int $id
  3938. * @param string $pos
  3939. * @return int
  3940. */
  3941. function newPage($insert = 0, $id = 0, $pos = 'after')
  3942. {
  3943. // if there is a state saved, then go up the stack closing them
  3944. // then on the new page, re-open them with the right setings
  3945. if ($this->nStateStack) {
  3946. for ($i = $this->nStateStack; $i >= 1; $i--) {
  3947. $this->restoreState($i);
  3948. }
  3949. }
  3950. $this->numObj++;
  3951. if ($insert) {
  3952. // the id from the ezPdf class is the id of the contents of the page, not the page object itself
  3953. // query that object to find the parent
  3954. $rid = $this->objects[$id]['onPage'];
  3955. $opt = ['rid' => $rid, 'pos' => $pos];
  3956. $this->o_page($this->numObj, 'new', $opt);
  3957. } else {
  3958. $this->o_page($this->numObj, 'new');
  3959. }
  3960. // if there is a stack saved, then put that onto the page
  3961. if ($this->nStateStack) {
  3962. for ($i = 1; $i <= $this->nStateStack; $i++) {
  3963. $this->saveState($i);
  3964. }
  3965. }
  3966. // and if there has been a stroke or fill color set, then transfer them
  3967. if (isset($this->currentColor)) {
  3968. $this->setColor($this->currentColor, true);
  3969. }
  3970. if (isset($this->currentStrokeColor)) {
  3971. $this->setStrokeColor($this->currentStrokeColor, true);
  3972. }
  3973. // if there is a line style set, then put this in too
  3974. if (mb_strlen($this->currentLineStyle, '8bit')) {
  3975. $this->addContent("\n$this->currentLineStyle");
  3976. }
  3977. // the call to the o_page object set currentContents to the present page, so this can be returned as the page id
  3978. return $this->currentContents;
  3979. }
  3980. /**
  3981. * Streams the PDF to the client.
  3982. *
  3983. * @param string $filename The filename to present to the client.
  3984. * @param array $options Associative array: 'compress' => 1 or 0 (default 1); 'Attachment' => 1 or 0 (default 1).
  3985. */
  3986. function stream($filename = "document.pdf", $options = [])
  3987. {
  3988. if (headers_sent()) {
  3989. die("Unable to stream pdf: headers already sent");
  3990. }
  3991. if (!isset($options["compress"])) $options["compress"] = true;
  3992. if (!isset($options["Attachment"])) $options["Attachment"] = true;
  3993. $debug = !$options['compress'];
  3994. $tmp = ltrim($this->output($debug));
  3995. header("Cache-Control: private");
  3996. header("Content-Type: application/pdf");
  3997. header("Content-Length: " . mb_strlen($tmp, "8bit"));
  3998. $filename = str_replace(["\n", "'"], "", basename($filename, ".pdf")) . ".pdf";
  3999. $attachment = $options["Attachment"] ? "attachment" : "inline";
  4000. $encoding = mb_detect_encoding($filename);
  4001. $fallbackfilename = mb_convert_encoding($filename, "ISO-8859-1", $encoding);
  4002. $fallbackfilename = str_replace("\"", "", $fallbackfilename);
  4003. $encodedfilename = rawurlencode($filename);
  4004. $contentDisposition = "Content-Disposition: $attachment; filename=\"$fallbackfilename\"";
  4005. if ($fallbackfilename !== $filename) {
  4006. $contentDisposition .= "; filename*=UTF-8''$encodedfilename";
  4007. }
  4008. header($contentDisposition);
  4009. echo $tmp;
  4010. flush();
  4011. }
  4012. /**
  4013. * return the height in units of the current font in the given size
  4014. *
  4015. * @param $size
  4016. * @return float|int
  4017. */
  4018. function getFontHeight($size)
  4019. {
  4020. if (!$this->numFonts) {
  4021. $this->selectFont($this->defaultFont);
  4022. }
  4023. $font = $this->fonts[$this->currentFont];
  4024. // for the current font, and the given size, what is the height of the font in user units
  4025. if (isset($font['Ascender']) && isset($font['Descender'])) {
  4026. $h = $font['Ascender'] - $font['Descender'];
  4027. } else {
  4028. $h = $font['FontBBox'][3] - $font['FontBBox'][1];
  4029. }
  4030. // have to adjust by a font offset for Windows fonts. unfortunately it looks like
  4031. // the bounding box calculations are wrong and I don't know why.
  4032. if (isset($font['FontHeightOffset'])) {
  4033. // For CourierNew from Windows this needs to be -646 to match the
  4034. // Adobe native Courier font.
  4035. //
  4036. // For FreeMono from GNU this needs to be -337 to match the
  4037. // Courier font.
  4038. //
  4039. // Both have been added manually to the .afm and .ufm files.
  4040. $h += (int)$font['FontHeightOffset'];
  4041. }
  4042. return $size * $h / 1000;
  4043. }
  4044. /**
  4045. * @param $size
  4046. * @return float|int
  4047. */
  4048. function getFontXHeight($size)
  4049. {
  4050. if (!$this->numFonts) {
  4051. $this->selectFont($this->defaultFont);
  4052. }
  4053. $font = $this->fonts[$this->currentFont];
  4054. // for the current font, and the given size, what is the height of the font in user units
  4055. if (isset($font['XHeight'])) {
  4056. $xh = $font['Ascender'] - $font['Descender'];
  4057. } else {
  4058. $xh = $this->getFontHeight($size) / 2;
  4059. }
  4060. return $size * $xh / 1000;
  4061. }
  4062. /**
  4063. * return the font descender, this will normally return a negative number
  4064. * if you add this number to the baseline, you get the level of the bottom of the font
  4065. * it is in the pdf user units
  4066. *
  4067. * @param $size
  4068. * @return float|int
  4069. */
  4070. function getFontDescender($size)
  4071. {
  4072. // note that this will most likely return a negative value
  4073. if (!$this->numFonts) {
  4074. $this->selectFont($this->defaultFont);
  4075. }
  4076. //$h = $this->fonts[$this->currentFont]['FontBBox'][1];
  4077. $h = $this->fonts[$this->currentFont]['Descender'];
  4078. return $size * $h / 1000;
  4079. }
  4080. /**
  4081. * filter the text, this is applied to all text just before being inserted into the pdf document
  4082. * it escapes the various things that need to be escaped, and so on
  4083. *
  4084. * @access private
  4085. *
  4086. * @param $text
  4087. * @param bool $bom
  4088. * @param bool $convert_encoding
  4089. * @return string
  4090. */
  4091. function filterText($text, $bom = true, $convert_encoding = true)
  4092. {
  4093. if (!$this->numFonts) {
  4094. $this->selectFont($this->defaultFont);
  4095. }
  4096. if ($convert_encoding) {
  4097. $cf = $this->currentFont;
  4098. if (isset($this->fonts[$cf]) && $this->fonts[$cf]['isUnicode']) {
  4099. $text = $this->utf8toUtf16BE($text, $bom);
  4100. } else {
  4101. //$text = html_entity_decode($text, ENT_QUOTES);
  4102. $text = mb_convert_encoding($text, self::$targetEncoding, 'UTF-8');
  4103. }
  4104. } else if ($bom) {
  4105. $text = $this->utf8toUtf16BE($text, $bom);
  4106. }
  4107. // the chr(13) substitution fixes a bug seen in TCPDF (bug #1421290)
  4108. return strtr($text, [')' => '\\)', '(' => '\\(', '\\' => '\\\\', chr(13) => '\r']);
  4109. }
  4110. /**
  4111. * return array containing codepoints (UTF-8 character values) for the
  4112. * string passed in.
  4113. *
  4114. * based on the excellent TCPDF code by Nicola Asuni and the
  4115. * RFC for UTF-8 at http://www.faqs.org/rfcs/rfc3629.html
  4116. *
  4117. * @access private
  4118. * @author Orion Richardson
  4119. * @since January 5, 2008
  4120. *
  4121. * @param string $text UTF-8 string to process
  4122. *
  4123. * @return array UTF-8 codepoints array for the string
  4124. */
  4125. function utf8toCodePointsArray(&$text)
  4126. {
  4127. $length = mb_strlen($text, '8bit'); // http://www.php.net/manual/en/function.mb-strlen.php#77040
  4128. $unicode = []; // array containing unicode values
  4129. $bytes = []; // array containing single character byte sequences
  4130. $numbytes = 1; // number of octets needed to represent the UTF-8 character
  4131. for ($i = 0; $i < $length; $i++) {
  4132. $c = ord($text[$i]); // get one string character at time
  4133. if (count($bytes) === 0) { // get starting octect
  4134. if ($c <= 0x7F) {
  4135. $unicode[] = $c; // use the character "as is" because is ASCII
  4136. $numbytes = 1;
  4137. } elseif (($c >> 0x05) === 0x06) { // 2 bytes character (0x06 = 110 BIN)
  4138. $bytes[] = ($c - 0xC0) << 0x06;
  4139. $numbytes = 2;
  4140. } elseif (($c >> 0x04) === 0x0E) { // 3 bytes character (0x0E = 1110 BIN)
  4141. $bytes[] = ($c - 0xE0) << 0x0C;
  4142. $numbytes = 3;
  4143. } elseif (($c >> 0x03) === 0x1E) { // 4 bytes character (0x1E = 11110 BIN)
  4144. $bytes[] = ($c - 0xF0) << 0x12;
  4145. $numbytes = 4;
  4146. } else {
  4147. // use replacement character for other invalid sequences
  4148. $unicode[] = 0xFFFD;
  4149. $bytes = [];
  4150. $numbytes = 1;
  4151. }
  4152. } elseif (($c >> 0x06) === 0x02) { // bytes 2, 3 and 4 must start with 0x02 = 10 BIN
  4153. $bytes[] = $c - 0x80;
  4154. if (count($bytes) === $numbytes) {
  4155. // compose UTF-8 bytes to a single unicode value
  4156. $c = $bytes[0];
  4157. for ($j = 1; $j < $numbytes; $j++) {
  4158. $c += ($bytes[$j] << (($numbytes - $j - 1) * 0x06));
  4159. }
  4160. if ((($c >= 0xD800) and ($c <= 0xDFFF)) or ($c >= 0x10FFFF)) {
  4161. // The definition of UTF-8 prohibits encoding character numbers between
  4162. // U+D800 and U+DFFF, which are reserved for use with the UTF-16
  4163. // encoding form (as surrogate pairs) and do not directly represent
  4164. // characters.
  4165. $unicode[] = 0xFFFD; // use replacement character
  4166. } else {
  4167. $unicode[] = $c; // add char to array
  4168. }
  4169. // reset data for next char
  4170. $bytes = [];
  4171. $numbytes = 1;
  4172. }
  4173. } else {
  4174. // use replacement character for other invalid sequences
  4175. $unicode[] = 0xFFFD;
  4176. $bytes = [];
  4177. $numbytes = 1;
  4178. }
  4179. }
  4180. return $unicode;
  4181. }
  4182. /**
  4183. * convert UTF-8 to UTF-16 with an additional byte order marker
  4184. * at the front if required.
  4185. *
  4186. * based on the excellent TCPDF code by Nicola Asuni and the
  4187. * RFC for UTF-8 at http://www.faqs.org/rfcs/rfc3629.html
  4188. *
  4189. * @access private
  4190. * @author Orion Richardson
  4191. * @since January 5, 2008
  4192. *
  4193. * @param string $text UTF-8 string to process
  4194. * @param boolean $bom whether to add the byte order marker
  4195. *
  4196. * @return string UTF-16 result string
  4197. */
  4198. function utf8toUtf16BE(&$text, $bom = true)
  4199. {
  4200. $out = $bom ? "\xFE\xFF" : '';
  4201. $unicode = $this->utf8toCodePointsArray($text);
  4202. foreach ($unicode as $c) {
  4203. if ($c === 0xFFFD) {
  4204. $out .= "\xFF\xFD"; // replacement character
  4205. } elseif ($c < 0x10000) {
  4206. $out .= chr($c >> 0x08) . chr($c & 0xFF);
  4207. } else {
  4208. $c -= 0x10000;
  4209. $w1 = 0xD800 | ($c >> 0x10);
  4210. $w2 = 0xDC00 | ($c & 0x3FF);
  4211. $out .= chr($w1 >> 0x08) . chr($w1 & 0xFF) . chr($w2 >> 0x08) . chr($w2 & 0xFF);
  4212. }
  4213. }
  4214. return $out;
  4215. }
  4216. /**
  4217. * given a start position and information about how text is to be laid out, calculate where
  4218. * on the page the text will end
  4219. *
  4220. * @param $x
  4221. * @param $y
  4222. * @param $angle
  4223. * @param $size
  4224. * @param $wa
  4225. * @param $text
  4226. * @return array
  4227. */
  4228. private function getTextPosition($x, $y, $angle, $size, $wa, $text)
  4229. {
  4230. // given this information return an array containing x and y for the end position as elements 0 and 1
  4231. $w = $this->getTextWidth($size, $text);
  4232. // need to adjust for the number of spaces in this text
  4233. $words = explode(' ', $text);
  4234. $nspaces = count($words) - 1;
  4235. $w += $wa * $nspaces;
  4236. $a = deg2rad((float)$angle);
  4237. return [cos($a) * $w + $x, -sin($a) * $w + $y];
  4238. }
  4239. /**
  4240. * Callback method used by smallCaps
  4241. *
  4242. * @param array $matches
  4243. *
  4244. * @return string
  4245. */
  4246. function toUpper($matches)
  4247. {
  4248. return mb_strtoupper($matches[0]);
  4249. }
  4250. function concatMatches($matches)
  4251. {
  4252. $str = "";
  4253. foreach ($matches as $match) {
  4254. $str .= $match[0];
  4255. }
  4256. return $str;
  4257. }
  4258. /**
  4259. * register text for font subsetting
  4260. *
  4261. * @param $font
  4262. * @param $text
  4263. */
  4264. function registerText($font, $text)
  4265. {
  4266. if (!$this->isUnicode || in_array(mb_strtolower(basename($font)), self::$coreFonts)) {
  4267. return;
  4268. }
  4269. if (!isset($this->stringSubsets[$font])) {
  4270. $this->stringSubsets[$font] = [];
  4271. }
  4272. $this->stringSubsets[$font] = array_unique(
  4273. array_merge($this->stringSubsets[$font], $this->utf8toCodePointsArray($text))
  4274. );
  4275. }
  4276. /**
  4277. * add text to the document, at a specified location, size and angle on the page
  4278. *
  4279. * @param $x
  4280. * @param $y
  4281. * @param $size
  4282. * @param $text
  4283. * @param int $angle
  4284. * @param int $wordSpaceAdjust
  4285. * @param int $charSpaceAdjust
  4286. * @param bool $smallCaps
  4287. */
  4288. function addText($x, $y, $size, $text, $angle = 0, $wordSpaceAdjust = 0, $charSpaceAdjust = 0, $smallCaps = false)
  4289. {
  4290. if (!$this->numFonts) {
  4291. $this->selectFont($this->defaultFont);
  4292. }
  4293. $text = str_replace(["\r", "\n"], "", $text);
  4294. if ($smallCaps) {
  4295. preg_match_all("/(\P{Ll}+)/u", $text, $matches, PREG_SET_ORDER);
  4296. $lower = $this->concatMatches($matches);
  4297. d($lower);
  4298. preg_match_all("/(\p{Ll}+)/u", $text, $matches, PREG_SET_ORDER);
  4299. $other = $this->concatMatches($matches);
  4300. d($other);
  4301. //$text = preg_replace_callback("/\p{Ll}/u", array($this, "toUpper"), $text);
  4302. }
  4303. // if there are any open callbacks, then they should be called, to show the start of the line
  4304. if ($this->nCallback > 0) {
  4305. for ($i = $this->nCallback; $i > 0; $i--) {
  4306. // call each function
  4307. $info = [
  4308. 'x' => $x,
  4309. 'y' => $y,
  4310. 'angle' => $angle,
  4311. 'status' => 'sol',
  4312. 'p' => $this->callback[$i]['p'],
  4313. 'nCallback' => $this->callback[$i]['nCallback'],
  4314. 'height' => $this->callback[$i]['height'],
  4315. 'descender' => $this->callback[$i]['descender']
  4316. ];
  4317. $func = $this->callback[$i]['f'];
  4318. $this->$func($info);
  4319. }
  4320. }
  4321. if ($angle == 0) {
  4322. $this->addContent(sprintf("\nBT %.3F %.3F Td", $x, $y));
  4323. } else {
  4324. $a = deg2rad((float)$angle);
  4325. $this->addContent(
  4326. sprintf("\nBT %.3F %.3F %.3F %.3F %.3F %.3F Tm", cos($a), -sin($a), sin($a), cos($a), $x, $y)
  4327. );
  4328. }
  4329. if ($wordSpaceAdjust != 0) {
  4330. $this->addContent(sprintf(" %.3F Tw", $wordSpaceAdjust));
  4331. }
  4332. if ($charSpaceAdjust != 0) {
  4333. $this->addContent(sprintf(" %.3F Tc", $charSpaceAdjust));
  4334. }
  4335. $len = mb_strlen($text);
  4336. $start = 0;
  4337. if ($start < $len) {
  4338. $part = $text; // OAR - Don't need this anymore, given that $start always equals zero. substr($text, $start);
  4339. $place_text = $this->filterText($part, false);
  4340. // modify unicode text so that extra word spacing is manually implemented (bug #)
  4341. if ($this->fonts[$this->currentFont]['isUnicode'] && $wordSpaceAdjust != 0) {
  4342. $space_scale = 1000 / $size;
  4343. $place_text = str_replace("\x00\x20", "\x00\x20)\x00\x20" . (-round($space_scale * $wordSpaceAdjust)) . "\x00\x20(", $place_text);
  4344. }
  4345. $this->addContent(" /F$this->currentFontNum " . sprintf('%.1F Tf ', $size));
  4346. $this->addContent(" [($place_text)] TJ");
  4347. }
  4348. if ($wordSpaceAdjust != 0) {
  4349. $this->addContent(sprintf(" %.3F Tw", 0));
  4350. }
  4351. if ($charSpaceAdjust != 0) {
  4352. $this->addContent(sprintf(" %.3F Tc", 0));
  4353. }
  4354. $this->addContent(' ET');
  4355. // if there are any open callbacks, then they should be called, to show the end of the line
  4356. if ($this->nCallback > 0) {
  4357. for ($i = $this->nCallback; $i > 0; $i--) {
  4358. // call each function
  4359. $tmp = $this->getTextPosition($x, $y, $angle, $size, $wordSpaceAdjust, $text);
  4360. $info = [
  4361. 'x' => $tmp[0],
  4362. 'y' => $tmp[1],
  4363. 'angle' => $angle,
  4364. 'status' => 'eol',
  4365. 'p' => $this->callback[$i]['p'],
  4366. 'nCallback' => $this->callback[$i]['nCallback'],
  4367. 'height' => $this->callback[$i]['height'],
  4368. 'descender' => $this->callback[$i]['descender']
  4369. ];
  4370. $func = $this->callback[$i]['f'];
  4371. $this->$func($info);
  4372. }
  4373. }
  4374. if ($this->fonts[$this->currentFont]['isSubsetting']) {
  4375. $this->registerText($this->currentFont, $text);
  4376. }
  4377. }
  4378. /**
  4379. * calculate how wide a given text string will be on a page, at a given size.
  4380. * this can be called externally, but is also used by the other class functions
  4381. *
  4382. * @param $size
  4383. * @param $text
  4384. * @param int $word_spacing
  4385. * @param int $char_spacing
  4386. * @return float|int
  4387. */
  4388. function getTextWidth($size, $text, $word_spacing = 0, $char_spacing = 0)
  4389. {
  4390. static $ord_cache = [];
  4391. // this function should not change any of the settings, though it will need to
  4392. // track any directives which change during calculation, so copy them at the start
  4393. // and put them back at the end.
  4394. $store_currentTextState = $this->currentTextState;
  4395. if (!$this->numFonts) {
  4396. $this->selectFont($this->defaultFont);
  4397. }
  4398. $text = str_replace(["\r", "\n"], "", $text);
  4399. // converts a number or a float to a string so it can get the width
  4400. $text = "$text";
  4401. // hmm, this is where it all starts to get tricky - use the font information to
  4402. // calculate the width of each character, add them up and convert to user units
  4403. $w = 0;
  4404. $cf = $this->currentFont;
  4405. $current_font = $this->fonts[$cf];
  4406. $space_scale = 1000 / ($size > 0 ? $size : 1);
  4407. $n_spaces = 0;
  4408. if ($current_font['isUnicode']) {
  4409. // for Unicode, use the code points array to calculate width rather
  4410. // than just the string itself
  4411. $unicode = $this->utf8toCodePointsArray($text);
  4412. foreach ($unicode as $char) {
  4413. // check if we have to replace character
  4414. if (isset($current_font['differences'][$char])) {
  4415. $char = $current_font['differences'][$char];
  4416. }
  4417. if (isset($current_font['C'][$char])) {
  4418. $char_width = $current_font['C'][$char];
  4419. // add the character width
  4420. $w += $char_width;
  4421. // add additional padding for space
  4422. if (isset($current_font['codeToName'][$char]) && $current_font['codeToName'][$char] === 'space') { // Space
  4423. $w += $word_spacing * $space_scale;
  4424. $n_spaces++;
  4425. }
  4426. }
  4427. }
  4428. // add additional char spacing
  4429. if ($char_spacing != 0) {
  4430. $w += $char_spacing * $space_scale * (count($unicode) + $n_spaces);
  4431. }
  4432. } else {
  4433. // If CPDF is in Unicode mode but the current font does not support Unicode we need to convert the character set to Windows-1252
  4434. if ($this->isUnicode) {
  4435. $text = mb_convert_encoding($text, 'Windows-1252', 'UTF-8');
  4436. }
  4437. $len = mb_strlen($text, 'Windows-1252');
  4438. for ($i = 0; $i < $len; $i++) {
  4439. $c = $text[$i];
  4440. $char = isset($ord_cache[$c]) ? $ord_cache[$c] : ($ord_cache[$c] = ord($c));
  4441. // check if we have to replace character
  4442. if (isset($current_font['differences'][$char])) {
  4443. $char = $current_font['differences'][$char];
  4444. }
  4445. if (isset($current_font['C'][$char])) {
  4446. $char_width = $current_font['C'][$char];
  4447. // add the character width
  4448. $w += $char_width;
  4449. // add additional padding for space
  4450. if (isset($current_font['codeToName'][$char]) && $current_font['codeToName'][$char] === 'space') { // Space
  4451. $w += $word_spacing * $space_scale;
  4452. $n_spaces++;
  4453. }
  4454. }
  4455. }
  4456. // add additional char spacing
  4457. if ($char_spacing != 0) {
  4458. $w += $char_spacing * $space_scale * ($len + $n_spaces);
  4459. }
  4460. }
  4461. $this->currentTextState = $store_currentTextState;
  4462. $this->setCurrentFont();
  4463. return $w * $size / 1000;
  4464. }
  4465. /**
  4466. * this will be called at a new page to return the state to what it was on the
  4467. * end of the previous page, before the stack was closed down
  4468. * This is to get around not being able to have open 'q' across pages
  4469. *
  4470. * @param int $pageEnd
  4471. */
  4472. function saveState($pageEnd = 0)
  4473. {
  4474. if ($pageEnd) {
  4475. // this will be called at a new page to return the state to what it was on the
  4476. // end of the previous page, before the stack was closed down
  4477. // This is to get around not being able to have open 'q' across pages
  4478. $opt = $this->stateStack[$pageEnd];
  4479. // ok to use this as stack starts numbering at 1
  4480. $this->setColor($opt['col'], true);
  4481. $this->setStrokeColor($opt['str'], true);
  4482. $this->addContent("\n" . $opt['lin']);
  4483. // $this->currentLineStyle = $opt['lin'];
  4484. } else {
  4485. $this->nStateStack++;
  4486. $this->stateStack[$this->nStateStack] = [
  4487. 'col' => $this->currentColor,
  4488. 'str' => $this->currentStrokeColor,
  4489. 'lin' => $this->currentLineStyle
  4490. ];
  4491. }
  4492. $this->save();
  4493. }
  4494. /**
  4495. * restore a previously saved state
  4496. *
  4497. * @param int $pageEnd
  4498. */
  4499. function restoreState($pageEnd = 0)
  4500. {
  4501. if (!$pageEnd) {
  4502. $n = $this->nStateStack;
  4503. $this->currentColor = $this->stateStack[$n]['col'];
  4504. $this->currentStrokeColor = $this->stateStack[$n]['str'];
  4505. $this->addContent("\n" . $this->stateStack[$n]['lin']);
  4506. $this->currentLineStyle = $this->stateStack[$n]['lin'];
  4507. $this->stateStack[$n] = null;
  4508. unset($this->stateStack[$n]);
  4509. $this->nStateStack--;
  4510. }
  4511. $this->restore();
  4512. }
  4513. /**
  4514. * make a loose object, the output will go into this object, until it is closed, then will revert to
  4515. * the current one.
  4516. * this object will not appear until it is included within a page.
  4517. * the function will return the object number
  4518. *
  4519. * @return int
  4520. */
  4521. function openObject()
  4522. {
  4523. $this->nStack++;
  4524. $this->stack[$this->nStack] = ['c' => $this->currentContents, 'p' => $this->currentPage];
  4525. // add a new object of the content type, to hold the data flow
  4526. $this->numObj++;
  4527. $this->o_contents($this->numObj, 'new');
  4528. $this->currentContents = $this->numObj;
  4529. $this->looseObjects[$this->numObj] = 1;
  4530. return $this->numObj;
  4531. }
  4532. /**
  4533. * open an existing object for editing
  4534. *
  4535. * @param $id
  4536. */
  4537. function reopenObject($id)
  4538. {
  4539. $this->nStack++;
  4540. $this->stack[$this->nStack] = ['c' => $this->currentContents, 'p' => $this->currentPage];
  4541. $this->currentContents = $id;
  4542. // also if this object is the primary contents for a page, then set the current page to its parent
  4543. if (isset($this->objects[$id]['onPage'])) {
  4544. $this->currentPage = $this->objects[$id]['onPage'];
  4545. }
  4546. }
  4547. /**
  4548. * close an object
  4549. */
  4550. function closeObject()
  4551. {
  4552. // close the object, as long as there was one open in the first place, which will be indicated by
  4553. // an objectId on the stack.
  4554. if ($this->nStack > 0) {
  4555. $this->currentContents = $this->stack[$this->nStack]['c'];
  4556. $this->currentPage = $this->stack[$this->nStack]['p'];
  4557. $this->nStack--;
  4558. // easier to probably not worry about removing the old entries, they will be overwritten
  4559. // if there are new ones.
  4560. }
  4561. }
  4562. /**
  4563. * stop an object from appearing on pages from this point on
  4564. *
  4565. * @param $id
  4566. */
  4567. function stopObject($id)
  4568. {
  4569. // if an object has been appearing on pages up to now, then stop it, this page will
  4570. // be the last one that could contain it.
  4571. if (isset($this->addLooseObjects[$id])) {
  4572. $this->addLooseObjects[$id] = '';
  4573. }
  4574. }
  4575. /**
  4576. * after an object has been created, it wil only show if it has been added, using this function.
  4577. *
  4578. * @param $id
  4579. * @param string $options
  4580. */
  4581. function addObject($id, $options = 'add')
  4582. {
  4583. // add the specified object to the page
  4584. if (isset($this->looseObjects[$id]) && $this->currentContents != $id) {
  4585. // then it is a valid object, and it is not being added to itself
  4586. switch ($options) {
  4587. case 'all':
  4588. // then this object is to be added to this page (done in the next block) and
  4589. // all future new pages.
  4590. $this->addLooseObjects[$id] = 'all';
  4591. case 'add':
  4592. if (isset($this->objects[$this->currentContents]['onPage'])) {
  4593. // then the destination contents is the primary for the page
  4594. // (though this object is actually added to that page)
  4595. $this->o_page($this->objects[$this->currentContents]['onPage'], 'content', $id);
  4596. }
  4597. break;
  4598. case 'even':
  4599. $this->addLooseObjects[$id] = 'even';
  4600. $pageObjectId = $this->objects[$this->currentContents]['onPage'];
  4601. if ($this->objects[$pageObjectId]['info']['pageNum'] % 2 == 0) {
  4602. $this->addObject($id);
  4603. // hacky huh :)
  4604. }
  4605. break;
  4606. case 'odd':
  4607. $this->addLooseObjects[$id] = 'odd';
  4608. $pageObjectId = $this->objects[$this->currentContents]['onPage'];
  4609. if ($this->objects[$pageObjectId]['info']['pageNum'] % 2 == 1) {
  4610. $this->addObject($id);
  4611. // hacky huh :)
  4612. }
  4613. break;
  4614. case 'next':
  4615. $this->addLooseObjects[$id] = 'all';
  4616. break;
  4617. case 'nexteven':
  4618. $this->addLooseObjects[$id] = 'even';
  4619. break;
  4620. case 'nextodd':
  4621. $this->addLooseObjects[$id] = 'odd';
  4622. break;
  4623. }
  4624. }
  4625. }
  4626. /**
  4627. * return a storable representation of a specific object
  4628. *
  4629. * @param $id
  4630. * @return string|null
  4631. */
  4632. function serializeObject($id)
  4633. {
  4634. if (array_key_exists($id, $this->objects)) {
  4635. return serialize($this->objects[$id]);
  4636. }
  4637. return null;
  4638. }
  4639. /**
  4640. * restore an object from its stored representation. Returns its new object id.
  4641. *
  4642. * @param $obj
  4643. * @return int
  4644. */
  4645. function restoreSerializedObject($obj)
  4646. {
  4647. $obj_id = $this->openObject();
  4648. $this->objects[$obj_id] = unserialize($obj);
  4649. $this->closeObject();
  4650. return $obj_id;
  4651. }
  4652. /**
  4653. * Embeds a file inside the PDF
  4654. *
  4655. * @param string $filepath path to the file to store inside the PDF
  4656. * @param string $embeddedFilename the filename displayed in the list of embedded files
  4657. * @param string $description a description in the list of embedded files
  4658. */
  4659. public function addEmbeddedFile(string $filepath, string $embeddedFilename, string $description): void
  4660. {
  4661. $this->numObj++;
  4662. $this->o_embedded_file_dictionary(
  4663. $this->numObj,
  4664. 'new',
  4665. [
  4666. 'filepath' => $filepath,
  4667. 'filename' => $embeddedFilename,
  4668. 'description' => $description
  4669. ]
  4670. );
  4671. }
  4672. /**
  4673. * add content to the documents info object
  4674. *
  4675. * @param $label
  4676. * @param int $value
  4677. */
  4678. function addInfo($label, $value = 0)
  4679. {
  4680. // this will only work if the label is one of the valid ones.
  4681. // modify this so that arrays can be passed as well.
  4682. // if $label is an array then assume that it is key => value pairs
  4683. // else assume that they are both scalar, anything else will probably error
  4684. if (is_array($label)) {
  4685. foreach ($label as $l => $v) {
  4686. $this->o_info($this->infoObject, $l, $v);
  4687. }
  4688. } else {
  4689. $this->o_info($this->infoObject, $label, $value);
  4690. }
  4691. }
  4692. /**
  4693. * set the viewer preferences of the document, it is up to the browser to obey these.
  4694. *
  4695. * @param $label
  4696. * @param int $value
  4697. */
  4698. function setPreferences($label, $value = 0)
  4699. {
  4700. // this will only work if the label is one of the valid ones.
  4701. if (is_array($label)) {
  4702. foreach ($label as $l => $v) {
  4703. $this->o_catalog($this->catalogId, 'viewerPreferences', [$l => $v]);
  4704. }
  4705. } else {
  4706. $this->o_catalog($this->catalogId, 'viewerPreferences', [$label => $value]);
  4707. }
  4708. }
  4709. /**
  4710. * extract an integer from a position in a byte stream
  4711. *
  4712. * @param $data
  4713. * @param $pos
  4714. * @param $num
  4715. * @return int
  4716. */
  4717. private function getBytes(&$data, $pos, $num)
  4718. {
  4719. // return the integer represented by $num bytes from $pos within $data
  4720. $ret = 0;
  4721. for ($i = 0; $i < $num; $i++) {
  4722. $ret *= 256;
  4723. $ret += ord($data[$pos + $i]);
  4724. }
  4725. return $ret;
  4726. }
  4727. /**
  4728. * Check if image already added to pdf image directory.
  4729. * If yes, need not to create again (pass empty data)
  4730. *
  4731. * @param $imgname
  4732. * @return bool
  4733. */
  4734. function image_iscached($imgname)
  4735. {
  4736. return isset($this->imagelist[$imgname]);
  4737. }
  4738. /**
  4739. * add a PNG image into the document, from a GD object
  4740. * this should work with remote files
  4741. *
  4742. * @param string $file The PNG file
  4743. * @param float $x X position
  4744. * @param float $y Y position
  4745. * @param float $w Width
  4746. * @param float $h Height
  4747. * @param resource $img A GD resource
  4748. * @param bool $is_mask true if the image is a mask
  4749. * @param bool $mask true if the image is masked
  4750. * @throws Exception
  4751. */
  4752. function addImagePng($file, $x, $y, $w = 0.0, $h = 0.0, &$img, $is_mask = false, $mask = null)
  4753. {
  4754. if (!function_exists("imagepng")) {
  4755. throw new \Exception("The PHP GD extension is required, but is not installed.");
  4756. }
  4757. //if already cached, need not to read again
  4758. if (isset($this->imagelist[$file])) {
  4759. $data = null;
  4760. } else {
  4761. // Example for transparency handling on new image. Retain for current image
  4762. // $tIndex = imagecolortransparent($img);
  4763. // if ($tIndex > 0) {
  4764. // $tColor = imagecolorsforindex($img, $tIndex);
  4765. // $new_tIndex = imagecolorallocate($new_img, $tColor['red'], $tColor['green'], $tColor['blue']);
  4766. // imagefill($new_img, 0, 0, $new_tIndex);
  4767. // imagecolortransparent($new_img, $new_tIndex);
  4768. // }
  4769. // blending mode (literal/blending) on drawing into current image. not relevant when not saved or not drawn
  4770. //imagealphablending($img, true);
  4771. //default, but explicitely set to ensure pdf compatibility
  4772. imagesavealpha($img, false/*!$is_mask && !$mask*/);
  4773. $error = 0;
  4774. //DEBUG_IMG_TEMP
  4775. //debugpng
  4776. if (defined("DEBUGPNG") && DEBUGPNG) {
  4777. print '[addImagePng ' . $file . ']';
  4778. }
  4779. ob_start();
  4780. @imagepng($img);
  4781. $data = ob_get_clean();
  4782. if ($data == '') {
  4783. $error = 1;
  4784. $errormsg = 'trouble writing file from GD';
  4785. //DEBUG_IMG_TEMP
  4786. //debugpng
  4787. if (defined("DEBUGPNG") && DEBUGPNG) {
  4788. print 'trouble writing file from GD';
  4789. }
  4790. }
  4791. if ($error) {
  4792. $this->addMessage('PNG error - (' . $file . ') ' . $errormsg);
  4793. return;
  4794. }
  4795. } //End isset($this->imagelist[$file]) (png Duplicate removal)
  4796. $this->addPngFromBuf($file, $x, $y, $w, $h, $data, $is_mask, $mask);
  4797. }
  4798. /**
  4799. * @param $file
  4800. * @param $x
  4801. * @param $y
  4802. * @param $w
  4803. * @param $h
  4804. * @param $byte
  4805. */
  4806. protected function addImagePngAlpha($file, $x, $y, $w, $h, $byte)
  4807. {
  4808. // generate images
  4809. $img = imagecreatefrompng($file);
  4810. if ($img === false) {
  4811. return;
  4812. }
  4813. // FIXME The pixel transformation doesn't work well with 8bit PNGs
  4814. $eight_bit = ($byte & 4) !== 4;
  4815. $wpx = imagesx($img);
  4816. $hpx = imagesy($img);
  4817. imagesavealpha($img, false);
  4818. // create temp alpha file
  4819. $tempfile_alpha = @tempnam($this->tmp, "cpdf_img_");
  4820. @unlink($tempfile_alpha);
  4821. $tempfile_alpha = "$tempfile_alpha.png";
  4822. // create temp plain file
  4823. $tempfile_plain = @tempnam($this->tmp, "cpdf_img_");
  4824. @unlink($tempfile_plain);
  4825. $tempfile_plain = "$tempfile_plain.png";
  4826. $imgalpha = imagecreate($wpx, $hpx);
  4827. imagesavealpha($imgalpha, false);
  4828. // generate gray scale palette (0 -> 255)
  4829. for ($c = 0; $c < 256; ++$c) {
  4830. imagecolorallocate($imgalpha, $c, $c, $c);
  4831. }
  4832. // Use PECL gmagick + Graphics Magic to process transparent PNG images
  4833. if (extension_loaded("gmagick")) {
  4834. $gmagick = new \Gmagick($file);
  4835. $gmagick->setimageformat('png');
  4836. // Get opacity channel (negative of alpha channel)
  4837. $alpha_channel_neg = clone $gmagick;
  4838. $alpha_channel_neg->separateimagechannel(\Gmagick::CHANNEL_OPACITY);
  4839. // Negate opacity channel
  4840. $alpha_channel = new \Gmagick();
  4841. $alpha_channel->newimage($wpx, $hpx, "#FFFFFF", "png");
  4842. $alpha_channel->compositeimage($alpha_channel_neg, \Gmagick::COMPOSITE_DIFFERENCE, 0, 0);
  4843. $alpha_channel->separateimagechannel(\Gmagick::CHANNEL_RED);
  4844. $alpha_channel->writeimage($tempfile_alpha);
  4845. // Cast to 8bit+palette
  4846. $imgalpha_ = imagecreatefrompng($tempfile_alpha);
  4847. imagecopy($imgalpha, $imgalpha_, 0, 0, 0, 0, $wpx, $hpx);
  4848. imagedestroy($imgalpha_);
  4849. imagepng($imgalpha, $tempfile_alpha);
  4850. // Make opaque image
  4851. $color_channels = new \Gmagick();
  4852. $color_channels->newimage($wpx, $hpx, "#FFFFFF", "png");
  4853. $color_channels->compositeimage($gmagick, \Gmagick::COMPOSITE_COPYRED, 0, 0);
  4854. $color_channels->compositeimage($gmagick, \Gmagick::COMPOSITE_COPYGREEN, 0, 0);
  4855. $color_channels->compositeimage($gmagick, \Gmagick::COMPOSITE_COPYBLUE, 0, 0);
  4856. $color_channels->writeimage($tempfile_plain);
  4857. $imgplain = imagecreatefrompng($tempfile_plain);
  4858. }
  4859. // Use PECL imagick + ImageMagic to process transparent PNG images
  4860. elseif (extension_loaded("imagick")) {
  4861. // Native cloning was added to pecl-imagick in svn commit 263814
  4862. // the first version containing it was 3.0.1RC1
  4863. static $imagickClonable = null;
  4864. if ($imagickClonable === null) {
  4865. $imagickClonable = version_compare(\Imagick::IMAGICK_EXTVER, '3.0.1rc1') > 0;
  4866. }
  4867. $imagick = new \Imagick($file);
  4868. $imagick->setFormat('png');
  4869. // Get opacity channel (negative of alpha channel)
  4870. if ($imagick->getImageAlphaChannel() !== 0) {
  4871. $alpha_channel = $imagickClonable ? clone $imagick : $imagick->clone();
  4872. $alpha_channel->separateImageChannel(\Imagick::CHANNEL_ALPHA);
  4873. // Since ImageMagick7 negate invert transparency as default
  4874. if (\Imagick::getVersion()['versionNumber'] < 1800) {
  4875. $alpha_channel->negateImage(true);
  4876. }
  4877. $alpha_channel->writeImage($tempfile_alpha);
  4878. // Cast to 8bit+palette
  4879. $imgalpha_ = imagecreatefrompng($tempfile_alpha);
  4880. imagecopy($imgalpha, $imgalpha_, 0, 0, 0, 0, $wpx, $hpx);
  4881. imagedestroy($imgalpha_);
  4882. imagepng($imgalpha, $tempfile_alpha);
  4883. } else {
  4884. $tempfile_alpha = null;
  4885. }
  4886. // Make opaque image
  4887. $color_channels = new \Imagick();
  4888. $color_channels->newImage($wpx, $hpx, "#FFFFFF", "png");
  4889. $color_channels->compositeImage($imagick, \Imagick::COMPOSITE_COPYRED, 0, 0);
  4890. $color_channels->compositeImage($imagick, \Imagick::COMPOSITE_COPYGREEN, 0, 0);
  4891. $color_channels->compositeImage($imagick, \Imagick::COMPOSITE_COPYBLUE, 0, 0);
  4892. $color_channels->writeImage($tempfile_plain);
  4893. $imgplain = imagecreatefrompng($tempfile_plain);
  4894. } else {
  4895. // allocated colors cache
  4896. $allocated_colors = [];
  4897. // extract alpha channel
  4898. for ($xpx = 0; $xpx < $wpx; ++$xpx) {
  4899. for ($ypx = 0; $ypx < $hpx; ++$ypx) {
  4900. $color = imagecolorat($img, $xpx, $ypx);
  4901. $col = imagecolorsforindex($img, $color);
  4902. $alpha = $col['alpha'];
  4903. if ($eight_bit) {
  4904. // with gamma correction
  4905. $gammacorr = 2.2;
  4906. $pixel = pow((((127 - $alpha) * 255 / 127) / 255), $gammacorr) * 255;
  4907. } else {
  4908. // without gamma correction
  4909. $pixel = (127 - $alpha) * 2;
  4910. $key = $col['red'] . $col['green'] . $col['blue'];
  4911. if (!isset($allocated_colors[$key])) {
  4912. $pixel_img = imagecolorallocate($img, $col['red'], $col['green'], $col['blue']);
  4913. $allocated_colors[$key] = $pixel_img;
  4914. } else {
  4915. $pixel_img = $allocated_colors[$key];
  4916. }
  4917. imagesetpixel($img, $xpx, $ypx, $pixel_img);
  4918. }
  4919. imagesetpixel($imgalpha, $xpx, $ypx, $pixel);
  4920. }
  4921. }
  4922. // extract image without alpha channel
  4923. $imgplain = imagecreatetruecolor($wpx, $hpx);
  4924. imagecopy($imgplain, $img, 0, 0, 0, 0, $wpx, $hpx);
  4925. imagedestroy($img);
  4926. imagepng($imgalpha, $tempfile_alpha);
  4927. imagepng($imgplain, $tempfile_plain);
  4928. }
  4929. // embed mask image
  4930. if ($tempfile_alpha) {
  4931. $this->addImagePng($tempfile_alpha, $x, $y, $w, $h, $imgalpha, true);
  4932. imagedestroy($imgalpha);
  4933. }
  4934. // embed image, masked with previously embedded mask
  4935. $this->addImagePng($tempfile_plain, $x, $y, $w, $h, $imgplain, false, ($tempfile_alpha !== null));
  4936. imagedestroy($imgplain);
  4937. // remove temp files
  4938. if ($tempfile_alpha) {
  4939. unlink($tempfile_alpha);
  4940. }
  4941. unlink($tempfile_plain);
  4942. }
  4943. /**
  4944. * add a PNG image into the document, from a file
  4945. * this should work with remote files
  4946. *
  4947. * @param $file
  4948. * @param $x
  4949. * @param $y
  4950. * @param int $w
  4951. * @param int $h
  4952. * @throws Exception
  4953. */
  4954. function addPngFromFile($file, $x, $y, $w = 0, $h = 0)
  4955. {
  4956. if (!function_exists("imagecreatefrompng")) {
  4957. throw new \Exception("The PHP GD extension is required, but is not installed.");
  4958. }
  4959. //if already cached, need not to read again
  4960. if (isset($this->imagelist[$file])) {
  4961. $img = null;
  4962. } else {
  4963. $info = file_get_contents($file, false, null, 24, 5);
  4964. $meta = unpack("CbitDepth/CcolorType/CcompressionMethod/CfilterMethod/CinterlaceMethod", $info);
  4965. $bit_depth = $meta["bitDepth"];
  4966. $color_type = $meta["colorType"];
  4967. // http://www.w3.org/TR/PNG/#11IHDR
  4968. // 3 => indexed
  4969. // 4 => greyscale with alpha
  4970. // 6 => fullcolor with alpha
  4971. $is_alpha = in_array($color_type, [4, 6]) || ($color_type == 3 && $bit_depth != 4);
  4972. if ($is_alpha) { // exclude grayscale alpha
  4973. $this->addImagePngAlpha($file, $x, $y, $w, $h, $color_type);
  4974. return;
  4975. }
  4976. //png files typically contain an alpha channel.
  4977. //pdf file format or class.pdf does not support alpha blending.
  4978. //on alpha blended images, more transparent areas have a color near black.
  4979. //This appears in the result on not storing the alpha channel.
  4980. //Correct would be the box background image or its parent when transparent.
  4981. //But this would make the image dependent on the background.
  4982. //Therefore create an image with white background and copy in
  4983. //A more natural background than black is white.
  4984. //Therefore create an empty image with white background and merge the
  4985. //image in with alpha blending.
  4986. $imgtmp = @imagecreatefrompng($file);
  4987. if (!$imgtmp) {
  4988. return;
  4989. }
  4990. $sx = imagesx($imgtmp);
  4991. $sy = imagesy($imgtmp);
  4992. $img = imagecreatetruecolor($sx, $sy);
  4993. imagealphablending($img, true);
  4994. // @todo is it still needed ??
  4995. $ti = imagecolortransparent($imgtmp);
  4996. if ($ti >= 0) {
  4997. $tc = imagecolorsforindex($imgtmp, $ti);
  4998. $ti = imagecolorallocate($img, $tc['red'], $tc['green'], $tc['blue']);
  4999. imagefill($img, 0, 0, $ti);
  5000. imagecolortransparent($img, $ti);
  5001. } else {
  5002. imagefill($img, 1, 1, imagecolorallocate($img, 255, 255, 255));
  5003. }
  5004. imagecopy($img, $imgtmp, 0, 0, 0, 0, $sx, $sy);
  5005. imagedestroy($imgtmp);
  5006. }
  5007. $this->addImagePng($file, $x, $y, $w, $h, $img);
  5008. if ($img) {
  5009. imagedestroy($img);
  5010. }
  5011. }
  5012. /**
  5013. * add a PNG image into the document, from a file
  5014. * this should work with remote files
  5015. *
  5016. * @param $file
  5017. * @param $x
  5018. * @param $y
  5019. * @param int $w
  5020. * @param int $h
  5021. */
  5022. function addSvgFromFile($file, $x, $y, $w = 0, $h = 0)
  5023. {
  5024. $doc = new \Svg\Document();
  5025. $doc->loadFile($file);
  5026. $dimensions = $doc->getDimensions();
  5027. $this->save();
  5028. $this->transform([$w / $dimensions["width"], 0, 0, $h / $dimensions["height"], $x, $y]);
  5029. $surface = new \Svg\Surface\SurfaceCpdf($doc, $this);
  5030. $doc->render($surface);
  5031. $this->restore();
  5032. }
  5033. /**
  5034. * add a PNG image into the document, from a memory buffer of the file
  5035. *
  5036. * @param $file
  5037. * @param $x
  5038. * @param $y
  5039. * @param float $w
  5040. * @param float $h
  5041. * @param $data
  5042. * @param bool $is_mask
  5043. * @param null $mask
  5044. */
  5045. function addPngFromBuf($file, $x, $y, $w = 0.0, $h = 0.0, &$data, $is_mask = false, $mask = null)
  5046. {
  5047. if (isset($this->imagelist[$file])) {
  5048. $data = null;
  5049. $info['width'] = $this->imagelist[$file]['w'];
  5050. $info['height'] = $this->imagelist[$file]['h'];
  5051. $label = $this->imagelist[$file]['label'];
  5052. } else {
  5053. if ($data == null) {
  5054. $this->addMessage('addPngFromBuf error - data not present!');
  5055. return;
  5056. }
  5057. $error = 0;
  5058. if (!$error) {
  5059. $header = chr(137) . chr(80) . chr(78) . chr(71) . chr(13) . chr(10) . chr(26) . chr(10);
  5060. if (mb_substr($data, 0, 8, '8bit') != $header) {
  5061. $error = 1;
  5062. if (defined("DEBUGPNG") && DEBUGPNG) {
  5063. print '[addPngFromFile this file does not have a valid header ' . $file . ']';
  5064. }
  5065. $errormsg = 'this file does not have a valid header';
  5066. }
  5067. }
  5068. if (!$error) {
  5069. // set pointer
  5070. $p = 8;
  5071. $len = mb_strlen($data, '8bit');
  5072. // cycle through the file, identifying chunks
  5073. $haveHeader = 0;
  5074. $info = [];
  5075. $idata = '';
  5076. $pdata = '';
  5077. while ($p < $len) {
  5078. $chunkLen = $this->getBytes($data, $p, 4);
  5079. $chunkType = mb_substr($data, $p + 4, 4, '8bit');
  5080. switch ($chunkType) {
  5081. case 'IHDR':
  5082. // this is where all the file information comes from
  5083. $info['width'] = $this->getBytes($data, $p + 8, 4);
  5084. $info['height'] = $this->getBytes($data, $p + 12, 4);
  5085. $info['bitDepth'] = ord($data[$p + 16]);
  5086. $info['colorType'] = ord($data[$p + 17]);
  5087. $info['compressionMethod'] = ord($data[$p + 18]);
  5088. $info['filterMethod'] = ord($data[$p + 19]);
  5089. $info['interlaceMethod'] = ord($data[$p + 20]);
  5090. //print_r($info);
  5091. $haveHeader = 1;
  5092. if ($info['compressionMethod'] != 0) {
  5093. $error = 1;
  5094. //debugpng
  5095. if (defined("DEBUGPNG") && DEBUGPNG) {
  5096. print '[addPngFromFile unsupported compression method ' . $file . ']';
  5097. }
  5098. $errormsg = 'unsupported compression method';
  5099. }
  5100. if ($info['filterMethod'] != 0) {
  5101. $error = 1;
  5102. //debugpng
  5103. if (defined("DEBUGPNG") && DEBUGPNG) {
  5104. print '[addPngFromFile unsupported filter method ' . $file . ']';
  5105. }
  5106. $errormsg = 'unsupported filter method';
  5107. }
  5108. break;
  5109. case 'PLTE':
  5110. $pdata .= mb_substr($data, $p + 8, $chunkLen, '8bit');
  5111. break;
  5112. case 'IDAT':
  5113. $idata .= mb_substr($data, $p + 8, $chunkLen, '8bit');
  5114. break;
  5115. case 'tRNS':
  5116. //this chunk can only occur once and it must occur after the PLTE chunk and before IDAT chunk
  5117. //print "tRNS found, color type = ".$info['colorType']."\n";
  5118. $transparency = [];
  5119. switch ($info['colorType']) {
  5120. // indexed color, rbg
  5121. case 3:
  5122. /* corresponding to entries in the plte chunk
  5123. Alpha for palette index 0: 1 byte
  5124. Alpha for palette index 1: 1 byte
  5125. ...etc...
  5126. */
  5127. // there will be one entry for each palette entry. up until the last non-opaque entry.
  5128. // set up an array, stretching over all palette entries which will be o (opaque) or 1 (transparent)
  5129. $transparency['type'] = 'indexed';
  5130. $trans = 0;
  5131. for ($i = $chunkLen; $i >= 0; $i--) {
  5132. if (ord($data[$p + 8 + $i]) == 0) {
  5133. $trans = $i;
  5134. }
  5135. }
  5136. $transparency['data'] = $trans;
  5137. break;
  5138. // grayscale
  5139. case 0:
  5140. /* corresponding to entries in the plte chunk
  5141. Gray: 2 bytes, range 0 .. (2^bitdepth)-1
  5142. */
  5143. // $transparency['grayscale'] = $this->PRVT_getBytes($data,$p+8,2); // g = grayscale
  5144. $transparency['type'] = 'indexed';
  5145. $transparency['data'] = ord($data[$p + 8 + 1]);
  5146. break;
  5147. // truecolor
  5148. case 2:
  5149. /* corresponding to entries in the plte chunk
  5150. Red: 2 bytes, range 0 .. (2^bitdepth)-1
  5151. Green: 2 bytes, range 0 .. (2^bitdepth)-1
  5152. Blue: 2 bytes, range 0 .. (2^bitdepth)-1
  5153. */
  5154. $transparency['r'] = $this->getBytes($data, $p + 8, 2);
  5155. // r from truecolor
  5156. $transparency['g'] = $this->getBytes($data, $p + 10, 2);
  5157. // g from truecolor
  5158. $transparency['b'] = $this->getBytes($data, $p + 12, 2);
  5159. // b from truecolor
  5160. $transparency['type'] = 'color-key';
  5161. break;
  5162. //unsupported transparency type
  5163. default:
  5164. if (defined("DEBUGPNG") && DEBUGPNG) {
  5165. print '[addPngFromFile unsupported transparency type ' . $file . ']';
  5166. }
  5167. break;
  5168. }
  5169. // KS End new code
  5170. break;
  5171. default:
  5172. break;
  5173. }
  5174. $p += $chunkLen + 12;
  5175. }
  5176. if (!$haveHeader) {
  5177. $error = 1;
  5178. //debugpng
  5179. if (defined("DEBUGPNG") && DEBUGPNG) {
  5180. print '[addPngFromFile information header is missing ' . $file . ']';
  5181. }
  5182. $errormsg = 'information header is missing';
  5183. }
  5184. if (isset($info['interlaceMethod']) && $info['interlaceMethod']) {
  5185. $error = 1;
  5186. //debugpng
  5187. if (defined("DEBUGPNG") && DEBUGPNG) {
  5188. print '[addPngFromFile no support for interlaced images in pdf ' . $file . ']';
  5189. }
  5190. $errormsg = 'There appears to be no support for interlaced images in pdf.';
  5191. }
  5192. }
  5193. if (!$error && $info['bitDepth'] > 8) {
  5194. $error = 1;
  5195. //debugpng
  5196. if (defined("DEBUGPNG") && DEBUGPNG) {
  5197. print '[addPngFromFile bit depth of 8 or less is supported ' . $file . ']';
  5198. }
  5199. $errormsg = 'only bit depth of 8 or less is supported';
  5200. }
  5201. if (!$error) {
  5202. switch ($info['colorType']) {
  5203. case 3:
  5204. $color = 'DeviceRGB';
  5205. $ncolor = 1;
  5206. break;
  5207. case 2:
  5208. $color = 'DeviceRGB';
  5209. $ncolor = 3;
  5210. break;
  5211. case 0:
  5212. $color = 'DeviceGray';
  5213. $ncolor = 1;
  5214. break;
  5215. default:
  5216. $error = 1;
  5217. //debugpng
  5218. if (defined("DEBUGPNG") && DEBUGPNG) {
  5219. print '[addPngFromFile alpha channel not supported: ' . $info['colorType'] . ' ' . $file . ']';
  5220. }
  5221. $errormsg = 'transparency alpha channel not supported, transparency only supported for palette images.';
  5222. }
  5223. }
  5224. if ($error) {
  5225. $this->addMessage('PNG error - (' . $file . ') ' . $errormsg);
  5226. return;
  5227. }
  5228. //print_r($info);
  5229. // so this image is ok... add it in.
  5230. $this->numImages++;
  5231. $im = $this->numImages;
  5232. $label = "I$im";
  5233. $this->numObj++;
  5234. // $this->o_image($this->numObj,'new',array('label' => $label,'data' => $idata,'iw' => $w,'ih' => $h,'type' => 'png','ic' => $info['width']));
  5235. $options = [
  5236. 'label' => $label,
  5237. 'data' => $idata,
  5238. 'bitsPerComponent' => $info['bitDepth'],
  5239. 'pdata' => $pdata,
  5240. 'iw' => $info['width'],
  5241. 'ih' => $info['height'],
  5242. 'type' => 'png',
  5243. 'color' => $color,
  5244. 'ncolor' => $ncolor,
  5245. 'masked' => $mask,
  5246. 'isMask' => $is_mask
  5247. ];
  5248. if (isset($transparency)) {
  5249. $options['transparency'] = $transparency;
  5250. }
  5251. $this->o_image($this->numObj, 'new', $options);
  5252. $this->imagelist[$file] = ['label' => $label, 'w' => $info['width'], 'h' => $info['height']];
  5253. }
  5254. if ($is_mask) {
  5255. return;
  5256. }
  5257. if ($w <= 0 && $h <= 0) {
  5258. $w = $info['width'];
  5259. $h = $info['height'];
  5260. }
  5261. if ($w <= 0) {
  5262. $w = $h / $info['height'] * $info['width'];
  5263. }
  5264. if ($h <= 0) {
  5265. $h = $w * $info['height'] / $info['width'];
  5266. }
  5267. $this->addContent(sprintf("\nq\n%.3F 0 0 %.3F %.3F %.3F cm /%s Do\nQ", $w, $h, $x, $y, $label));
  5268. }
  5269. /**
  5270. * add a JPEG image into the document, from a file
  5271. *
  5272. * @param $img
  5273. * @param $x
  5274. * @param $y
  5275. * @param int $w
  5276. * @param int $h
  5277. */
  5278. function addJpegFromFile($img, $x, $y, $w = 0, $h = 0)
  5279. {
  5280. // attempt to add a jpeg image straight from a file, using no GD commands
  5281. // note that this function is unable to operate on a remote file.
  5282. if (!file_exists($img)) {
  5283. return;
  5284. }
  5285. if ($this->image_iscached($img)) {
  5286. $data = null;
  5287. $imageWidth = $this->imagelist[$img]['w'];
  5288. $imageHeight = $this->imagelist[$img]['h'];
  5289. $channels = $this->imagelist[$img]['c'];
  5290. } else {
  5291. $tmp = getimagesize($img);
  5292. $imageWidth = $tmp[0];
  5293. $imageHeight = $tmp[1];
  5294. if (isset($tmp['channels'])) {
  5295. $channels = $tmp['channels'];
  5296. } else {
  5297. $channels = 3;
  5298. }
  5299. $data = file_get_contents($img);
  5300. }
  5301. if ($w <= 0 && $h <= 0) {
  5302. $w = $imageWidth;
  5303. }
  5304. if ($w == 0) {
  5305. $w = $h / $imageHeight * $imageWidth;
  5306. }
  5307. if ($h == 0) {
  5308. $h = $w * $imageHeight / $imageWidth;
  5309. }
  5310. $this->addJpegImage_common($data, $x, $y, $w, $h, $imageWidth, $imageHeight, $channels, $img);
  5311. }
  5312. /**
  5313. * common code used by the two JPEG adding functions
  5314. * @param $data
  5315. * @param $x
  5316. * @param $y
  5317. * @param int $w
  5318. * @param int $h
  5319. * @param $imageWidth
  5320. * @param $imageHeight
  5321. * @param int $channels
  5322. * @param $imgname
  5323. */
  5324. private function addJpegImage_common(
  5325. &$data,
  5326. $x,
  5327. $y,
  5328. $w = 0,
  5329. $h = 0,
  5330. $imageWidth,
  5331. $imageHeight,
  5332. $channels = 3,
  5333. $imgname
  5334. ) {
  5335. if ($this->image_iscached($imgname)) {
  5336. $label = $this->imagelist[$imgname]['label'];
  5337. //debugpng
  5338. //if (DEBUGPNG) print '[addJpegImage_common Duplicate '.$imgname.']';
  5339. } else {
  5340. if ($data == null) {
  5341. $this->addMessage('addJpegImage_common error - (' . $imgname . ') data not present!');
  5342. return;
  5343. }
  5344. // note that this function is not to be called externally
  5345. // it is just the common code between the GD and the file options
  5346. $this->numImages++;
  5347. $im = $this->numImages;
  5348. $label = "I$im";
  5349. $this->numObj++;
  5350. $this->o_image(
  5351. $this->numObj,
  5352. 'new',
  5353. [
  5354. 'label' => $label,
  5355. 'data' => &$data,
  5356. 'iw' => $imageWidth,
  5357. 'ih' => $imageHeight,
  5358. 'channels' => $channels
  5359. ]
  5360. );
  5361. $this->imagelist[$imgname] = [
  5362. 'label' => $label,
  5363. 'w' => $imageWidth,
  5364. 'h' => $imageHeight,
  5365. 'c' => $channels
  5366. ];
  5367. }
  5368. $this->addContent(sprintf("\nq\n%.3F 0 0 %.3F %.3F %.3F cm /%s Do\nQ ", $w, $h, $x, $y, $label));
  5369. }
  5370. /**
  5371. * specify where the document should open when it first starts
  5372. *
  5373. * @param $style
  5374. * @param int $a
  5375. * @param int $b
  5376. * @param int $c
  5377. */
  5378. function openHere($style, $a = 0, $b = 0, $c = 0)
  5379. {
  5380. // this function will open the document at a specified page, in a specified style
  5381. // the values for style, and the required parameters are:
  5382. // 'XYZ' left, top, zoom
  5383. // 'Fit'
  5384. // 'FitH' top
  5385. // 'FitV' left
  5386. // 'FitR' left,bottom,right
  5387. // 'FitB'
  5388. // 'FitBH' top
  5389. // 'FitBV' left
  5390. $this->numObj++;
  5391. $this->o_destination(
  5392. $this->numObj,
  5393. 'new',
  5394. ['page' => $this->currentPage, 'type' => $style, 'p1' => $a, 'p2' => $b, 'p3' => $c]
  5395. );
  5396. $id = $this->catalogId;
  5397. $this->o_catalog($id, 'openHere', $this->numObj);
  5398. }
  5399. /**
  5400. * Add JavaScript code to the PDF document
  5401. *
  5402. * @param string $code
  5403. */
  5404. function addJavascript($code)
  5405. {
  5406. $this->javascript .= $code;
  5407. }
  5408. /**
  5409. * create a labelled destination within the document
  5410. *
  5411. * @param $label
  5412. * @param $style
  5413. * @param int $a
  5414. * @param int $b
  5415. * @param int $c
  5416. */
  5417. function addDestination($label, $style, $a = 0, $b = 0, $c = 0)
  5418. {
  5419. // associates the given label with the destination, it is done this way so that a destination can be specified after
  5420. // it has been linked to
  5421. // styles are the same as the 'openHere' function
  5422. $this->numObj++;
  5423. $this->o_destination(
  5424. $this->numObj,
  5425. 'new',
  5426. ['page' => $this->currentPage, 'type' => $style, 'p1' => $a, 'p2' => $b, 'p3' => $c]
  5427. );
  5428. $id = $this->numObj;
  5429. // store the label->idf relationship, note that this means that labels can be used only once
  5430. $this->destinations["$label"] = $id;
  5431. }
  5432. /**
  5433. * define font families, this is used to initialize the font families for the default fonts
  5434. * and for the user to add new ones for their fonts. The default bahavious can be overridden should
  5435. * that be desired.
  5436. *
  5437. * @param $family
  5438. * @param string $options
  5439. */
  5440. function setFontFamily($family, $options = '')
  5441. {
  5442. if (!is_array($options)) {
  5443. if ($family === 'init') {
  5444. // set the known family groups
  5445. // these font families will be used to enable bold and italic markers to be included
  5446. // within text streams. html forms will be used... <b></b> <i></i>
  5447. $this->fontFamilies['Helvetica.afm'] =
  5448. [
  5449. 'b' => 'Helvetica-Bold.afm',
  5450. 'i' => 'Helvetica-Oblique.afm',
  5451. 'bi' => 'Helvetica-BoldOblique.afm',
  5452. 'ib' => 'Helvetica-BoldOblique.afm'
  5453. ];
  5454. $this->fontFamilies['Courier.afm'] =
  5455. [
  5456. 'b' => 'Courier-Bold.afm',
  5457. 'i' => 'Courier-Oblique.afm',
  5458. 'bi' => 'Courier-BoldOblique.afm',
  5459. 'ib' => 'Courier-BoldOblique.afm'
  5460. ];
  5461. $this->fontFamilies['Times-Roman.afm'] =
  5462. [
  5463. 'b' => 'Times-Bold.afm',
  5464. 'i' => 'Times-Italic.afm',
  5465. 'bi' => 'Times-BoldItalic.afm',
  5466. 'ib' => 'Times-BoldItalic.afm'
  5467. ];
  5468. }
  5469. } else {
  5470. // the user is trying to set a font family
  5471. // note that this can also be used to set the base ones to something else
  5472. if (mb_strlen($family)) {
  5473. $this->fontFamilies[$family] = $options;
  5474. }
  5475. }
  5476. }
  5477. /**
  5478. * used to add messages for use in debugging
  5479. *
  5480. * @param $message
  5481. */
  5482. function addMessage($message)
  5483. {
  5484. $this->messages .= $message . "\n";
  5485. }
  5486. /**
  5487. * a few functions which should allow the document to be treated transactionally.
  5488. *
  5489. * @param $action
  5490. */
  5491. function transaction($action)
  5492. {
  5493. switch ($action) {
  5494. case 'start':
  5495. // store all the data away into the checkpoint variable
  5496. $data = get_object_vars($this);
  5497. $this->checkpoint = $data;
  5498. unset($data);
  5499. break;
  5500. case 'commit':
  5501. if (is_array($this->checkpoint) && isset($this->checkpoint['checkpoint'])) {
  5502. $tmp = $this->checkpoint['checkpoint'];
  5503. $this->checkpoint = $tmp;
  5504. unset($tmp);
  5505. } else {
  5506. $this->checkpoint = '';
  5507. }
  5508. break;
  5509. case 'rewind':
  5510. // do not destroy the current checkpoint, but move us back to the state then, so that we can try again
  5511. if (is_array($this->checkpoint)) {
  5512. // can only abort if were inside a checkpoint
  5513. $tmp = $this->checkpoint;
  5514. foreach ($tmp as $k => $v) {
  5515. if ($k !== 'checkpoint') {
  5516. $this->$k = $v;
  5517. }
  5518. }
  5519. unset($tmp);
  5520. }
  5521. break;
  5522. case 'abort':
  5523. if (is_array($this->checkpoint)) {
  5524. // can only abort if were inside a checkpoint
  5525. $tmp = $this->checkpoint;
  5526. foreach ($tmp as $k => $v) {
  5527. $this->$k = $v;
  5528. }
  5529. unset($tmp);
  5530. }
  5531. break;
  5532. }
  5533. }
  5534. }