Incluido dompdf.
[CLab.git] / include / dompdf / lib / class.pdf.php
blob04cf51622fbf15385f33f81802d94e9a528ec5e6
1 <?php
2 /**
3 * Cpdf
5 * http://www.ros.co.nz/pdf
7 * A PHP class to provide the basic functionality to create a pdf document without
8 * any requirement for additional modules.
10 * Note that they companion class CezPdf can be used to extend this class and dramatically
11 * simplify the creation of documents.
13 * IMPORTANT NOTE
14 * there is no warranty, implied or otherwise with this software.
16 * LICENCE
17 * This code has been placed in the Public Domain for all to enjoy.
19 * @author Wayne Munro <pdf@ros.co.nz>
20 * @version 009
21 * @package Cpdf
23 class Cpdf {
26 /**
27 * the current number of pdf objects in the document
29 public $numObj = 0;
31 /**
32 * this array contains all of the pdf objects, ready for final assembly
34 public $objects = array();
36 /**
37 * the objectId (number within the objects array) of the document catalog
39 public $catalogId;
41 /**
42 * array carrying information about the fonts that the system currently knows about
43 * used to ensure that a font is not loaded twice, among other things
45 public $fonts = array();
47 /**
48 * a record of the current font
50 public $currentFont = '';
52 /**
53 * the current base font
55 public $currentBaseFont = '';
57 /**
58 * the number of the current font within the font array
60 public $currentFontNum = 0;
62 /**
65 public $currentNode;
67 /**
68 * object number of the current page
70 public $currentPage;
72 /**
73 * object number of the currently active contents block
75 public $currentContents;
77 /**
78 * number of fonts within the system
80 public $numFonts = 0;
82 /**
83 * Number of graphic state resources used
85 private $numStates = 0;
88 /**
89 * current colour for fill operations, defaults to inactive value, all three components should be between 0 and 1 inclusive when active
91 public $currentColour = array('r'=>-1, 'g'=>-1, 'b'=>-1);
93 /**
94 * current colour for stroke operations (lines etc.)
96 public $currentStrokeColour = array('r'=>-1, 'g'=>-1, 'b'=>-1);
98 /**
99 * current style that lines are drawn in
101 public $currentLineStyle = '';
104 * current line transparency (partial graphics state)
106 public $currentLineTransparency = array("mode" => "Normal", "opacity" => 1.0);
109 * current fill transparency (partial graphics state)
111 public $currentFillTransparency = array("mode" => "Normal", "opacity" => 1.0);
114 * an array which is used to save the state of the document, mainly the colours and styles
115 * it is used to temporarily change to another state, the change back to what it was before
117 public $stateStack = array();
120 * number of elements within the state stack
122 public $nStateStack = 0;
125 * number of page objects within the document
127 public $numPages = 0;
130 * object Id storage stack
132 public $stack = array();
135 * number of elements within the object Id storage stack
137 public $nStack = 0;
140 * an array which contains information about the objects which are not firmly attached to pages
141 * these have been added with the addObject function
143 public $looseObjects = array();
146 * array contains infomation about how the loose objects are to be added to the document
148 public $addLooseObjects = array();
151 * the objectId of the information object for the document
152 * this contains authorship, title etc.
154 public $infoObject = 0;
157 * number of images being tracked within the document
159 public $numImages = 0;
162 * an array containing options about the document
163 * it defaults to turning on the compression of the objects
165 public $options = array('compression'=>1);
168 * the objectId of the first page of the document
170 public $firstPageId;
173 * used to track the last used value of the inter-word spacing, this is so that it is known
174 * when the spacing is changed.
176 public $wordSpaceAdjust = 0;
179 * the object Id of the procset object
181 public $procsetObjectId;
184 * store the information about the relationship between font families
185 * this used so that the code knows which font is the bold version of another font, etc.
186 * the value of this array is initialised in the constuctor function.
188 public $fontFamilies = array();
191 * track if the current font is bolded or italicised
193 public $currentTextState = '';
196 * messages are stored here during processing, these can be selected afterwards to give some useful debug information
198 public $messages = '';
201 * the ancryption array for the document encryption is stored here
203 public $arc4 = '';
206 * the object Id of the encryption information
208 public $arc4_objnum = 0;
211 * the file identifier, used to uniquely identify a pdf document
213 public $fileIdentifier = '';
216 * a flag to say if a document is to be encrypted or not
218 public $encrypted = 0;
221 * the ancryption key for the encryption of all the document content (structure is not encrypted)
223 public $encryptionKey = '';
226 * array which forms a stack to keep track of nested callback functions
228 public $callback = array();
231 * the number of callback functions in the callback array
233 public $nCallback = 0;
236 * store label->id pairs for named destinations, these will be used to replace internal links
237 * done this way so that destinations can be defined after the location that links to them
239 public $destinations = array();
242 * store the stack for the transaction commands, each item in here is a record of the values of all the
243 * publiciables within the class, so that the user can rollback at will (from each 'start' command)
244 * note that this includes the objects array, so these can be large.
246 public $checkpoint = '';
249 * class constructor
250 * this will start a new document
251 * @var array array of 4 numbers, defining the bottom left and upper right corner of the page. first two are normally zero.
253 function Cpdf ($pageSize = array(0, 0, 612, 792)) {
255 $this->newDocument($pageSize);
258 // also initialize the font families that are known about already
259 $this->setFontFamily('init');
261 // $this->fileIdentifier = md5('xxxxxxxx'.time());
268 * Document object methods (internal use only)
270 * There is about one object method for each type of object in the pdf document
271 * Each function has the same call list ($id,$action,$options).
272 * $id = the object ID of the object, or what it is to be if it is being created
273 * $action = a string specifying the action to be performed, though ALL must support:
274 * 'new' - create the object with the id $id
275 * 'out' - produce the output for the pdf object
276 * $options = optional, a string or array containing the various parameters for the object
278 * These, in conjunction with the output function are the ONLY way for output to be produced
279 * within the pdf 'file'.
283 *destination object, used to specify the location for the user to jump to, presently on opening
285 function o_destination($id, $action, $options = '') {
287 if ($action != 'new') {
289 $o = & $this->objects[$id];
292 switch ($action) {
294 case 'new':
296 $this->objects[$id] = array('t'=>'destination', 'info'=>array());
298 $tmp = '';
300 switch ($options['type']) {
302 case 'XYZ':
304 case 'FitR':
306 $tmp = ' '.$options['p3'].$tmp;
308 case 'FitH':
310 case 'FitV':
312 case 'FitBH':
314 case 'FitBV':
316 $tmp = ' '.$options['p1'].' '.$options['p2'].$tmp;
318 case 'Fit':
320 case 'FitB':
322 $tmp = $options['type'].$tmp;
324 $this->objects[$id]['info']['string'] = $tmp;
326 $this->objects[$id]['info']['page'] = $options['page'];
329 break;
331 case 'out':
333 $tmp = $o['info'];
335 $res = "\n".$id." 0 obj\n".'['.$tmp['page'].' 0 R /'.$tmp['string']."]\nendobj\n";
337 return $res;
339 break;
345 * set the viewer preferences
347 function o_viewerPreferences($id, $action, $options = '') {
349 if ($action != 'new') {
351 $o = & $this->objects[$id];
354 switch ($action) {
356 case 'new':
358 $this->objects[$id] = array('t'=>'viewerPreferences', 'info'=>array());
360 break;
362 case 'add':
364 foreach($options as $k=>$v) {
366 switch ($k) {
368 case 'HideToolbar':
370 case 'HideMenubar':
372 case 'HideWindowUI':
374 case 'FitWindow':
376 case 'CenterWindow':
378 case 'NonFullScreenPageMode':
380 case 'Direction':
382 $o['info'][$k] = $v;
384 break;
388 break;
390 case 'out':
393 $res = "\n".$id." 0 obj\n".'<< ';
395 foreach($o['info'] as $k=>$v) {
397 $res.= "\n/".$k.' '.$v;
400 $res.= "\n>>\n";
402 return $res;
404 break;
410 * define the document catalog, the overall controller for the document
412 function o_catalog($id, $action, $options = '') {
414 if ($action != 'new') {
416 $o = & $this->objects[$id];
419 switch ($action) {
421 case 'new':
423 $this->objects[$id] = array('t'=>'catalog', 'info'=>array());
425 $this->catalogId = $id;
427 break;
429 case 'outlines':
431 case 'pages':
433 case 'openHere':
435 $o['info'][$action] = $options;
437 break;
439 case 'viewerPreferences':
441 if (!isset($o['info']['viewerPreferences'])) {
443 $this->numObj++;
445 $this->o_viewerPreferences($this->numObj, 'new');
447 $o['info']['viewerPreferences'] = $this->numObj;
450 $vp = $o['info']['viewerPreferences'];
452 $this->o_viewerPreferences($vp, 'add', $options);
454 break;
456 case 'out':
458 $res = "\n".$id." 0 obj\n".'<< /Type /Catalog';
460 foreach($o['info'] as $k=>$v) {
462 switch ($k) {
464 case 'outlines':
466 $res.= "\n".'/Outlines '.$v.' 0 R';
468 break;
470 case 'pages':
472 $res.= "\n".'/Pages '.$v.' 0 R';
474 break;
476 case 'viewerPreferences':
478 $res.= "\n".'/ViewerPreferences '.$o['info']['viewerPreferences'].' 0 R';
480 break;
482 case 'openHere':
484 $res.= "\n".'/OpenAction '.$o['info']['openHere'].' 0 R';
486 break;
490 $res.= " >>\nendobj";
492 return $res;
494 break;
500 * object which is a parent to the pages in the document
502 function o_pages($id, $action, $options = '') {
504 if ($action != 'new') {
506 $o = & $this->objects[$id];
509 switch ($action) {
511 case 'new':
513 $this->objects[$id] = array('t'=>'pages', 'info'=>array());
515 $this->o_catalog($this->catalogId, 'pages', $id);
517 break;
519 case 'page':
521 if (!is_array($options)) {
523 // then it will just be the id of the new page
524 $o['info']['pages'][] = $options;
525 } else {
527 // then it should be an array having 'id','rid','pos', where rid=the page to which this one will be placed relative
528 // and pos is either 'before' or 'after', saying where this page will fit.
529 if (isset($options['id']) && isset($options['rid']) && isset($options['pos'])) {
531 $i = array_search($options['rid'], $o['info']['pages']);
533 if (isset($o['info']['pages'][$i]) && $o['info']['pages'][$i] == $options['rid']) {
535 // then there is a match
536 // make a space
537 switch ($options['pos']) {
539 case 'before':
541 $k = $i;
543 break;
545 case 'after':
547 $k = $i+1;
549 break;
551 default:
553 $k = -1;
555 break;
558 if ($k >= 0) {
560 for ($j = count($o['info']['pages']) -1;$j >= $k;$j--) {
562 $o['info']['pages'][$j+1] = $o['info']['pages'][$j];
565 $o['info']['pages'][$k] = $options['id'];
571 break;
573 case 'procset':
575 $o['info']['procset'] = $options;
577 break;
579 case 'mediaBox':
581 $o['info']['mediaBox'] = $options;
582 // which should be an array of 4 numbers
583 break;
585 case 'font':
587 $o['info']['fonts'][] = array('objNum'=>$options['objNum'], 'fontNum'=>$options['fontNum']);
589 break;
592 case 'extGState':
594 $o['info']['extGStates'][] = array('objNum' => $options['objNum'], 'stateNum' => $options['stateNum']);
596 break;
599 case 'xObject':
601 $o['info']['xObjects'][] = array('objNum'=>$options['objNum'], 'label'=>$options['label']);
603 break;
605 case 'out':
607 if (count($o['info']['pages'])) {
609 $res = "\n".$id." 0 obj\n<< /Type /Pages\n/Kids [";
611 foreach($o['info']['pages'] as $k=>$v) {
613 $res.= $v." 0 R\n";
616 $res.= "]\n/Count ".count($this->objects[$id]['info']['pages']);
619 if ( (isset($o['info']['fonts']) && count($o['info']['fonts'])) ||
620 isset($o['info']['procset']) ||
621 (isset($o['info']['extGStates']) && count($o['info']['extGStates']))) {
624 $res.= "\n/Resources <<";
626 if (isset($o['info']['procset'])) {
628 $res.= "\n/ProcSet ".$o['info']['procset']." 0 R";
631 if (isset($o['info']['fonts']) && count($o['info']['fonts'])) {
633 $res.= "\n/Font << ";
635 foreach($o['info']['fonts'] as $finfo) {
637 $res.= "\n/F".$finfo['fontNum']." ".$finfo['objNum']." 0 R";
640 $res.= " >>";
643 if (isset($o['info']['xObjects']) && count($o['info']['xObjects'])) {
645 $res.= "\n/XObject << ";
647 foreach($o['info']['xObjects'] as $finfo) {
649 $res.= "\n/".$finfo['label']." ".$finfo['objNum']." 0 R";
652 $res.= " >>";
655 if ( isset($o['info']['extGStates']) && count($o['info']['extGStates'])) {
657 $res.= "\n/ExtGState << ";
659 foreach ($o['info']['extGStates'] as $gstate) {
661 $res.= "\n/GS" . $gstate['stateNum'] . " " . $gstate['objNum'] . " 0 R";
664 $res.= " >>";
668 $res.= "\n>>";
670 if (isset($o['info']['mediaBox'])) {
672 $tmp = $o['info']['mediaBox'];
674 $res.= "\n/MediaBox [".sprintf('%.3f', $tmp[0]) .' '.sprintf('%.3f', $tmp[1]) .' '.sprintf('%.3f', $tmp[2]) .' '.sprintf('%.3f', $tmp[3]) .']';
678 $res.= "\n >>\nendobj";
679 } else {
681 $res = "\n".$id." 0 obj\n<< /Type /Pages\n/Count 0\n>>\nendobj";
684 return $res;
686 break;
692 * define the outlines in the doc, empty for now
694 function o_outlines($id, $action, $options = '') {
696 if ($action != 'new') {
698 $o = & $this->objects[$id];
701 switch ($action) {
703 case 'new':
705 $this->objects[$id] = array('t'=>'outlines', 'info'=>array('outlines'=>array()));
707 $this->o_catalog($this->catalogId, 'outlines', $id);
709 break;
711 case 'outline':
713 $o['info']['outlines'][] = $options;
715 break;
717 case 'out':
719 if (count($o['info']['outlines'])) {
721 $res = "\n".$id." 0 obj\n<< /Type /Outlines /Kids [";
723 foreach($o['info']['outlines'] as $k=>$v) {
725 $res.= $v." 0 R ";
728 $res.= "] /Count ".count($o['info']['outlines']) ." >>\nendobj";
729 } else {
731 $res = "\n".$id." 0 obj\n<< /Type /Outlines /Count 0 >>\nendobj";
734 return $res;
736 break;
742 * an object to hold the font description
744 function o_font($id, $action, $options = '') {
746 if ($action != 'new') {
748 $o = & $this->objects[$id];
751 switch ($action) {
753 case 'new':
755 $this->objects[$id] = array('t' => 'font', 'info' => array('name' => $options['name'], 'SubType' => 'Type1'));
757 $fontNum = $this->numFonts;
759 $this->objects[$id]['info']['fontNum'] = $fontNum;
761 // deal with the encoding and the differences
762 if (isset($options['differences'])) {
764 // then we'll need an encoding dictionary
765 $this->numObj++;
767 $this->o_fontEncoding($this->numObj, 'new', $options);
769 $this->objects[$id]['info']['encodingDictionary'] = $this->numObj;
770 } else if (isset($options['encoding'])) {
772 // we can specify encoding here
773 switch ($options['encoding']) {
775 case 'WinAnsiEncoding':
777 case 'MacRomanEncoding':
779 case 'MacExpertEncoding':
781 $this->objects[$id]['info']['encoding'] = $options['encoding'];
783 break;
785 case 'none':
787 break;
789 default:
791 $this->objects[$id]['info']['encoding'] = 'WinAnsiEncoding';
793 break;
795 } else {
797 $this->objects[$id]['info']['encoding'] = 'WinAnsiEncoding';
800 // also tell the pages node about the new font
801 $this->o_pages($this->currentNode, 'font', array('fontNum' => $fontNum, 'objNum' => $id));
803 break;
806 case 'add':
808 foreach ($options as $k => $v) {
810 switch ($k) {
812 case 'BaseFont':
814 $o['info']['name'] = $v;
816 break;
818 case 'FirstChar':
820 case 'LastChar':
822 case 'Widths':
824 case 'FontDescriptor':
826 case 'SubType':
828 $this->addMessage('o_font '.$k." : ".$v);
830 $o['info'][$k] = $v;
832 break;
836 break;
839 case 'out':
841 $res = "\n".$id." 0 obj\n<< /Type /Font\n/Subtype /".$o['info']['SubType']."\n";
843 $res.= "/Name /F".$o['info']['fontNum']."\n";
845 $res.= "/BaseFont /".$o['info']['name']."\n";
847 if (isset($o['info']['encodingDictionary'])) {
849 // then place a reference to the dictionary
850 $res.= "/Encoding ".$o['info']['encodingDictionary']." 0 R\n";
851 } else if (isset($o['info']['encoding'])) {
853 // use the specified encoding
854 $res.= "/Encoding /".$o['info']['encoding']."\n";
857 if (isset($o['info']['FirstChar'])) {
859 $res.= "/FirstChar ".$o['info']['FirstChar']."\n";
862 if (isset($o['info']['LastChar'])) {
864 $res.= "/LastChar ".$o['info']['LastChar']."\n";
867 if (isset($o['info']['Widths'])) {
869 $res.= "/Widths ".$o['info']['Widths']." 0 R\n";
872 if (isset($o['info']['FontDescriptor'])) {
874 $res.= "/FontDescriptor ".$o['info']['FontDescriptor']." 0 R\n";
877 $res.= ">>\nendobj";
879 return $res;
881 break;
887 * a font descriptor, needed for including additional fonts
889 function o_fontDescriptor($id, $action, $options = '') {
891 if ($action != 'new') {
893 $o = & $this->objects[$id];
896 switch ($action) {
898 case 'new':
900 $this->objects[$id] = array('t'=>'fontDescriptor', 'info'=>$options);
902 break;
904 case 'out':
906 $res = "\n".$id." 0 obj\n<< /Type /FontDescriptor\n";
908 foreach ($o['info'] as $label => $value) {
910 switch ($label) {
912 case 'Ascent':
914 case 'CapHeight':
916 case 'Descent':
918 case 'Flags':
920 case 'ItalicAngle':
922 case 'StemV':
924 case 'AvgWidth':
926 case 'Leading':
928 case 'MaxWidth':
930 case 'MissingWidth':
932 case 'StemH':
934 case 'XHeight':
936 case 'CharSet':
938 if (strlen($value)) {
940 $res.= '/'.$label.' '.$value."\n";
943 break;
945 case 'FontFile':
947 case 'FontFile2':
949 case 'FontFile3':
951 $res.= '/'.$label.' '.$value." 0 R\n";
953 break;
955 case 'FontBBox':
957 $res.= '/'.$label.' ['.$value[0].' '.$value[1].' '.$value[2].' '.$value[3]."]\n";
959 break;
961 case 'FontName':
963 $res.= '/'.$label.' /'.$value."\n";
965 break;
969 $res.= ">>\nendobj";
971 return $res;
973 break;
979 * the font encoding
981 function o_fontEncoding($id, $action, $options = '') {
983 if ($action != 'new') {
985 $o = & $this->objects[$id];
988 switch ($action) {
990 case 'new':
992 // the options array should contain 'differences' and maybe 'encoding'
993 $this->objects[$id] = array('t'=>'fontEncoding', 'info'=>$options);
995 break;
997 case 'out':
999 $res = "\n".$id." 0 obj\n<< /Type /Encoding\n";
1001 if (!isset($o['info']['encoding'])) {
1003 $o['info']['encoding'] = 'WinAnsiEncoding';
1006 if ($o['info']['encoding'] != 'none') {
1008 $res.= "/BaseEncoding /".$o['info']['encoding']."\n";
1011 $res.= "/Differences \n[";
1013 $onum = -100;
1015 foreach($o['info']['differences'] as $num=>$label) {
1017 if ($num != $onum+1) {
1019 // we cannot make use of consecutive numbering
1020 $res.= "\n".$num." /".$label;
1021 } else {
1023 $res.= " /".$label;
1026 $onum = $num;
1029 $res.= "\n]\n>>\nendobj";
1031 return $res;
1033 break;
1039 * the document procset, solves some problems with printing to old PS printers
1041 function o_procset($id, $action, $options = '') {
1043 if ($action != 'new') {
1045 $o = & $this->objects[$id];
1048 switch ($action) {
1050 case 'new':
1052 $this->objects[$id] = array('t'=>'procset', 'info'=>array('PDF'=>1, 'Text'=>1));
1054 $this->o_pages($this->currentNode, 'procset', $id);
1056 $this->procsetObjectId = $id;
1058 break;
1060 case 'add':
1062 // this is to add new items to the procset list, despite the fact that this is considered
1063 // obselete, the items are required for printing to some postscript printers
1064 switch ($options) {
1066 case 'ImageB':
1068 case 'ImageC':
1070 case 'ImageI':
1072 $o['info'][$options] = 1;
1074 break;
1077 break;
1079 case 'out':
1081 $res = "\n".$id." 0 obj\n[";
1083 foreach ($o['info'] as $label=>$val) {
1085 $res.= '/'.$label.' ';
1088 $res.= "]\nendobj";
1090 return $res;
1092 break;
1098 * define the document information
1100 function o_info($id, $action, $options = '') {
1102 if ($action != 'new') {
1104 $o = & $this->objects[$id];
1107 switch ($action) {
1109 case 'new':
1111 $this->infoObject = $id;
1113 $date = 'D:'.@date('Ymd');
1115 $this->objects[$id] = array('t'=>'info', 'info'=>array('Creator'=>'R and OS php pdf writer, http://www.ros.co.nz', 'CreationDate'=>$date));
1117 break;
1119 case 'Title':
1121 case 'Author':
1123 case 'Subject':
1125 case 'Keywords':
1127 case 'Creator':
1129 case 'Producer':
1131 case 'CreationDate':
1133 case 'ModDate':
1135 case 'Trapped':
1137 $o['info'][$action] = $options;
1139 break;
1141 case 'out':
1143 if ($this->encrypted) {
1145 $this->encryptInit($id);
1148 $res = "\n".$id." 0 obj\n<<\n";
1150 foreach ($o['info'] as $k=>$v) {
1152 $res.= '/'.$k.' (';
1154 if ($this->encrypted) {
1156 $res.= $this->filterText($this->ARC4($v));
1157 } else {
1159 $res.= $this->filterText($v);
1162 $res.= ")\n";
1165 $res.= ">>\nendobj";
1167 return $res;
1169 break;
1175 * an action object, used to link to URLS initially
1177 function o_action($id, $action, $options = '') {
1179 if ($action != 'new') {
1181 $o = & $this->objects[$id];
1184 switch ($action) {
1186 case 'new':
1188 if (is_array($options)) {
1190 $this->objects[$id] = array('t'=>'action', 'info'=>$options, 'type'=>$options['type']);
1191 } else {
1193 // then assume a URI action
1194 $this->objects[$id] = array('t'=>'action', 'info'=>$options, 'type'=>'URI');
1197 break;
1199 case 'out':
1201 if ($this->encrypted) {
1203 $this->encryptInit($id);
1206 $res = "\n".$id." 0 obj\n<< /Type /Action";
1208 switch ($o['type']) {
1210 case 'ilink':
1212 // there will be an 'label' setting, this is the name of the destination
1213 $res.= "\n/S /GoTo\n/D ".$this->destinations[(string)$o['info']['label']]." 0 R";
1215 break;
1217 case 'URI':
1219 $res.= "\n/S /URI\n/URI (";
1221 if ($this->encrypted) {
1223 $res.= $this->filterText($this->ARC4($o['info']));
1224 } else {
1226 $res.= $this->filterText($o['info']);
1229 $res.= ")";
1231 break;
1234 $res.= "\n>>\nendobj";
1236 return $res;
1238 break;
1244 * an annotation object, this will add an annotation to the current page.
1245 * initially will support just link annotations
1247 function o_annotation($id, $action, $options = '') {
1249 if ($action != 'new') {
1251 $o = & $this->objects[$id];
1254 switch ($action) {
1256 case 'new':
1258 // add the annotation to the current page
1259 $pageId = $this->currentPage;
1261 $this->o_page($pageId, 'annot', $id);
1263 // and add the action object which is going to be required
1264 switch ($options['type']) {
1266 case 'link':
1268 $this->objects[$id] = array('t'=>'annotation', 'info'=>$options);
1270 $this->numObj++;
1272 $this->o_action($this->numObj, 'new', $options['url']);
1274 $this->objects[$id]['info']['actionId'] = $this->numObj;
1276 break;
1278 case 'ilink':
1280 // this is to a named internal link
1281 $label = $options['label'];
1283 $this->objects[$id] = array('t'=>'annotation', 'info'=>$options);
1285 $this->numObj++;
1287 $this->o_action($this->numObj, 'new', array('type'=>'ilink', 'label'=>$label));
1289 $this->objects[$id]['info']['actionId'] = $this->numObj;
1291 break;
1294 break;
1296 case 'out':
1298 $res = "\n".$id." 0 obj\n<< /Type /Annot";
1300 switch ($o['info']['type']) {
1302 case 'link':
1304 case 'ilink':
1306 $res.= "\n/Subtype /Link";
1308 break;
1311 $res.= "\n/A ".$o['info']['actionId']." 0 R";
1313 $res.= "\n/Border [0 0 0]";
1315 $res.= "\n/H /I";
1317 $res.= "\n/Rect [ ";
1319 foreach($o['info']['rect'] as $v) {
1321 $res.= sprintf("%.4f ", $v);
1324 $res.= "]";
1326 $res.= "\n>>\nendobj";
1328 return $res;
1330 break;
1336 * a page object, it also creates a contents object to hold its contents
1338 function o_page($id, $action, $options = '') {
1340 if ($action != 'new') {
1342 $o = & $this->objects[$id];
1345 switch ($action) {
1347 case 'new':
1349 $this->numPages++;
1351 $this->objects[$id] = array('t'=>'page', 'info'=>array('parent'=>$this->currentNode, 'pageNum'=>$this->numPages));
1353 if (is_array($options)) {
1355 // then this must be a page insertion, array shoudl contain 'rid','pos'=[before|after]
1356 $options['id'] = $id;
1358 $this->o_pages($this->currentNode, 'page', $options);
1359 } else {
1361 $this->o_pages($this->currentNode, 'page', $id);
1364 $this->currentPage = $id;
1366 //make a contents object to go with this page
1367 $this->numObj++;
1369 $this->o_contents($this->numObj, 'new', $id);
1371 $this->currentContents = $this->numObj;
1373 $this->objects[$id]['info']['contents'] = array();
1375 $this->objects[$id]['info']['contents'][] = $this->numObj;
1377 $match = ($this->numPages%2 ? 'odd' : 'even');
1379 foreach($this->addLooseObjects as $oId=>$target) {
1381 if ($target == 'all' || $match == $target) {
1383 $this->objects[$id]['info']['contents'][] = $oId;
1387 break;
1389 case 'content':
1391 $o['info']['contents'][] = $options;
1393 break;
1395 case 'annot':
1397 // add an annotation to this page
1398 if (!isset($o['info']['annot'])) {
1400 $o['info']['annot'] = array();
1403 // $options should contain the id of the annotation dictionary
1404 $o['info']['annot'][] = $options;
1406 break;
1408 case 'out':
1410 $res = "\n".$id." 0 obj\n<< /Type /Page";
1412 $res.= "\n/Parent ".$o['info']['parent']." 0 R";
1414 if (isset($o['info']['annot'])) {
1416 $res.= "\n/Annots [";
1418 foreach($o['info']['annot'] as $aId) {
1420 $res.= " ".$aId." 0 R";
1423 $res.= " ]";
1426 $count = count($o['info']['contents']);
1428 if ($count == 1) {
1430 $res.= "\n/Contents ".$o['info']['contents'][0]." 0 R";
1431 } else if ($count>1) {
1433 $res.= "\n/Contents [\n";
1435 // reverse the page contents so added objects are below normal content
1436 //foreach (array_reverse($o['info']['contents']) as $cId) {
1438 // Back to normal now that I've got transparency working --Benj
1439 foreach ($o['info']['contents'] as $cId) {
1440 $res.= $cId." 0 R\n";
1443 $res.= "]";
1446 $res.= "\n>>\nendobj";
1448 return $res;
1450 break;
1456 * the contents objects hold all of the content which appears on pages
1458 function o_contents($id, $action, $options = '') {
1460 if ($action != 'new') {
1462 $o = & $this->objects[$id];
1465 switch ($action) {
1467 case 'new':
1469 $this->objects[$id] = array('t'=>'contents', 'c'=>'', 'info'=>array());
1471 if (strlen($options) && intval($options)) {
1473 // then this contents is the primary for a page
1474 $this->objects[$id]['onPage'] = $options;
1475 } else if ($options == 'raw') {
1477 // then this page contains some other type of system object
1478 $this->objects[$id]['raw'] = 1;
1481 break;
1483 case 'add':
1485 // add more options to the decleration
1486 foreach ($options as $k=>$v) {
1488 $o['info'][$k] = $v;
1491 case 'out':
1493 $tmp = $o['c'];
1495 $res = "\n".$id." 0 obj\n";
1497 if (isset($this->objects[$id]['raw'])) {
1499 $res.= $tmp;
1500 } else {
1502 $res.= "<<";
1504 if (function_exists('gzcompress') && $this->options['compression']) {
1506 // then implement ZLIB based compression on this content stream
1507 $res.= " /Filter /FlateDecode";
1509 $tmp = gzcompress($tmp, 6);
1512 if ($this->encrypted) {
1514 $this->encryptInit($id);
1516 $tmp = $this->ARC4($tmp);
1519 foreach($o['info'] as $k=>$v) {
1521 $res.= "\n/".$k.' '.$v;
1524 $res.= "\n/Length ".strlen($tmp) ." >>\nstream\n".$tmp."\nendstream";
1527 $res.= "\nendobj\n";
1529 return $res;
1531 break;
1537 * an image object, will be an XObject in the document, includes description and data
1539 function o_image($id, $action, $options = '') {
1541 if ($action != 'new') {
1543 $o = & $this->objects[$id];
1546 switch ($action) {
1548 case 'new':
1550 // make the new object
1551 $this->objects[$id] = array('t'=>'image', 'data'=>&$options['data'], 'info'=>array());
1553 $this->objects[$id]['info']['Type'] = '/XObject';
1555 $this->objects[$id]['info']['Subtype'] = '/Image';
1557 $this->objects[$id]['info']['Width'] = $options['iw'];
1559 $this->objects[$id]['info']['Height'] = $options['ih'];
1561 if (!isset($options['type']) || $options['type'] == 'jpg') {
1563 if (!isset($options['channels'])) {
1565 $options['channels'] = 3;
1568 switch ($options['channels']) {
1570 case 1:
1572 $this->objects[$id]['info']['ColorSpace'] = '/DeviceGray';
1574 break;
1576 default:
1578 $this->objects[$id]['info']['ColorSpace'] = '/DeviceRGB';
1580 break;
1583 $this->objects[$id]['info']['Filter'] = '/DCTDecode';
1585 $this->objects[$id]['info']['BitsPerComponent'] = 8;
1586 } else if ($options['type'] == 'png') {
1588 $this->objects[$id]['info']['Filter'] = '/FlateDecode';
1590 $this->objects[$id]['info']['DecodeParms'] = '<< /Predictor 15 /Colors '.$options['ncolor'].' /Columns '.$options['iw'].' /BitsPerComponent '.$options['bitsPerComponent'].'>>';
1591 if (strlen($options['pdata'])) {
1593 $tmp = ' [ /Indexed /DeviceRGB '.(strlen($options['pdata']) /3-1) .' ';
1595 $this->numObj++;
1597 $this->o_contents($this->numObj, 'new');
1599 $this->objects[$this->numObj]['c'] = $options['pdata'];
1601 $tmp.= $this->numObj.' 0 R';
1603 $tmp.= ' ]';
1605 $this->objects[$id]['info']['ColorSpace'] = $tmp;
1607 if (isset($options['transparency'])) {
1609 switch ($options['transparency']['type']) {
1611 case 'indexed':
1613 $tmp = ' [ '.$options['transparency']['data'].' '.$options['transparency']['data'].'] ';
1615 $this->objects[$id]['info']['Mask'] = $tmp;
1617 break;
1619 case 'color-key':
1620 $tmp = ' [ '.
1621 $options['transparency']['r'] . ' ' . $options['transparency']['r'] .
1622 $options['transparency']['g'] . ' ' . $options['transparency']['g'] .
1623 $options['transparency']['b'] . ' ' . $options['transparency']['b'] .
1624 ' ] ';
1625 $this->objects[$id]['info']['Mask'] = $tmp;
1626 pre_r($tmp);
1627 break;
1631 } else {
1633 if (isset($options['transparency'])) {
1635 switch ($options['transparency']['type']) {
1637 case 'indexed':
1639 $tmp = ' [ '.$options['transparency']['data'].' '.$options['transparency']['data'].'] ';
1641 $this->objects[$id]['info']['Mask'] = $tmp;
1643 break;
1645 case 'color-key':
1646 $tmp = ' [ '.
1647 $options['transparency']['r'] . ' ' . $options['transparency']['r'] . ' ' .
1648 $options['transparency']['g'] . ' ' . $options['transparency']['g'] . ' ' .
1649 $options['transparency']['b'] . ' ' . $options['transparency']['b'] .
1650 ' ] ';
1651 $this->objects[$id]['info']['Mask'] = $tmp;
1652 break;
1656 $this->objects[$id]['info']['ColorSpace'] = '/'.$options['color'];
1659 $this->objects[$id]['info']['BitsPerComponent'] = $options['bitsPerComponent'];
1662 // assign it a place in the named resource dictionary as an external object, according to
1663 // the label passed in with it.
1664 $this->o_pages($this->currentNode, 'xObject', array('label'=>$options['label'], 'objNum'=>$id));
1666 // also make sure that we have the right procset object for it.
1667 $this->o_procset($this->procsetObjectId, 'add', 'ImageC');
1669 break;
1671 case 'out':
1673 $tmp = &$o['data'];
1675 $res = "\n".$id." 0 obj\n<<";
1677 foreach($o['info'] as $k=>$v) {
1679 $res.= "\n/".$k.' '.$v;
1682 if ($this->encrypted) {
1684 $this->encryptInit($id);
1686 $tmp = $this->ARC4($tmp);
1689 $res.= "\n/Length ".strlen($tmp) ." >>\nstream\n".$tmp."\nendstream\nendobj\n";
1691 return $res;
1693 break;
1699 * graphics state object
1701 function o_extGState($id, $action, $options = "") {
1703 static $valid_params = array("LW", "LC", "LC", "LJ", "ML",
1704 "D", "RI", "OP", "op", "OPM",
1705 "Font", "BG", "BG2", "UCR",
1706 "TR", "TR2", "HT", "FL",
1707 "SM", "SA", "BM", "SMask",
1708 "CA", "ca", "AIS", "TK");
1710 if ( $action != "new") {
1711 $o = & $this->objects[$id];
1714 switch ($action) {
1716 case "new":
1717 $this->objects[$id] = array('t' => 'extGState', 'info' => $options);
1719 // Tell the pages about the new resource
1720 $this->numStates++;
1721 $this->o_pages($this->currentNode, 'extGState', array("objNum" => $id, "stateNum" => $this->numStates));
1722 break;
1725 case "out":
1726 $res =
1727 "\n" . $id . " 0 obj\n".
1728 "<< /Type /ExtGState\n";
1730 foreach ($o["info"] as $parameter => $value) {
1731 if ( !in_array($parameter, $valid_params))
1732 continue;
1733 $res.= "/$parameter $value\n";
1736 $res.=
1737 ">>\n".
1738 "endobj";
1740 return $res;
1746 * encryption object.
1748 function o_encryption($id, $action, $options = '') {
1750 if ($action != 'new') {
1752 $o = & $this->objects[$id];
1755 switch ($action) {
1757 case 'new':
1759 // make the new object
1760 $this->objects[$id] = array('t'=>'encryption', 'info'=>$options);
1762 $this->arc4_objnum = $id;
1764 // figure out the additional paramaters required
1765 $pad = chr(0x28) .chr(0xBF) .chr(0x4E) .chr(0x5E) .chr(0x4E) .chr(0x75) .chr(0x8A) .chr(0x41) .chr(0x64) .chr(0x00) .chr(0x4E) .chr(0x56) .chr(0xFF) .chr(0xFA) .chr(0x01) .chr(0x08) .chr(0x2E) .chr(0x2E) .chr(0x00) .chr(0xB6) .chr(0xD0) .chr(0x68) .chr(0x3E) .chr(0x80) .chr(0x2F) .chr(0x0C) .chr(0xA9) .chr(0xFE) .chr(0x64) .chr(0x53) .chr(0x69) .chr(0x7A);
1767 $len = strlen($options['owner']);
1769 if ($len>32) {
1771 $owner = substr($options['owner'], 0, 32);
1772 } else if ($len<32) {
1774 $owner = $options['owner'].substr($pad, 0, 32-$len);
1775 } else {
1777 $owner = $options['owner'];
1780 $len = strlen($options['user']);
1782 if ($len>32) {
1784 $user = substr($options['user'], 0, 32);
1785 } else if ($len<32) {
1787 $user = $options['user'].substr($pad, 0, 32-$len);
1788 } else {
1790 $user = $options['user'];
1793 $tmp = $this->md5_16($owner);
1795 $okey = substr($tmp, 0, 5);
1797 $this->ARC4_init($okey);
1799 $ovalue = $this->ARC4($user);
1801 $this->objects[$id]['info']['O'] = $ovalue;
1803 // now make the u value, phew.
1804 $tmp = $this->md5_16($user.$ovalue.chr($options['p']) .chr(255) .chr(255) .chr(255) .$this->fileIdentifier);
1806 $ukey = substr($tmp, 0, 5);
1809 $this->ARC4_init($ukey);
1811 $this->encryptionKey = $ukey;
1813 $this->encrypted = 1;
1815 $uvalue = $this->ARC4($pad);
1818 $this->objects[$id]['info']['U'] = $uvalue;
1820 $this->encryptionKey = $ukey;
1823 // initialize the arc4 array
1824 break;
1826 case 'out':
1828 $res = "\n".$id." 0 obj\n<<";
1830 $res.= "\n/Filter /Standard";
1832 $res.= "\n/V 1";
1834 $res.= "\n/R 2";
1836 $res.= "\n/O (".$this->filterText($o['info']['O']) .')';
1838 $res.= "\n/U (".$this->filterText($o['info']['U']) .')';
1840 // and the p-value needs to be converted to account for the twos-complement approach
1841 $o['info']['p'] = (($o['info']['p']^255) +1) *-1;
1843 $res.= "\n/P ".($o['info']['p']);
1845 $res.= "\n>>\nendobj\n";
1848 return $res;
1850 break;
1856 * ARC4 functions
1857 * A series of function to implement ARC4 encoding in PHP
1861 * calculate the 16 byte version of the 128 bit md5 digest of the string
1863 function md5_16($string) {
1865 $tmp = md5($string);
1867 $out = '';
1869 for ($i = 0;$i <= 30;$i = $i+2) {
1871 $out.= chr(hexdec(substr($tmp, $i, 2)));
1874 return $out;
1879 * initialize the encryption for processing a particular object
1881 function encryptInit($id) {
1883 $tmp = $this->encryptionKey;
1885 $hex = dechex($id);
1887 if (strlen($hex) <6) {
1889 $hex = substr('000000', 0, 6-strlen($hex)) .$hex;
1892 $tmp.= chr(hexdec(substr($hex, 4, 2))) .chr(hexdec(substr($hex, 2, 2))) .chr(hexdec(substr($hex, 0, 2))) .chr(0) .chr(0);
1894 $key = $this->md5_16($tmp);
1896 $this->ARC4_init(substr($key, 0, 10));
1901 * initialize the ARC4 encryption
1903 function ARC4_init($key = '') {
1905 $this->arc4 = '';
1907 // setup the control array
1908 if (strlen($key) == 0) {
1910 return;
1913 $k = '';
1915 while (strlen($k) <256) {
1917 $k.= $key;
1920 $k = substr($k, 0, 256);
1922 for ($i = 0;$i<256;$i++) {
1924 $this->arc4.= chr($i);
1927 $j = 0;
1929 for ($i = 0;$i<256;$i++) {
1931 $t = $this->arc4[$i];
1933 $j = ($j + ord($t) + ord($k[$i])) %256;
1935 $this->arc4[$i] = $this->arc4[$j];
1937 $this->arc4[$j] = $t;
1943 * ARC4 encrypt a text string
1945 function ARC4($text) {
1947 $len = strlen($text);
1949 $a = 0;
1951 $b = 0;
1953 $c = $this->arc4;
1955 $out = '';
1957 for ($i = 0;$i<$len;$i++) {
1959 $a = ($a+1) %256;
1961 $t = $c[$a];
1963 $b = ($b+ord($t)) %256;
1965 $c[$a] = $c[$b];
1967 $c[$b] = $t;
1969 $k = ord($c[(ord($c[$a]) +ord($c[$b])) %256]);
1971 $out.= chr(ord($text[$i]) ^ $k);
1975 return $out;
1980 * functions which can be called to adjust or add to the document
1984 * add a link in the document to an external URL
1986 function addLink($url, $x0, $y0, $x1, $y1) {
1988 $this->numObj++;
1990 $info = array('type'=>'link', 'url'=>$url, 'rect'=>array($x0, $y0, $x1, $y1));
1992 $this->o_annotation($this->numObj, 'new', $info);
1997 * add a link in the document to an internal destination (ie. within the document)
1999 function addInternalLink($label, $x0, $y0, $x1, $y1) {
2001 $this->numObj++;
2003 $info = array('type'=>'ilink', 'label'=>$label, 'rect'=>array($x0, $y0, $x1, $y1));
2005 $this->o_annotation($this->numObj, 'new', $info);
2010 * set the encryption of the document
2011 * can be used to turn it on and/or set the passwords which it will have.
2012 * also the functions that the user will have are set here, such as print, modify, add
2014 function setEncryption($userPass = '', $ownerPass = '', $pc = array()) {
2016 $p = bindec(11000000);
2019 $options = array(
2020 'print'=>4, 'modify'=>8, 'copy'=>16, 'add'=>32);
2022 foreach($pc as $k=>$v) {
2024 if ($v && isset($options[$k])) {
2026 $p+= $options[$k];
2027 } else if (isset($options[$v])) {
2029 $p+= $options[$v];
2033 // implement encryption on the document
2034 if ($this->arc4_objnum == 0) {
2036 // then the block does not exist already, add it.
2037 $this->numObj++;
2039 if (strlen($ownerPass) == 0) {
2041 $ownerPass = $userPass;
2044 $this->o_encryption($this->numObj, 'new', array('user'=>$userPass, 'owner'=>$ownerPass, 'p'=>$p));
2050 * should be used for internal checks, not implemented as yet
2052 function checkAllHere() {
2057 * return the pdf stream as a string returned from the function
2059 function output($debug = 0) {
2062 if ($debug) {
2064 // turn compression off
2065 $this->options['compression'] = 0;
2069 if ($this->arc4_objnum) {
2071 $this->ARC4_init($this->encryptionKey);
2075 $this->checkAllHere();
2078 $xref = array();
2080 $content = "%PDF-1.3\n%âãÏÓ\n";
2082 // $content="%PDF-1.3\n";
2083 $pos = strlen($content);
2085 foreach($this->objects as $k=>$v) {
2087 $tmp = 'o_'.$v['t'];
2089 $cont = $this->$tmp($k, 'out');
2091 $content.= $cont;
2093 $xref[] = $pos;
2095 $pos+= strlen($cont);
2098 $content.= "\nxref\n0 ".(count($xref) +1) ."\n0000000000 65535 f \n";
2100 foreach($xref as $p) {
2102 $content.= str_pad($p, 10, "0", STR_PAD_LEFT) . " 00000 n \n";
2105 $content.= "trailer\n<<\n/Size ".(count($xref) +1) ."\n/Root 1 0 R\n/Info ".$this->infoObject." 0 R\n";
2107 // if encryption has been applied to this document then add the marker for this dictionary
2108 if ($this->arc4_objnum > 0) {
2110 $content.= "/Encrypt ".$this->arc4_objnum." 0 R\n";
2113 if (strlen($this->fileIdentifier)) {
2115 $content.= "/ID[<".$this->fileIdentifier."><".$this->fileIdentifier.">]\n";
2118 $content.= ">>\nstartxref\n".$pos."\n%%EOF\n";
2120 return $content;
2125 * intialize a new document
2126 * if this is called on an existing document results may be unpredictable, but the existing document would be lost at minimum
2127 * this function is called automatically by the constructor function
2129 * @access private
2131 function newDocument($pageSize = array(0, 0, 612, 792)) {
2133 $this->numObj = 0;
2135 $this->objects = array();
2138 $this->numObj++;
2140 $this->o_catalog($this->numObj, 'new');
2143 $this->numObj++;
2145 $this->o_outlines($this->numObj, 'new');
2148 $this->numObj++;
2150 $this->o_pages($this->numObj, 'new');
2153 $this->o_pages($this->numObj, 'mediaBox', $pageSize);
2155 $this->currentNode = 3;
2158 $this->numObj++;
2160 $this->o_procset($this->numObj, 'new');
2163 $this->numObj++;
2165 $this->o_info($this->numObj, 'new');
2168 $this->numObj++;
2170 $this->o_page($this->numObj, 'new');
2173 // need to store the first page id as there is no way to get it to the user during
2174 // startup
2175 $this->firstPageId = $this->currentContents;
2180 * open the font file and return a php structure containing it.
2181 * first check if this one has been done before and saved in a form more suited to php
2182 * note that if a php serialized version does not exist it will try and make one, but will
2183 * require write access to the directory to do it... it is MUCH faster to have these serialized
2184 * files.
2186 * @access private
2188 function openFont($font) {
2190 // assume that $font contains both the path and perhaps the extension to the file, split them
2191 $pos = strrpos($font, '/');
2193 if ($pos === false) {
2195 $dir = './';
2197 $name = $font;
2198 } else {
2200 $dir = substr($font, 0, $pos+1);
2202 $name = substr($font, $pos+1);
2206 if (substr($name, -4) == '.afm') {
2208 $name = substr($name, 0, strlen($name) -4);
2211 $this->addMessage('openFont: '.$font.' - '.$name);
2213 if (file_exists($dir . 'php_' . $name . '.afm')) {
2215 $this->addMessage('openFont: php file exists ' . $dir . 'php_' . $name.'.afm');
2217 $tmp = file_get_contents($dir.'php_'.$name.'.afm');
2219 eval($tmp);
2221 if (!isset($this->fonts[$font]['_version_']) || $this->fonts[$font]['_version_']<1) {
2223 // if the font file is old, then clear it out and prepare for re-creation
2224 $this->addMessage('openFont: clear out, make way for new version.');
2226 unset($this->fonts[$font]);
2230 if (!isset($this->fonts[$font]) && file_exists($dir.$name.'.afm')) {
2232 // then rebuild the php_<font>.afm file from the <font>.afm file
2233 $this->addMessage('openFont: build php file from '.$dir.$name.'.afm');
2235 $data = array();
2237 $file = file($dir.$name.'.afm');
2239 foreach ($file as $rowA) {
2241 $row = trim($rowA);
2243 $pos = strpos($row, ' ');
2245 if ($pos) {
2247 // then there must be some keyword
2248 $key = substr($row, 0, $pos);
2250 switch ($key) {
2252 case 'FontName':
2254 case 'FullName':
2256 case 'FamilyName':
2258 case 'Weight':
2260 case 'ItalicAngle':
2262 case 'IsFixedPitch':
2264 case 'CharacterSet':
2266 case 'UnderlinePosition':
2268 case 'UnderlineThickness':
2270 case 'Version':
2272 case 'EncodingScheme':
2274 case 'CapHeight':
2276 case 'XHeight':
2278 case 'Ascender':
2280 case 'Descender':
2282 case 'StdHW':
2284 case 'StdVW':
2286 case 'StartCharMetrics':
2288 $data[$key] = trim(substr($row, $pos));
2290 break;
2292 case 'FontBBox':
2294 $data[$key] = explode(' ', trim(substr($row, $pos)));
2296 break;
2298 case 'C':
2300 //C 39 ; WX 222 ; N quoteright ; B 53 463 157 718 ;
2301 $bits = explode(';', trim($row));
2303 $dtmp = array();
2305 foreach($bits as $bit) {
2307 $bits2 = explode(' ', trim($bit));
2309 if (strlen($bits2[0])) {
2311 if (count($bits2) >2) {
2313 $dtmp[$bits2[0]] = array();
2315 for ($i = 1;$i<count($bits2);$i++) {
2317 $dtmp[$bits2[0]][] = $bits2[$i];
2319 } else if (count($bits2) == 2) {
2321 $dtmp[$bits2[0]] = $bits2[1];
2326 if ($dtmp['C'] >= 0) {
2328 $data['C'][$dtmp['C']] = $dtmp;
2330 $data['C'][$dtmp['N']] = $dtmp;
2331 } else {
2333 $data['C'][$dtmp['N']] = $dtmp;
2336 break;
2338 case 'KPX':
2340 //KPX Adieresis yacute -40
2341 $bits = explode(' ', trim($row));
2343 $data['KPX'][$bits[1]][$bits[2]] = $bits[3];
2345 break;
2350 $data['_version_'] = 1;
2352 $this->fonts[$font] = $data;
2354 file_put_contents($dir . 'php_' . $name . '.afm', '$this->fonts[$font]=' . var_export($data, true) . ';');
2355 } else if (!isset($this->fonts[$font])) {
2357 $this->addMessage('openFont: no font file found');
2359 // echo 'Font not Found '.$font;
2366 * if the font is not loaded then load it and make the required object
2367 * else just make it the current font
2368 * the encoding array can contain 'encoding'=> 'none','WinAnsiEncoding','MacRomanEncoding' or 'MacExpertEncoding'
2369 * note that encoding='none' will need to be used for symbolic fonts
2370 * and 'differences' => an array of mappings between numbers 0->255 and character names.
2373 function selectFont($fontName, $encoding = '', $set = 1) {
2375 if (!isset($this->fonts[$fontName])) {
2377 // load the file
2378 $this->openFont($fontName);
2380 if (isset($this->fonts[$fontName])) {
2382 $this->numObj++;
2384 $this->numFonts++;
2386 //$this->numFonts = md5($fontName);
2387 $pos = strrpos($fontName, '/');
2389 // $dir = substr($fontName,0,$pos+1);
2390 $name = substr($fontName, $pos+1);
2392 if (substr($name, -4) == '.afm') {
2394 $name = substr($name, 0, strlen($name) -4);
2398 $options = array('name' => $name);
2400 if (is_array($encoding)) {
2402 // then encoding and differences might be set
2403 if (isset($encoding['encoding'])) {
2405 $options['encoding'] = $encoding['encoding'];
2408 if (isset($encoding['differences'])) {
2410 $options['differences'] = $encoding['differences'];
2412 } else if (strlen($encoding)) {
2414 // then perhaps only the encoding has been set
2415 $options['encoding'] = $encoding;
2419 $fontObj = $this->numObj;
2421 $this->o_font($this->numObj, 'new', $options);
2423 $this->fonts[$fontName]['fontNum'] = $this->numFonts;
2426 // if this is a '.afm' font, and there is a '.pfa' file to go with it ( as there
2427 // should be for all non-basic fonts), then load it into an object and put the
2428 // references into the font object
2429 $basefile = substr($fontName, 0, strlen($fontName) -4);
2431 if (file_exists($basefile.'.pfb')) {
2433 $fbtype = 'pfb';
2434 } else if (file_exists($basefile.'.ttf')) {
2436 $fbtype = 'ttf';
2437 } else {
2439 $fbtype = '';
2442 $fbfile = $basefile.'.'.$fbtype;
2445 // $pfbfile = substr($fontName,0,strlen($fontName)-4).'.pfb';
2446 // $ttffile = substr($fontName,0,strlen($fontName)-4).'.ttf';
2447 $this->addMessage('selectFont: checking for - '.$fbfile);
2450 if (substr($fontName, -4) == '.afm' && strlen($fbtype)) {
2452 $adobeFontName = $this->fonts[$fontName]['FontName'];
2454 // $fontObj = $this->numObj;
2455 $this->addMessage('selectFont: adding font file - '.$fbfile.' - '.$adobeFontName);
2457 // find the array of fond widths, and put that into an object.
2458 $firstChar = -1;
2460 $lastChar = 0;
2462 $widths = array();
2464 foreach ($this->fonts[$fontName]['C'] as $num => $d) {
2466 if (intval($num) >0 || $num == '0') {
2468 if ($lastChar>0 && $num>$lastChar+1) {
2470 for ($i = $lastChar+1;$i<$num;$i++) {
2472 $widths[] = 0;
2476 $widths[] = $d['WX'];
2478 if ($firstChar == -1) {
2480 $firstChar = $num;
2483 $lastChar = $num;
2487 // also need to adjust the widths for the differences array
2488 if (isset($options['differences'])) {
2490 foreach($options['differences'] as $charNum => $charName) {
2492 if ($charNum > $lastChar) {
2494 for ($i = $lastChar + 1; $i <= $charNum; $i++) {
2496 $widths[] = 0;
2499 $lastChar = $charNum;
2502 if (isset($this->fonts[$fontName]['C'][$charName])) {
2504 $widths[$charNum-$firstChar] = $this->fonts[$fontName]['C'][$charName]['WX'];
2509 $this->addMessage('selectFont: FirstChar = '.$firstChar);
2511 $this->addMessage('selectFont: LastChar = '.$lastChar);
2513 $this->numObj++;
2515 $this->o_contents($this->numObj, 'new', 'raw');
2517 $this->objects[$this->numObj]['c'].= '[';
2519 foreach($widths as $width) {
2521 $this->objects[$this->numObj]['c'].= ' '.$width;
2524 $this->objects[$this->numObj]['c'].= ' ]';
2526 $widthid = $this->numObj;
2529 // load the pfb file, and put that into an object too.
2530 // note that pdf supports only binary format type 1 font files, though there is a
2531 // simple utility to convert them from pfa to pfb.
2532 $tmp = get_magic_quotes_runtime();
2534 set_magic_quotes_runtime(0);
2536 $data = file_get_contents($fbfile);
2538 set_magic_quotes_runtime($tmp);
2541 // create the font descriptor
2542 $this->numObj++;
2544 $fontDescriptorId = $this->numObj;
2546 $this->numObj++;
2548 $pfbid = $this->numObj;
2550 // determine flags (more than a little flakey, hopefully will not matter much)
2551 $flags = 0;
2553 if ($this->fonts[$fontName]['ItalicAngle'] != 0) {
2554 $flags+= pow(2, 6);
2557 if ($this->fonts[$fontName]['IsFixedPitch'] == 'true') {
2558 $flags+= 1;
2561 $flags+= pow(2, 5);
2562 // assume non-sybolic
2564 $list = array('Ascent' => 'Ascender', 'CapHeight' => 'CapHeight', 'Descent' => 'Descender', 'FontBBox' => 'FontBBox', 'ItalicAngle' => 'ItalicAngle');
2566 $fdopt = array(
2567 'Flags' => $flags, 'FontName' => $adobeFontName, 'StemV' => 100 // don't know what the value for this should be!
2570 foreach($list as $k => $v) {
2572 if (isset($this->fonts[$fontName][$v])) {
2574 $fdopt[$k] = $this->fonts[$fontName][$v];
2579 if ($fbtype == 'pfb') {
2581 $fdopt['FontFile'] = $pfbid;
2582 } else if ($fbtype == 'ttf') {
2584 $fdopt['FontFile2'] = $pfbid;
2587 $this->o_fontDescriptor($fontDescriptorId, 'new', $fdopt);
2590 // embed the font program
2591 $this->o_contents($this->numObj, 'new');
2593 $this->objects[$pfbid]['c'].= $data;
2595 // determine the cruicial lengths within this file
2596 if ($fbtype == 'pfb') {
2598 $l1 = strpos($data, 'eexec') +6;
2600 $l2 = strpos($data, '00000000') -$l1;
2602 $l3 = strlen($data) -$l2-$l1;
2604 $this->o_contents($this->numObj, 'add', array('Length1' => $l1, 'Length2' => $l2, 'Length3' => $l3));
2605 } else if ($fbtype == 'ttf') {
2607 $l1 = strlen($data);
2609 $this->o_contents($this->numObj, 'add', array('Length1' => $l1));
2614 // tell the font object about all this new stuff
2615 $tmp = array('BaseFont' => $adobeFontName, 'Widths' => $widthid, 'FirstChar' => $firstChar, 'LastChar' => $lastChar, 'FontDescriptor' => $fontDescriptorId);
2617 if ($fbtype == 'ttf') {
2619 $tmp['SubType'] = 'TrueType';
2622 $this->addMessage('adding extra info to font.('.$fontObj.')');
2624 foreach($tmp as $fk => $fv) {
2626 $this->addMessage($fk." : ".$fv);
2629 $this->o_font($fontObj, 'add', $tmp);
2630 } else {
2632 $this->addMessage('selectFont: pfb or ttf file not found, ok if this is one of the 14 standard fonts');
2637 // also set the differences here, note that this means that these will take effect only the
2638 //first time that a font is selected, else they are ignored
2639 if (isset($options['differences'])) {
2641 $this->fonts[$fontName]['differences'] = $options['differences'];
2646 if ($set && isset($this->fonts[$fontName])) {
2648 // so if for some reason the font was not set in the last one then it will not be selected
2649 $this->currentBaseFont = $fontName;
2651 // the next lines mean that if a new font is selected, then the current text state will be
2652 // applied to it as well.
2653 $this->currentFont = $this->currentBaseFont;
2655 $this->currentFontNum = $this->fonts[$this->currentFont]['fontNum'];
2657 //$this->setCurrentFont();
2661 return $this->currentFontNum;
2663 //return $this->numObj;
2669 * sets up the current font, based on the font families, and the current text state
2670 * note that this system is quite flexible, a bold-italic font can be completely different to a
2671 * italic-bold font, and even bold-bold will have to be defined within the family to have meaning
2672 * This function is to be called whenever the currentTextState is changed, it will update
2673 * the currentFont setting to whatever the appropriatte family one is.
2674 * If the user calls selectFont themselves then that will reset the currentBaseFont, and the currentFont
2675 * This function will change the currentFont to whatever it should be, but will not change the
2676 * currentBaseFont.
2678 * @access private
2680 function setCurrentFont() {
2682 // if (strlen($this->currentBaseFont) == 0){
2683 // // then assume an initial font
2684 // $this->selectFont('./fonts/Helvetica.afm');
2685 // }
2686 // $cf = substr($this->currentBaseFont,strrpos($this->currentBaseFont,'/')+1);
2687 // if (strlen($this->currentTextState)
2688 // && isset($this->fontFamilies[$cf])
2689 // && isset($this->fontFamilies[$cf][$this->currentTextState])){
2690 // // then we are in some state or another
2691 // // and this font has a family, and the current setting exists within it
2692 // // select the font, then return it
2693 // $nf = substr($this->currentBaseFont,0,strrpos($this->currentBaseFont,'/')+1).$this->fontFamilies[$cf][$this->currentTextState];
2694 // $this->selectFont($nf,'',0);
2695 // $this->currentFont = $nf;
2696 // $this->currentFontNum = $this->fonts[$nf]['fontNum'];
2697 // } else {
2698 // // the this font must not have the right family member for the current state
2699 // // simply assume the base font
2700 $this->currentFont = $this->currentBaseFont;
2702 $this->currentFontNum = $this->fonts[$this->currentFont]['fontNum'];
2704 // }
2710 * function for the user to find out what the ID is of the first page that was created during
2711 * startup - useful if they wish to add something to it later.
2713 function getFirstPageId() {
2715 return $this->firstPageId;
2720 * add content to the currently active object
2722 * @access private
2724 function addContent($content) {
2726 $this->objects[$this->currentContents]['c'].= $content;
2731 * sets the colour for fill operations
2733 function setColor($r, $g, $b, $force = 0) {
2735 if ($r >= 0 && ($force || $r != $this->currentColour['r'] || $g != $this->currentColour['g'] || $b != $this->currentColour['b'])) {
2737 $this->objects[$this->currentContents]['c'].= "\n".sprintf('%.3f', $r) .' '.sprintf('%.3f', $g) .' '.sprintf('%.3f', $b) .' rg';
2739 $this->currentColour = array('r' => $r, 'g' => $g, 'b' => $b);
2745 * sets the colour for stroke operations
2747 function setStrokeColor($r, $g, $b, $force = 0) {
2749 if ($r >= 0 && ($force || $r != $this->currentStrokeColour['r'] || $g != $this->currentStrokeColour['g'] || $b != $this->currentStrokeColour['b'])) {
2751 $this->objects[$this->currentContents]['c'].= "\n".sprintf('%.3f', $r) .' '.sprintf('%.3f', $g) .' '.sprintf('%.3f', $b) .' RG';
2753 $this->currentStrokeColour = array('r' => $r, 'g' => $g, 'b' => $b);
2759 * Set the graphics state for compositions
2761 function setGraphicsState($parameters) {
2763 // Create a new graphics state object
2764 // FIXME: should actually keep track of states that have already been created...
2765 $this->numObj++;
2767 $this->o_extGState($this->numObj, 'new', $parameters);
2769 $this->objects[ $this->currentContents ]['c'].= "\n/GS" . $this->numStates . " gs";
2774 * Set current blend mode & opacity for lines.
2776 * Valid blend modes are:
2778 * Normal, Multiply, Screen, Overlay, Darken, Lighten,
2779 * ColorDogde, ColorBurn, HardLight, SoftLight, Difference,
2780 * Exclusion
2782 * @param string $mode the blend mode to use
2783 * @param float $opacity 0.0 fully transparent, 1.0 fully opaque
2785 function setLineTransparency($mode, $opacity) {
2786 static $blend_modes = array("Normal", "Multiply", "Screen",
2787 "Overlay", "Darken", "Lighten",
2788 "ColorDogde", "ColorBurn", "HardLight",
2789 "SoftLight", "Difference", "Exclusion");
2791 if ( !in_array($mode, $blend_modes) )
2792 $mode = "Normal";
2794 // Only create a new graphics state if required
2795 if ( $mode == $this->currentLineTransparency["mode"] &&
2796 $opacity == $this->currentLineTransparency["opacity"] )
2797 return;
2799 $options = array("BM" => "/$mode",
2800 "CA" => (float)$opacity);
2802 $this->setGraphicsState($options);
2806 * Set current blend mode & opacity for filled objects.
2808 * Valid blend modes are:
2810 * Normal, Multiply, Screen, Overlay, Darken, Lighten,
2811 * ColorDogde, ColorBurn, HardLight, SoftLight, Difference,
2812 * Exclusion
2814 * @param string $mode the blend mode to use
2815 * @param float $opacity 0.0 fully transparent, 1.0 fully opaque
2817 function setFillTransparency($mode, $opacity) {
2818 static $blend_modes = array("Normal", "Multiply", "Screen",
2819 "Overlay", "Darken", "Lighten",
2820 "ColorDogde", "ColorBurn", "HardLight",
2821 "SoftLight", "Difference", "Exclusion");
2823 if ( !in_array($mode, $blend_modes) )
2824 $mode = "Normal";
2826 if ( $mode == $this->currentFillTransparency["mode"] &&
2827 $opacity == $this->currentFillTransparency["opacity"] )
2828 return;
2830 $options = array("BM" => "/$mode",
2831 "ca" => (float)$opacity);
2833 $this->setGraphicsState($options);
2837 * draw a line from one set of coordinates to another
2839 function line($x1, $y1, $x2, $y2) {
2841 $this->objects[$this->currentContents]['c'] .=
2842 "\n".sprintf('%.3f', $x1) .' '.sprintf('%.3f', $y1) .' m '.sprintf('%.3f', $x2) .' '.sprintf('%.3f', $y2) .' l S';
2847 * draw a bezier curve based on 4 control points
2849 function curve($x0, $y0, $x1, $y1, $x2, $y2, $x3, $y3) {
2851 // in the current line style, draw a bezier curve from (x0,y0) to (x3,y3) using the other two points
2852 // as the control points for the curve.
2853 $this->objects[$this->currentContents]['c'] .=
2854 "\n".sprintf('%.3f', $x0) .' '.sprintf('%.3f', $y0) .' m '.sprintf('%.3f', $x1) .' '.sprintf('%.3f', $y1);
2856 $this->objects[$this->currentContents]['c'] .=
2857 ' '.sprintf('%.3f', $x2) .' '.sprintf('%.3f', $y2) .' '.sprintf('%.3f', $x3) .' '.sprintf('%.3f', $y3) .' c S';
2862 * draw a part of an ellipse
2864 function partEllipse($x0, $y0, $astart, $afinish, $r1, $r2 = 0, $angle = 0, $nSeg = 8) {
2866 $this->ellipse($x0, $y0, $r1, $r2, $angle, $nSeg, $astart, $afinish, 0);
2871 * draw a filled ellipse
2873 function filledEllipse($x0, $y0, $r1, $r2 = 0, $angle = 0, $nSeg = 8, $astart = 0, $afinish = 360) {
2875 return $this->ellipse($x0, $y0, $r1, $r2 = 0, $angle, $nSeg, $astart, $afinish, 1, 1);
2880 * draw an ellipse
2881 * note that the part and filled ellipse are just special cases of this function
2883 * draws an ellipse in the current line style
2884 * centered at $x0,$y0, radii $r1,$r2
2885 * if $r2 is not set, then a circle is drawn
2886 * nSeg is not allowed to be less than 2, as this will simply draw a line (and will even draw a
2887 * pretty crappy shape at 2, as we are approximating with bezier curves.
2889 function ellipse($x0, $y0, $r1, $r2 = 0, $angle = 0, $nSeg = 8, $astart = 0, $afinish = 360, $close = 1, $fill = 0) {
2891 if ($r1 == 0) {
2892 return;
2895 if ($r2 == 0) {
2896 $r2 = $r1;
2899 if ($nSeg < 2) {
2900 $nSeg = 2;
2904 $astart = deg2rad((float)$astart);
2906 $afinish = deg2rad((float)$afinish);
2908 $totalAngle = $afinish-$astart;
2911 $dt = $totalAngle/$nSeg;
2913 $dtm = $dt/3;
2916 if ($angle != 0) {
2918 $a = -1*deg2rad((float)$angle);
2920 $tmp = "\n q ";
2921 $tmp .= sprintf('%.3f', cos($a)) .' '.sprintf('%.3f', (-1.0*sin($a))) .' '.sprintf('%.3f', sin($a)) .' '.sprintf('%.3f', cos($a)) .' ';
2922 $tmp .= sprintf('%.3f', $x0) .' '.sprintf('%.3f', $y0) .' cm';
2924 $this->objects[$this->currentContents]['c'].= $tmp;
2926 $x0 = 0;
2927 $y0 = 0;
2931 $t1 = $astart;
2932 $a0 = $x0 + $r1*cos($t1);
2933 $b0 = $y0 + $r2*sin($t1);
2934 $c0 = -$r1 * sin($t1);
2935 $d0 = $r2 * cos($t1);
2938 $this->objects[$this->currentContents]['c'] .= "\n".sprintf('%.3f', $a0) .' '.sprintf('%.3f', $b0) .' m ';
2940 for ($i = 1; $i <= $nSeg; $i++) {
2942 // draw this bit of the total curve
2943 $t1 = $i * $dt + $astart;
2945 $a1 = $x0 + $r1 * cos($t1);
2947 $b1 = $y0 + $r2 * sin($t1);
2949 $c1 = -$r1 * sin($t1);
2951 $d1 = $r2 * cos($t1);
2953 $this->objects[$this->currentContents]['c']
2954 .= "\n".sprintf('%.3f', ($a0+$c0*$dtm)) .' '.sprintf('%.3f', ($b0 + $d0 * $dtm));
2956 $this->objects[$this->currentContents]['c'] .=
2957 ' '.sprintf('%.3f', ($a1-$c1*$dtm)) .' '.sprintf('%.3f', ($b1-$d1*$dtm)) .' '.sprintf('%.3f', $a1) .' '.sprintf('%.3f', $b1) .' c';
2959 $a0 = $a1;
2961 $b0 = $b1;
2963 $c0 = $c1;
2965 $d0 = $d1;
2968 if ($fill) {
2969 $this->objects[$this->currentContents]['c'].= ' f';
2971 } else if ($close) {
2973 $this->objects[$this->currentContents]['c'].= ' s';
2974 // small 's' signifies closing the path as well
2976 } else {
2978 $this->objects[$this->currentContents]['c'].= ' S';
2982 if ($angle != 0) {
2983 $this->objects[$this->currentContents]['c'].= ' Q';
2990 * this sets the line drawing style.
2991 * width, is the thickness of the line in user units
2992 * cap is the type of cap to put on the line, values can be 'butt','round','square'
2993 * where the diffference between 'square' and 'butt' is that 'square' projects a flat end past the
2994 * end of the line.
2995 * join can be 'miter', 'round', 'bevel'
2996 * dash is an array which sets the dash pattern, is a series of length values, which are the lengths of the
2997 * on and off dashes.
2998 * (2) represents 2 on, 2 off, 2 on , 2 off ...
2999 * (2,1) is 2 on, 1 off, 2 on, 1 off.. etc
3000 * phase is a modifier on the dash pattern which is used to shift the point at which the pattern starts.
3002 function setLineStyle($width = 1, $cap = '', $join = '', $dash = '', $phase = 0) {
3005 // this is quite inefficient in that it sets all the parameters whenever 1 is changed, but will fix another day
3006 $string = '';
3008 if ($width>0) {
3010 $string.= $width.' w';
3013 $ca = array('butt' => 0, 'round' => 1, 'square' => 2);
3015 if (isset($ca[$cap])) {
3017 $string.= ' '.$ca[$cap].' J';
3020 $ja = array('miter' => 0, 'round' => 1, 'bevel' => 2);
3022 if (isset($ja[$join])) {
3024 $string.= ' '.$ja[$join].' j';
3027 if (is_array($dash)) {
3029 $string.= ' [';
3031 foreach ($dash as $len) {
3033 $string.= ' '.$len;
3036 $string.= ' ] '.$phase.' d';
3039 $this->currentLineStyle = $string;
3041 $this->objects[$this->currentContents]['c'].= "\n".$string;
3047 * draw a polygon, the syntax for this is similar to the GD polygon command
3049 function polygon($p, $np, $f = 0) {
3051 $this->objects[$this->currentContents]['c'].= "\n";
3053 $this->objects[$this->currentContents]['c'].= sprintf('%.3f', $p[0]) .' '.sprintf('%.3f', $p[1]) .' m ';
3055 for ($i = 2; $i < $np * 2; $i = $i + 2) {
3057 $this->objects[$this->currentContents]['c'].= sprintf('%.3f', $p[$i]) .' '.sprintf('%.3f', $p[$i+1]) .' l ';
3060 if ($f == 1) {
3062 $this->objects[$this->currentContents]['c'].= ' f';
3063 } else {
3065 $this->objects[$this->currentContents]['c'].= ' S';
3071 * a filled rectangle, note that it is the width and height of the rectangle which are the secondary paramaters, not
3072 * the coordinates of the upper-right corner
3074 function filledRectangle($x1, $y1, $width, $height) {
3076 $this->objects[$this->currentContents]['c'].= "\n".sprintf('%.3f', $x1) .' '.sprintf('%.3f', $y1) .' '.sprintf('%.3f', $width) .' '.sprintf('%.3f', $height) .' re f';
3081 * draw a rectangle, note that it is the width and height of the rectangle which are the secondary paramaters, not
3082 * the coordinates of the upper-right corner
3084 function rectangle($x1, $y1, $width, $height) {
3086 $this->objects[$this->currentContents]['c'].= "\n".sprintf('%.3f', $x1) .' '.sprintf('%.3f', $y1) .' '.sprintf('%.3f', $width) .' '.sprintf('%.3f', $height) .' re S';
3091 * add a new page to the document
3092 * this also makes the new page the current active object
3094 function newPage($insert = 0, $id = 0, $pos = 'after') {
3097 // if there is a state saved, then go up the stack closing them
3098 // then on the new page, re-open them with the right setings
3100 if ($this->nStateStack) {
3102 for ($i = $this->nStateStack;$i >= 1;$i--) {
3104 $this->restoreState($i);
3109 $this->numObj++;
3111 if ($insert) {
3113 // the id from the ezPdf class is the od of the contents of the page, not the page object itself
3114 // query that object to find the parent
3115 $rid = $this->objects[$id]['onPage'];
3117 $opt = array('rid' => $rid, 'pos' => $pos);
3119 $this->o_page($this->numObj, 'new', $opt);
3120 } else {
3122 $this->o_page($this->numObj, 'new');
3125 // if there is a stack saved, then put that onto the page
3126 if ($this->nStateStack) {
3128 for ($i = 1;$i <= $this->nStateStack;$i++) {
3130 $this->saveState($i);
3134 // and if there has been a stroke or fill colour set, then transfer them
3135 if ($this->currentColour['r'] >= 0) {
3137 $this->setColor($this->currentColour['r'], $this->currentColour['g'], $this->currentColour['b'], 1);
3140 if ($this->currentStrokeColour['r'] >= 0) {
3142 $this->setStrokeColor($this->currentStrokeColour['r'], $this->currentStrokeColour['g'], $this->currentStrokeColour['b'], 1);
3146 // if there is a line style set, then put this in too
3147 if (strlen($this->currentLineStyle)) {
3149 $this->objects[$this->currentContents]['c'].= "\n".$this->currentLineStyle;
3153 // the call to the o_page object set currentContents to the present page, so this can be returned as the page id
3154 return $this->currentContents;
3159 * output the pdf code, streaming it to the browser
3160 * the relevant headers are set so that hopefully the browser will recognise it
3162 function stream($options = '') {
3164 // setting the options allows the adjustment of the headers
3165 // values at the moment are:
3166 // 'Content-Disposition' => 'filename' - sets the filename, though not too sure how well this will
3167 // work as in my trial the browser seems to use the filename of the php file with .pdf on the end
3168 // 'Accept-Ranges' => 1 or 0 - if this is not set to 1, then this header is not included, off by default
3169 // this header seems to have caused some problems despite tha fact that it is supposed to solve
3170 // them, so I am leaving it off by default.
3171 // 'compress' = > 1 or 0 - apply content stream compression, this is on (1) by default
3172 // 'Attachment' => 1 or 0 - if 1, force the browser to open a download dialog
3173 if (!is_array($options)) {
3175 $options = array();
3178 if ( headers_sent())
3179 die("Unable to stream pdf: headers already sent");
3182 if ( isset($options['compress']) && $options['compress'] == 0) {
3184 $tmp = ltrim($this->output(1));
3185 } else {
3187 $tmp = ltrim($this->output());
3191 header("Cache-Control: private");
3193 header("Content-type: application/pdf");
3195 //header("Content-Length: " . strlen($tmp));
3196 $fileName = (isset($options['Content-Disposition']) ? $options['Content-Disposition'] : 'file.pdf');
3198 if ( !isset($options["Attachment"]))
3199 $options["Attachment"] = true;
3202 $attachment = $options["Attachment"] ? "attachment" : "inline";
3205 header("Content-Disposition: $attachment; filename=\"$fileName\"");
3208 if (isset($options['Accept-Ranges']) && $options['Accept-Ranges'] == 1) {
3210 header("Accept-Ranges: " . strlen($tmp));
3213 echo $tmp;
3215 flush();
3220 * return the height in units of the current font in the given size
3222 function getFontHeight($size) {
3224 if (!$this->numFonts) {
3226 $this->selectFont('./fonts/Helvetica');
3229 // for the current font, and the given size, what is the height of the font in user units
3230 $h = $this->fonts[$this->currentFont]['FontBBox'][3]-$this->fonts[$this->currentFont]['FontBBox'][1];
3232 return $size*$h/1000;
3237 * return the font decender, this will normally return a negative number
3238 * if you add this number to the baseline, you get the level of the bottom of the font
3239 * it is in the pdf user units
3241 function getFontDecender($size) {
3243 // note that this will most likely return a negative value
3244 if (!$this->numFonts) {
3246 $this->selectFont('./fonts/Helvetica');
3249 $h = $this->fonts[$this->currentFont]['FontBBox'][1];
3251 return $size*$h/1000;
3256 * filter the text, this is applied to all text just before being inserted into the pdf document
3257 * it escapes the various things that need to be escaped, and so on
3259 * @access private
3261 function filterText($text) {
3263 $search = array("\\", "(", ")", "&lt;", "&gt;", "&#039;", "&quot;", "&amp;");
3265 $replace = array("\\\\", "\(", "\)", "<", ">", "\'", '"', "&");
3267 $text = str_replace($search, $replace, $text);
3270 return $text;
3275 * given a start position and information about how text is to be laid out, calculate where
3276 * on the page the text will end
3278 * @access private
3280 function PRVTgetTextPosition($x, $y, $angle, $size, $wa, $text) {
3282 // given this information return an array containing x and y for the end position as elements 0 and 1
3283 $w = $this->getTextWidth($size, $text);
3285 // need to adjust for the number of spaces in this text
3286 $words = explode(' ', $text);
3288 $nspaces = count($words) -1;
3290 $w+= $wa*$nspaces;
3292 $a = deg2rad((float)$angle);
3294 return array(cos($a) *$w+$x, -sin($a) *$w+$y);
3299 * wrapper function for PRVTcheckTextDirective1
3301 * @access private
3303 function PRVTcheckTextDirective(&$text, $i, &$f) {
3305 return 0;
3307 $x = 0;
3309 $y = 0;
3311 return $this->PRVTcheckTextDirective1($text, $i, $f, 0, $x, $y);
3316 * checks if the text stream contains a control directive
3317 * if so then makes some changes and returns the number of characters involved in the directive
3318 * this has been re-worked to include everything neccesary to fins the current writing point, so that
3319 * the location can be sent to the callback function if required
3320 * if the directive does not require a font change, then $f should be set to 0
3322 * @access private
3324 function PRVTcheckTextDirective1(&$text, $i, &$f, $final, &$x, &$y, $size = 0, $angle = 0, $wordSpaceAdjust = 0) {
3326 return 0;
3328 $directive = 0;
3330 $j = $i;
3332 if ($text[$j] == '<') {
3334 $j++;
3336 switch ($text[$j]) {
3338 case '/':
3340 $j++;
3342 if (strlen($text) <= $j) {
3344 return $directive;
3347 switch ($text[$j]) {
3349 case 'b':
3351 case 'i':
3353 $j++;
3355 if ($text[$j] == '>') {
3357 $p = strrpos($this->currentTextState, $text[$j-1]);
3359 if ($p !== false) {
3361 // then there is one to remove
3362 $this->currentTextState = substr($this->currentTextState, 0, $p) .substr($this->currentTextState, $p+1);
3365 $directive = $j-$i+1;
3368 break;
3370 case 'c':
3372 // this this might be a callback function
3373 $j++;
3375 $k = strpos($text, '>', $j);
3377 if ($k !== false && $text[$j] == ':') {
3379 // then this will be treated as a callback directive
3380 $directive = $k-$i+1;
3382 $f = 0;
3384 // split the remainder on colons to get the function name and the paramater
3385 $tmp = substr($text, $j+1, $k-$j-1);
3387 $b1 = strpos($tmp, ':');
3389 if ($b1 !== false) {
3391 $func = substr($tmp, 0, $b1);
3393 $parm = substr($tmp, $b1+1);
3394 } else {
3396 $func = $tmp;
3398 $parm = '';
3401 if (!isset($func) || !strlen(trim($func))) {
3403 $directive = 0;
3404 } else {
3406 // only call the function if this is the final call
3407 if ($final) {
3409 // need to assess the text position, calculate the text width to this point
3410 // can use getTextWidth to find the text width I think
3411 $tmp = $this->PRVTgetTextPosition($x, $y, $angle, $size, $wordSpaceAdjust, substr($text, 0, $i));
3413 $info = array('x' => $tmp[0], 'y' => $tmp[1], 'angle' => $angle, 'status' => 'end', 'p' => $parm, 'nCallback' => $this->nCallback);
3415 $x = $tmp[0];
3417 $y = $tmp[1];
3419 $ret = $this->$func($info);
3421 if (is_array($ret)) {
3423 // then the return from the callback function could set the position, to start with, later will do font colour, and font
3424 foreach($ret as $rk => $rv) {
3426 switch ($rk) {
3428 case 'x':
3430 case 'y':
3432 $$rk = $rv;
3434 break;
3439 // also remove from to the stack
3440 // for simplicity, just take from the end, fix this another day
3441 $this->nCallback--;
3443 if ($this->nCallback<0) {
3445 $this->nCallBack = 0;
3451 break;
3454 break;
3456 case 'b':
3458 case 'i':
3460 $j++;
3462 if ($text[$j] == '>') {
3464 $this->currentTextState.= $text[$j-1];
3466 $directive = $j-$i+1;
3469 break;
3471 case 'C':
3473 $noClose = 1;
3475 case 'c':
3477 // this this might be a callback function
3478 $j++;
3480 $k = strpos($text, '>', $j);
3482 if ($k !== false && $text[$j] == ':') {
3484 // then this will be treated as a callback directive
3485 $directive = $k-$i+1;
3487 $f = 0;
3489 // split the remainder on colons to get the function name and the paramater
3490 // $bits = explode(':',substr($text,$j+1,$k-$j-1));
3491 $tmp = substr($text, $j+1, $k-$j-1);
3493 $b1 = strpos($tmp, ':');
3495 if ($b1 !== false) {
3497 $func = substr($tmp, 0, $b1);
3499 $parm = substr($tmp, $b1+1);
3500 } else {
3502 $func = $tmp;
3504 $parm = '';
3507 if (!isset($func) || !strlen(trim($func))) {
3509 $directive = 0;
3510 } else {
3512 // only call the function if this is the final call, ie, the one actually doing printing, not measurement
3513 if ($final) {
3515 // need to assess the text position, calculate the text width to this point
3516 // can use getTextWidth to find the text width I think
3517 // also add the text height and decender
3518 $tmp = $this->PRVTgetTextPosition($x, $y, $angle, $size, $wordSpaceAdjust, substr($text, 0, $i));
3520 $info = array('x' => $tmp[0], 'y' => $tmp[1], 'angle' => $angle, 'status' => 'start', 'p' => $parm, 'f' => $func, 'height' => $this->getFontHeight($size), 'decender' => $this->getFontDecender($size));
3522 $x = $tmp[0];
3524 $y = $tmp[1];
3526 if (!isset($noClose) || !$noClose) {
3528 // only add to the stack if this is a small 'c', therefore is a start-stop pair
3529 $this->nCallback++;
3531 $info['nCallback'] = $this->nCallback;
3533 $this->callback[$this->nCallback] = $info;
3536 $ret = $this->$func($info);
3538 if (is_array($ret)) {
3540 // then the return from the callback function could set the position, to start with, later will do font colour, and font
3541 foreach($ret as $rk => $rv) {
3543 switch ($rk) {
3545 case 'x':
3547 case 'y':
3549 $$rk = $rv;
3551 break;
3559 break;
3563 return $directive;
3568 * add text to the document, at a specified location, size and angle on the page
3570 function addText($x, $y, $size, $text, $angle = 0, $wordSpaceAdjust = 0) {
3572 if (!$this->numFonts) {
3573 $this->selectFont('./fonts/Helvetica');
3577 // if there are any open callbacks, then they should be called, to show the start of the line
3578 if ($this->nCallback>0) {
3580 for ($i = $this->nCallback;$i>0;$i--) {
3582 // call each function
3583 $info = array('x' => $x,
3584 'y' => $y,
3585 'angle' => $angle,
3586 'status' => 'sol',
3587 'p' => $this->callback[$i]['p'],
3588 'nCallback' => $this->callback[$i]['nCallback'],
3589 'height' => $this->callback[$i]['height'],
3590 'decender' => $this->callback[$i]['decender']);
3592 $func = $this->callback[$i]['f'];
3594 $this->$func($info);
3598 if ($angle == 0) {
3600 $this->objects[$this->currentContents]['c'].= "\n".'BT '.sprintf('%.3f', $x) .' '.sprintf('%.3f', $y) .' Td';
3602 } else {
3604 $a = deg2rad((float)$angle);
3606 $tmp = "\n".'BT ';
3608 $tmp.= sprintf('%.3f', cos($a)) .' '.sprintf('%.3f', (-1.0*sin($a))) .' '.sprintf('%.3f', sin($a)) .' '.sprintf('%.3f', cos($a)) .' ';
3610 $tmp.= sprintf('%.3f', $x) .' '.sprintf('%.3f', $y) .' Tm';
3612 $this->objects[$this->currentContents]['c'].= $tmp;
3615 if ($wordSpaceAdjust != 0 || $wordSpaceAdjust != $this->wordSpaceAdjust) {
3617 $this->wordSpaceAdjust = $wordSpaceAdjust;
3619 $this->objects[$this->currentContents]['c'].= ' '.sprintf('%.3f', $wordSpaceAdjust) .' Tw';
3622 $len = strlen($text);
3624 $start = 0;
3627 for ($i = 0;$i<$len;$i++){
3628 $f = 1;
3629 $directive = 0; //$this->PRVTcheckTextDirective($text,$i,$f);
3630 if ($directive){
3631 // then we should write what we need to
3632 if ($i>$start){
3633 $part = substr($text,$start,$i-$start);
3634 $this->objects[$this->currentContents]['c'] .= ' /F'.$this->currentFontNum.' '.sprintf('%.1f',$size).' Tf ';
3635 $this->objects[$this->currentContents]['c'] .= ' ('.$this->filterText($part).') Tj';
3637 if ($f){
3638 // then there was nothing drastic done here, restore the contents
3639 $this->setCurrentFont();
3640 } else {
3641 $this->objects[$this->currentContents]['c'] .= ' ET';
3642 $f = 1;
3643 $xp = $x;
3644 $yp = $y;
3645 $directive = 0; //$this->PRVTcheckTextDirective1($text,$i,$f,1,$xp,$yp,$size,$angle,$wordSpaceAdjust);
3647 // restart the text object
3648 if ($angle == 0){
3649 $this->objects[$this->currentContents]['c'] .= "\n".'BT '.sprintf('%.3f',$xp).' '.sprintf('%.3f',$yp).' Td';
3650 } else {
3651 $a = deg2rad((float)$angle);
3652 $tmp = "\n".'BT ';
3653 $tmp .= sprintf('%.3f',cos($a)).' '.sprintf('%.3f',(-1.0*sin($a))).' '.sprintf('%.3f',sin($a)).' '.sprintf('%.3f',cos($a)).' ';
3654 $tmp .= sprintf('%.3f',$xp).' '.sprintf('%.3f',$yp).' Tm';
3655 $this->objects[$this->currentContents]['c'] .= $tmp;
3657 if ($wordSpaceAdjust != 0 || $wordSpaceAdjust != $this->wordSpaceAdjust){
3658 $this->wordSpaceAdjust = $wordSpaceAdjust;
3659 $this->objects[$this->currentContents]['c'] .= ' '.sprintf('%.3f',$wordSpaceAdjust).' Tw';
3662 // and move the writing point to the next piece of text
3663 $i = $i+$directive-1;
3664 $start = $i+1;
3669 if ($start < $len) {
3671 $part = substr($text, $start);
3673 $this->objects[$this->currentContents]['c'].= ' /F'.$this->currentFontNum.' '.sprintf('%.1f', $size) .' Tf ';
3675 $this->objects[$this->currentContents]['c'].= ' ('.$this->filterText($part) .') Tj';
3678 $this->objects[$this->currentContents]['c'].= ' ET';
3681 // if there are any open callbacks, then they should be called, to show the end of the line
3682 if ($this->nCallback>0) {
3684 for ($i = $this->nCallback;$i>0;$i--) {
3686 // call each function
3687 $tmp = $this->PRVTgetTextPosition($x, $y, $angle, $size, $wordSpaceAdjust, $text);
3689 $info = array('x' => $tmp[0], 'y' => $tmp[1], 'angle' => $angle, 'status' => 'eol', 'p' => $this->callback[$i]['p'], 'nCallback' => $this->callback[$i]['nCallback'], 'height' => $this->callback[$i]['height'], 'decender' => $this->callback[$i]['decender']);
3691 $func = $this->callback[$i]['f'];
3693 $this->$func($info);
3700 * calculate how wide a given text string will be on a page, at a given size.
3701 * this can be called externally, but is alse used by the other class functions
3703 function getTextWidth($size, $text, $spacing = 0) {
3705 // this function should not change any of the settings, though it will need to
3706 // track any directives which change during calculation, so copy them at the start
3707 // and put them back at the end.
3708 $store_currentTextState = $this->currentTextState;
3711 if (!$this->numFonts) {
3713 $this->selectFont('./fonts/Helvetica');
3717 // converts a number or a float to a string so it can get the width
3718 $text = "$text";
3721 // hmm, this is where it all starts to get tricky - use the font information to
3722 // calculate the width of each character, add them up and convert to user units
3723 $w = 0;
3725 $len = strlen($text);
3727 $cf = $this->currentFont;
3729 $space_scale = 1000 / $size;
3731 for ($i = 0; $i < $len; $i++) {
3733 // $f = 1;
3734 // $directive = 0; //$this->PRVTcheckTextDirective($text,$i,$f);
3735 // if ($directive){
3736 // if ($f){
3737 // $this->setCurrentFont();
3738 // $cf = $this->currentFont;
3739 // }
3740 // $i = $i+$directive-1;
3741 // } else {
3742 $char = ord($text{$i});
3744 if ( isset($this->fonts[$cf]['differences'][$char])) {
3747 // then this character is being replaced by another
3748 $name = $this->fonts[$cf]['differences'][$char];
3751 if ( isset($this->fonts[$cf]['C'][$name]['WX']))
3752 $w+= $this->fonts[$cf]['C'][$name]['WX'];
3753 } else if (isset($this->fonts[$cf]['C'][$char]['WX']))
3754 $w+= $this->fonts[$cf]['C'][$char]['WX'];
3757 if ( $char == 32) // Space
3758 $w+= $spacing * $space_scale;
3763 $this->currentTextState = $store_currentTextState;
3765 $this->setCurrentFont();
3768 return $w*$size/1000;
3773 * do a part of the calculation for sorting out the justification of the text
3775 * @access private
3777 function PRVTadjustWrapText($text, $actual, $width, &$x, &$adjust, $justification) {
3779 switch ($justification) {
3781 case 'left':
3783 return;
3785 break;
3787 case 'right':
3789 $x+= $width-$actual;
3791 break;
3793 case 'center':
3795 case 'centre':
3797 $x+= ($width-$actual) /2;
3799 break;
3801 case 'full':
3803 // count the number of words
3804 $words = explode(' ', $text);
3806 $nspaces = count($words) -1;
3808 if ($nspaces>0) {
3810 $adjust = ($width-$actual) /$nspaces;
3811 } else {
3813 $adjust = 0;
3816 break;
3822 * add text to the page, but ensure that it fits within a certain width
3823 * if it does not fit then put in as much as possible, splitting at word boundaries
3824 * and return the remainder.
3825 * justification and angle can also be specified for the text
3827 function addTextWrap($x, $y, $width, $size, $text, $justification = 'left', $angle = 0, $test = 0) {
3829 // this will display the text, and if it goes beyond the width $width, will backtrack to the
3830 // previous space or hyphen, and return the remainder of the text.
3832 // $justification can be set to 'left','right','center','centre','full'
3834 // need to store the initial text state, as this will change during the width calculation
3835 // but will need to be re-set before printing, so that the chars work out right
3836 $store_currentTextState = $this->currentTextState;
3839 if (!$this->numFonts) {
3840 $this->selectFont('./fonts/Helvetica');
3843 if ($width <= 0) {
3845 // error, pretend it printed ok, otherwise risking a loop
3846 return '';
3849 $w = 0;
3851 $break = 0;
3853 $breakWidth = 0;
3855 $len = strlen($text);
3857 $cf = $this->currentFont;
3859 $tw = $width/$size*1000;
3861 for ($i = 0;$i<$len;$i++) {
3863 $f = 1;
3865 $directive = 0;
3866 //$this->PRVTcheckTextDirective($text,$i,$f);
3867 if ($directive) {
3869 if ($f) {
3871 $this->setCurrentFont();
3873 $cf = $this->currentFont;
3876 $i = $i+$directive-1;
3877 } else {
3879 $cOrd = ord($text[$i]);
3881 if (isset($this->fonts[$cf]['differences'][$cOrd])) {
3883 // then this character is being replaced by another
3884 $cOrd2 = $this->fonts[$cf]['differences'][$cOrd];
3885 } else {
3887 $cOrd2 = $cOrd;
3891 if (isset($this->fonts[$cf]['C'][$cOrd2]['WX'])) {
3893 $w+= $this->fonts[$cf]['C'][$cOrd2]['WX'];
3896 if ($w>$tw) {
3898 // then we need to truncate this line
3899 if ($break>0) {
3901 // then we have somewhere that we can split :)
3902 if ($text[$break] == ' ') {
3904 $tmp = substr($text, 0, $break);
3905 } else {
3907 $tmp = substr($text, 0, $break+1);
3910 $adjust = 0;
3912 $this->PRVTadjustWrapText($tmp, $breakWidth, $width, $x, $adjust, $justification);
3915 // reset the text state
3916 $this->currentTextState = $store_currentTextState;
3918 $this->setCurrentFont();
3920 if (!$test) {
3922 $this->addText($x, $y, $size, $tmp, $angle, $adjust);
3925 return substr($text, $break+1);
3926 } else {
3928 // just split before the current character
3929 $tmp = substr($text, 0, $i);
3931 $adjust = 0;
3933 $ctmp = ord($text[$i]);
3935 if (isset($this->fonts[$cf]['differences'][$ctmp])) {
3937 $ctmp = $this->fonts[$cf]['differences'][$ctmp];
3940 $tmpw = ($w-$this->fonts[$cf]['C'][$ctmp]['WX']) *$size/1000;
3942 $this->PRVTadjustWrapText($tmp, $tmpw, $width, $x, $adjust, $justification);
3944 // reset the text state
3945 $this->currentTextState = $store_currentTextState;
3947 $this->setCurrentFont();
3949 if (!$test) {
3951 $this->addText($x, $y, $size, $tmp, $angle, $adjust);
3954 return substr($text, $i);
3958 if ($text[$i] == '-') {
3960 $break = $i;
3962 $breakWidth = $w*$size/1000;
3965 if ($text[$i] == ' ') {
3967 $break = $i;
3969 $ctmp = ord($text[$i]);
3971 if (isset($this->fonts[$cf]['differences'][$ctmp])) {
3973 $ctmp = $this->fonts[$cf]['differences'][$ctmp];
3976 $breakWidth = ($w-$this->fonts[$cf]['C'][$ctmp]['WX']) *$size/1000;
3981 // then there was no need to break this line
3982 if ($justification == 'full') {
3984 $justification = 'left';
3987 $adjust = 0;
3989 $tmpw = $w*$size/1000;
3991 $this->PRVTadjustWrapText($text, $tmpw, $width, $x, $adjust, $justification);
3993 // reset the text state
3994 $this->currentTextState = $store_currentTextState;
3996 $this->setCurrentFont();
3998 if (!$test) {
4000 $this->addText($x, $y, $size, $text, $angle, $adjust, $angle);
4003 return '';
4008 * this will be called at a new page to return the state to what it was on the
4009 * end of the previous page, before the stack was closed down
4010 * This is to get around not being able to have open 'q' across pages
4013 function saveState($pageEnd = 0) {
4015 if ($pageEnd) {
4017 // this will be called at a new page to return the state to what it was on the
4018 // end of the previous page, before the stack was closed down
4019 // This is to get around not being able to have open 'q' across pages
4020 $opt = $this->stateStack[$pageEnd];
4021 // ok to use this as stack starts numbering at 1
4022 $this->setColor($opt['col']['r'], $opt['col']['g'], $opt['col']['b'], 1);
4024 $this->setStrokeColor($opt['str']['r'], $opt['str']['g'], $opt['str']['b'], 1);
4026 $this->objects[$this->currentContents]['c'].= "\n".$opt['lin'];
4028 // $this->currentLineStyle = $opt['lin'];
4030 } else {
4032 $this->nStateStack++;
4034 $this->stateStack[$this->nStateStack] = array(
4035 'col' => $this->currentColour, 'str' => $this->currentStrokeColour, 'lin' => $this->currentLineStyle);
4038 $this->objects[$this->currentContents]['c'].= "\nq";
4043 * restore a previously saved state
4045 function restoreState($pageEnd = 0) {
4047 if (!$pageEnd) {
4049 $n = $this->nStateStack;
4051 $this->currentColour = $this->stateStack[$n]['col'];
4053 $this->currentStrokeColour = $this->stateStack[$n]['str'];
4055 $this->objects[$this->currentContents]['c'].= "\n".$this->stateStack[$n]['lin'];
4057 $this->currentLineStyle = $this->stateStack[$n]['lin'];
4059 unset($this->stateStack[$n]);
4061 $this->nStateStack--;
4064 $this->objects[$this->currentContents]['c'].= "\nQ";
4069 * make a loose object, the output will go into this object, until it is closed, then will revert to
4070 * the current one.
4071 * this object will not appear until it is included within a page.
4072 * the function will return the object number
4074 function openObject() {
4076 $this->nStack++;
4078 $this->stack[$this->nStack] = array('c' => $this->currentContents, 'p' => $this->currentPage);
4080 // add a new object of the content type, to hold the data flow
4081 $this->numObj++;
4083 $this->o_contents($this->numObj, 'new');
4085 $this->currentContents = $this->numObj;
4087 $this->looseObjects[$this->numObj] = 1;
4090 return $this->numObj;
4095 * open an existing object for editing
4097 function reopenObject($id) {
4099 $this->nStack++;
4101 $this->stack[$this->nStack] = array('c' => $this->currentContents, 'p' => $this->currentPage);
4103 $this->currentContents = $id;
4105 // also if this object is the primary contents for a page, then set the current page to its parent
4106 if (isset($this->objects[$id]['onPage'])) {
4108 $this->currentPage = $this->objects[$id]['onPage'];
4114 * close an object
4116 function closeObject() {
4118 // close the object, as long as there was one open in the first place, which will be indicated by
4119 // an objectId on the stack.
4120 if ($this->nStack>0) {
4122 $this->currentContents = $this->stack[$this->nStack]['c'];
4124 $this->currentPage = $this->stack[$this->nStack]['p'];
4126 $this->nStack--;
4128 // easier to probably not worry about removing the old entries, they will be overwritten
4129 // if there are new ones.
4136 * stop an object from appearing on pages from this point on
4138 function stopObject($id) {
4140 // if an object has been appearing on pages up to now, then stop it, this page will
4141 // be the last one that could contian it.
4142 if (isset($this->addLooseObjects[$id])) {
4144 $this->addLooseObjects[$id] = '';
4150 * after an object has been created, it wil only show if it has been added, using this function.
4152 function addObject($id, $options = 'add') {
4154 // add the specified object to the page
4155 if (isset($this->looseObjects[$id]) && $this->currentContents != $id) {
4157 // then it is a valid object, and it is not being added to itself
4158 switch ($options) {
4160 case 'all':
4162 // then this object is to be added to this page (done in the next block) and
4163 // all future new pages.
4164 $this->addLooseObjects[$id] = 'all';
4166 case 'add':
4168 if (isset($this->objects[$this->currentContents]['onPage'])) {
4170 // then the destination contents is the primary for the page
4171 // (though this object is actually added to that page)
4172 $this->o_page($this->objects[$this->currentContents]['onPage'], 'content', $id);
4175 break;
4177 case 'even':
4179 $this->addLooseObjects[$id] = 'even';
4181 $pageObjectId = $this->objects[$this->currentContents]['onPage'];
4183 if ($this->objects[$pageObjectId]['info']['pageNum']%2 == 0) {
4185 $this->addObject($id);
4186 // hacky huh :)
4190 break;
4192 case 'odd':
4194 $this->addLooseObjects[$id] = 'odd';
4196 $pageObjectId = $this->objects[$this->currentContents]['onPage'];
4198 if ($this->objects[$pageObjectId]['info']['pageNum']%2 == 1) {
4200 $this->addObject($id);
4201 // hacky huh :)
4205 break;
4207 case 'next':
4209 $this->addLooseObjects[$id] = 'all';
4211 break;
4213 case 'nexteven':
4215 $this->addLooseObjects[$id] = 'even';
4217 break;
4219 case 'nextodd':
4221 $this->addLooseObjects[$id] = 'odd';
4223 break;
4230 * return a storable representation of a specific object
4232 function serializeObject($id) {
4234 if ( array_key_exists($id, $this->objects))
4235 return var_export($this->objects[$id], true);
4238 return null;
4243 * restore an object from its stored representation. returns its new object id.
4245 function restoreSerializedObject($obj) {
4248 $obj_id = $this->openObject();
4250 eval('$this->objects[$obj_id] = ' . $obj . ';');
4252 $this->closeObject();
4254 return $obj_id;
4260 * add content to the documents info object
4262 function addInfo($label, $value = 0) {
4264 // this will only work if the label is one of the valid ones.
4265 // modify this so that arrays can be passed as well.
4266 // if $label is an array then assume that it is key => value pairs
4267 // else assume that they are both scalar, anything else will probably error
4268 if (is_array($label)) {
4270 foreach ($label as $l => $v) {
4272 $this->o_info($this->infoObject, $l, $v);
4274 } else {
4276 $this->o_info($this->infoObject, $label, $value);
4282 * set the viewer preferences of the document, it is up to the browser to obey these.
4284 function setPreferences($label, $value = 0) {
4286 // this will only work if the label is one of the valid ones.
4287 if (is_array($label)) {
4289 foreach ($label as $l => $v) {
4291 $this->o_catalog($this->catalogId, 'viewerPreferences', array($l => $v));
4293 } else {
4295 $this->o_catalog($this->catalogId, 'viewerPreferences', array($label => $value));
4301 * extract an integer from a position in a byte stream
4303 * @access private
4305 function PRVT_getBytes(&$data, $pos, $num) {
4307 // return the integer represented by $num bytes from $pos within $data
4308 $ret = 0;
4310 for ($i = 0;$i<$num;$i++) {
4312 $ret = $ret*256;
4314 $ret+= ord($data[$pos+$i]);
4317 return $ret;
4322 * add a PNG image into the document, from a file
4323 * this should work with remote files
4325 function addPngFromFile($file, $x, $y, $w = 0, $h = 0) {
4327 // read in a png file, interpret it, then add to the system
4328 $error = 0;
4330 $tmp = get_magic_quotes_runtime();
4332 set_magic_quotes_runtime(0);
4334 if ( ($data = file_get_contents($file)) === false) {
4336 // $fp = @fopen($file,'rb');
4337 // if ($fp){
4338 // $data = '';
4339 // while(!feof($fp)){
4340 // $data .= fread($fp,1024);
4341 // }
4342 // fclose($fp);
4343 $error = 1;
4345 $errormsg = 'trouble opening file: '.$file;
4348 set_magic_quotes_runtime($tmp);
4351 if (!$error) {
4353 $header = chr(137) .chr(80) .chr(78) .chr(71) .chr(13) .chr(10) .chr(26) .chr(10);
4355 if (substr($data, 0, 8) != $header) {
4357 $error = 1;
4359 $errormsg = 'this file does not have a valid header';
4364 if (!$error) {
4366 // set pointer
4367 $p = 8;
4369 $len = strlen($data);
4371 // cycle through the file, identifying chunks
4372 $haveHeader = 0;
4374 $info = array();
4376 $idata = '';
4378 $pdata = '';
4380 while ($p < $len) {
4382 $chunkLen = $this->PRVT_getBytes($data, $p, 4);
4384 $chunkType = substr($data, $p+4, 4);
4386 // echo $chunkType.' - '.$chunkLen.'<br>';
4388 switch ($chunkType) {
4390 case 'IHDR':
4392 // this is where all the file information comes from
4393 $info['width'] = $this->PRVT_getBytes($data, $p+8, 4);
4395 $info['height'] = $this->PRVT_getBytes($data, $p+12, 4);
4397 $info['bitDepth'] = ord($data[$p+16]);
4399 $info['colorType'] = ord($data[$p+17]);
4401 $info['compressionMethod'] = ord($data[$p+18]);
4403 $info['filterMethod'] = ord($data[$p+19]);
4405 $info['interlaceMethod'] = ord($data[$p+20]);
4407 //print_r($info);
4408 $haveHeader = 1;
4410 if ($info['compressionMethod'] != 0) {
4412 $error = 1;
4414 $errormsg = 'unsupported compression method';
4417 if ($info['filterMethod'] != 0) {
4419 $error = 1;
4421 $errormsg = 'unsupported filter method';
4424 break;
4426 case 'PLTE':
4428 $pdata.= substr($data, $p+8, $chunkLen);
4430 break;
4432 case 'IDAT':
4434 $idata.= substr($data, $p+8, $chunkLen);
4436 break;
4438 case 'tRNS':
4440 //this chunk can only occur once and it must occur after the PLTE chunk and before IDAT chunk
4441 //print "tRNS found, color type = ".$info['colorType']."\n";
4442 $transparency = array();
4444 if ($info['colorType'] == 3) {
4445 // indexed color, rbg
4446 /* corresponding to entries in the plte chunk
4447 Alpha for palette index 0: 1 byte
4448 Alpha for palette index 1: 1 byte
4449 ...etc...
4451 // there will be one entry for each palette entry. up until the last non-opaque entry.
4452 // set up an array, stretching over all palette entries which will be o (opaque) or 1 (transparent)
4453 $transparency['type'] = 'indexed';
4455 $numPalette = strlen($pdata) /3;
4457 $trans = 0;
4459 for ($i = $chunkLen;$i >= 0;$i--) {
4461 if (ord($data[$p+8+$i]) == 0) {
4463 $trans = $i;
4467 $transparency['data'] = $trans;
4468 } elseif ($info['colorType'] == 0) {
4469 // grayscale
4470 /* corresponding to entries in the plte chunk
4471 Gray: 2 bytes, range 0 .. (2^bitdepth)-1
4473 // $transparency['grayscale'] = $this->PRVT_getBytes($data,$p+8,2); // g = grayscale
4474 $transparency['type'] = 'indexed';
4476 $transparency['data'] = ord($data[$p+8+1]);
4477 } elseif ($info['colorType'] == 2) {
4478 // truecolor
4479 /* corresponding to entries in the plte chunk
4480 Red: 2 bytes, range 0 .. (2^bitdepth)-1
4481 Green: 2 bytes, range 0 .. (2^bitdepth)-1
4482 Blue: 2 bytes, range 0 .. (2^bitdepth)-1
4484 $transparency['r'] = $this->PRVT_getBytes($data, $p+8, 2);
4485 // r from truecolor
4486 $transparency['g'] = $this->PRVT_getBytes($data, $p+10, 2);
4487 // g from truecolor
4488 $transparency['b'] = $this->PRVT_getBytes($data, $p+12, 2);
4489 // b from truecolor
4491 $transparency['type'] = 'color-key';
4493 } else {
4495 //unsupported transparency type
4499 // KS End new code
4500 break;
4502 default:
4504 break;
4508 $p+= $chunkLen+12;
4512 if (!$haveHeader) {
4514 $error = 1;
4516 $errormsg = 'information header is missing';
4519 if (isset($info['interlaceMethod']) && $info['interlaceMethod']) {
4521 $error = 1;
4523 $errormsg = 'There appears to be no support for interlaced images in pdf.';
4528 if (!$error && $info['bitDepth'] > 8) {
4530 $error = 1;
4532 $errormsg = 'only bit depth of 8 or less is supported';
4536 if (!$error) {
4538 if ($info['colorType'] != 2 && $info['colorType'] != 0 && $info['colorType'] != 3) {
4540 $error = 1;
4542 $errormsg = 'transparancey alpha channel not supported, transparency only supported for palette images.';
4543 } else {
4545 switch ($info['colorType']) {
4547 case 3:
4549 $color = 'DeviceRGB';
4551 $ncolor = 1;
4553 break;
4555 case 2:
4557 $color = 'DeviceRGB';
4559 $ncolor = 3;
4561 break;
4563 case 0:
4565 $color = 'DeviceGray';
4567 $ncolor = 1;
4569 break;
4574 if ($error) {
4576 $this->addMessage('PNG error - ('.$file.') '.$errormsg);
4578 return;
4581 if ($w == 0) {
4583 $w = $h/$info['height']*$info['width'];
4586 if ($h == 0) {
4588 $h = $w*$info['height']/$info['width'];
4591 //print_r($info);
4592 // so this image is ok... add it in.
4593 $this->numImages++;
4595 $im = $this->numImages;
4597 $label = 'I'.$im;
4599 $this->numObj++;
4601 // $this->o_image($this->numObj,'new',array('label' => $label,'data' => $idata,'iw' => $w,'ih' => $h,'type' => 'png','ic' => $info['width']));
4602 $options = array('label' => $label, 'data' => $idata, 'bitsPerComponent' => $info['bitDepth'], 'pdata' => $pdata, 'iw' => $info['width'], 'ih' => $info['height'], 'type' => 'png', 'color' => $color, 'ncolor' => $ncolor);
4604 if (isset($transparency)) {
4606 $options['transparency'] = $transparency;
4609 $this->o_image($this->numObj, 'new', $options);
4612 $this->objects[$this->currentContents]['c'].= "\nq";
4614 $this->objects[$this->currentContents]['c'].= "\n".sprintf('%.3f', $w) ." 0 0 ".sprintf('%.3f', $h) ." ".sprintf('%.3f', $x) ." ".sprintf('%.3f', $y) ." cm";
4616 $this->objects[$this->currentContents]['c'].= "\n/".$label.' Do';
4618 $this->objects[$this->currentContents]['c'].= "\nQ";
4623 * add a JPEG image into the document, from a file
4625 function addJpegFromFile($img, $x, $y, $w = 0, $h = 0) {
4627 // attempt to add a jpeg image straight from a file, using no GD commands
4628 // note that this function is unable to operate on a remote file.
4630 if (!file_exists($img)) {
4632 return;
4636 $tmp = getimagesize($img);
4638 $imageWidth = $tmp[0];
4640 $imageHeight = $tmp[1];
4643 if (isset($tmp['channels'])) {
4645 $channels = $tmp['channels'];
4646 } else {
4648 $channels = 3;
4652 if ($w <= 0 && $h <= 0) {
4654 $w = $imageWidth;
4657 if ($w == 0) {
4659 $w = $h/$imageHeight*$imageWidth;
4662 if ($h == 0) {
4664 $h = $w*$imageHeight/$imageWidth;
4668 //$fp = fopen($img,'rb');
4670 $tmp = get_magic_quotes_runtime();
4672 set_magic_quotes_runtime(0);
4674 $data = file_get_contents($img);
4676 //fread($fp,filesize($img));
4677 set_magic_quotes_runtime($tmp);
4680 //fclose($fp);
4682 $this->addJpegImage_common($data, $x, $y, $w, $h, $imageWidth, $imageHeight, $channels);
4687 * add an image into the document, from a GD object
4688 * this function is not all that reliable, and I would probably encourage people to use
4689 * the file based functions
4691 function addImage(&$img, $x, $y, $w = 0, $h = 0, $quality = 75) {
4693 // add a new image into the current location, as an external object
4694 // add the image at $x,$y, and with width and height as defined by $w & $h
4696 // note that this will only work with full colour images and makes them jpg images for display
4697 // later versions could present lossless image formats if there is interest.
4699 // there seems to be some problem here in that images that have quality set above 75 do not appear
4700 // not too sure why this is, but in the meantime I have restricted this to 75.
4701 if ($quality>75) {
4703 $quality = 75;
4707 // if the width or height are set to zero, then set the other one based on keeping the image
4708 // height/width ratio the same, if they are both zero, then give up :)
4709 $imageWidth = imagesx($img);
4711 $imageHeight = imagesy($img);
4714 if ($w <= 0 && $h <= 0) {
4716 return;
4719 if ($w == 0) {
4721 $w = $h/$imageHeight*$imageWidth;
4724 if ($h == 0) {
4726 $h = $w*$imageHeight/$imageWidth;
4730 // gotta get the data out of the img..
4732 // so I write to a temp file, and then read it back.. soo ugly, my apologies.
4733 $tmpDir = '/tmp';
4735 $tmpName = tempnam($tmpDir, 'img');
4737 imagejpeg($img, $tmpName, $quality);
4739 //$fp = fopen($tmpName,'rb');
4741 $tmp = get_magic_quotes_runtime();
4743 set_magic_quotes_runtime(0);
4745 if ( ($data = file_get_contents($tmpName)) === false) {
4747 // $fp = @fopen($tmpName,'rb');
4748 // if ($fp){
4749 // $data = '';
4750 // while(!feof($fp)){
4751 // $data .= fread($fp,1024);
4752 // }
4753 // fclose($fp);
4754 $error = 1;
4756 $errormsg = 'trouble opening file';
4759 // $data = fread($fp,filesize($tmpName));
4760 set_magic_quotes_runtime($tmp);
4762 // fclose($fp);
4763 unlink($tmpName);
4765 $this->addJpegImage_common($data, $x, $y, $w, $h, $imageWidth, $imageHeight);
4770 * common code used by the two JPEG adding functions
4772 * @access private
4774 function addJpegImage_common(&$data, $x, $y, $w = 0, $h = 0, $imageWidth, $imageHeight, $channels = 3) {
4776 // note that this function is not to be called externally
4777 // it is just the common code between the GD and the file options
4778 $this->numImages++;
4780 $im = $this->numImages;
4782 $label = 'I'.$im;
4784 $this->numObj++;
4786 $this->o_image($this->numObj, 'new', array('label' => $label, 'data' => &$data, 'iw' => $imageWidth, 'ih' => $imageHeight, 'channels' => $channels));
4789 $this->objects[$this->currentContents]['c'].= "\nq";
4791 $this->objects[$this->currentContents]['c'].= "\n".sprintf('%.3f', $w) ." 0 0 ".sprintf('%.3f', $h) ." ".sprintf('%.3f', $x) ." ".sprintf('%.3f', $y) ." cm";
4793 $this->objects[$this->currentContents]['c'].= "\n/".$label.' Do';
4795 $this->objects[$this->currentContents]['c'].= "\nQ";
4800 * specify where the document should open when it first starts
4802 function openHere($style, $a = 0, $b = 0, $c = 0) {
4804 // this function will open the document at a specified page, in a specified style
4805 // the values for style, and the required paramters are:
4806 // 'XYZ' left, top, zoom
4807 // 'Fit'
4808 // 'FitH' top
4809 // 'FitV' left
4810 // 'FitR' left,bottom,right
4811 // 'FitB'
4812 // 'FitBH' top
4813 // 'FitBV' left
4814 $this->numObj++;
4816 $this->o_destination($this->numObj, 'new', array('page' => $this->currentPage, 'type' => $style, 'p1' => $a, 'p2' => $b, 'p3' => $c));
4818 $id = $this->catalogId;
4820 $this->o_catalog($id, 'openHere', $this->numObj);
4825 * create a labelled destination within the document
4827 function addDestination($label, $style, $a = 0, $b = 0, $c = 0) {
4829 // associates the given label with the destination, it is done this way so that a destination can be specified after
4830 // it has been linked to
4831 // styles are the same as the 'openHere' function
4832 $this->numObj++;
4834 $this->o_destination($this->numObj, 'new', array('page' => $this->currentPage, 'type' => $style, 'p1' => $a, 'p2' => $b, 'p3' => $c));
4836 $id = $this->numObj;
4838 // store the label->idf relationship, note that this means that labels can be used only once
4839 $this->destinations["$label"] = $id;
4844 * define font families, this is used to initialize the font families for the default fonts
4845 * and for the user to add new ones for their fonts. The default bahavious can be overridden should
4846 * that be desired.
4848 function setFontFamily($family, $options = '') {
4850 if (!is_array($options)) {
4852 if ($family == 'init') {
4854 // set the known family groups
4855 // these font families will be used to enable bold and italic markers to be included
4856 // within text streams. html forms will be used... <b></b> <i></i>
4857 $this->fontFamilies['Helvetica.afm'] =
4858 array('b' => 'Helvetica-Bold.afm',
4859 'i' => 'Helvetica-Oblique.afm',
4860 'bi' => 'Helvetica-BoldOblique.afm',
4861 'ib' => 'Helvetica-BoldOblique.afm');
4863 $this->fontFamilies['Courier.afm'] =
4864 array('b' => 'Courier-Bold.afm',
4865 'i' => 'Courier-Oblique.afm',
4866 'bi' => 'Courier-BoldOblique.afm',
4867 'ib' => 'Courier-BoldOblique.afm');
4869 $this->fontFamilies['Times-Roman.afm'] =
4870 array('b' => 'Times-Bold.afm',
4871 'i' => 'Times-Italic.afm',
4872 'bi' => 'Times-BoldItalic.afm',
4873 'ib' => 'Times-BoldItalic.afm');
4875 } else {
4877 // the user is trying to set a font family
4878 // note that this can also be used to set the base ones to something else
4879 if (strlen($family)) {
4881 $this->fontFamilies[$family] = $options;
4888 * used to add messages for use in debugging
4890 function addMessage($message) {
4892 $this->messages.= $message."\n";
4897 * a few functions which should allow the document to be treated transactionally.
4899 function transaction($action) {
4901 switch ($action) {
4903 case 'start':
4905 // store all the data away into the checkpoint variable
4906 $data = get_object_vars($this);
4908 $this->checkpoint = $data;
4910 unset($data);
4912 break;
4914 case 'commit':
4916 if (is_array($this->checkpoint) && isset($this->checkpoint['checkpoint'])) {
4918 $tmp = $this->checkpoint['checkpoint'];
4920 $this->checkpoint = $tmp;
4922 unset($tmp);
4923 } else {
4925 $this->checkpoint = '';
4928 break;
4930 case 'rewind':
4932 // do not destroy the current checkpoint, but move us back to the state then, so that we can try again
4933 if (is_array($this->checkpoint)) {
4935 // can only abort if were inside a checkpoint
4936 $tmp = $this->checkpoint;
4938 foreach ($tmp as $k => $v) {
4940 if ($k != 'checkpoint') {
4942 $this->$k = $v;
4946 unset($tmp);
4949 break;
4951 case 'abort':
4953 if (is_array($this->checkpoint)) {
4955 // can only abort if were inside a checkpoint
4956 $tmp = $this->checkpoint;
4958 foreach ($tmp as $k => $v) {
4960 $this->$k = $v;
4963 unset($tmp);
4966 break;
4970 // end of class