class.pdf.php 140 KB

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