Cpdf~20171216-130144.php 187 KB

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