PageRenderTime 80ms CodeModel.GetById 18ms app.highlight 45ms RepoModel.GetById 1ms app.codeStats 1ms

/lib/class.pdf.php

https://github.com/dwagner2301/dompdf
PHP | 4607 lines | 2833 code | 736 blank | 1038 comment | 554 complexity | ed7e198371529c7aa5db09e0d9b921e0 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

   1<?php
   2/**
   3 * A PHP class to provide the basic functionality to create a pdf document without
   4 * any requirement for additional modules.
   5 *
   6 * Extended by Orion Richardson to support Unicode / UTF-8 characters using
   7 * TCPDF and others as a guide.
   8 *
   9 * @author  Wayne Munro <pdf@ros.co.nz>
  10 * @author  Orion Richardson <orionr@yahoo.com>
  11 * @author  Helmut Tischer <htischer@weihenstephan.org>
  12 * @author  Ryan H. Masten <ryan.masten@gmail.com>
  13 * @author  Brian Sweeney <eclecticgeek@gmail.com>
  14 * @author  Fabien MĂŠnager <fabien.menager@gmail.com>
  15 * @license Public Domain http://creativecommons.org/licenses/publicdomain/
  16 * @package Cpdf
  17 */
  18class Cpdf {
  19
  20  /**
  21   * @var integer The current number of pdf objects in the document
  22   */
  23  public $numObj = 0;
  24
  25  /**
  26   * @var array This array contains all of the pdf objects, ready for final assembly
  27   */
  28  public $objects = array();
  29
  30  /**
  31   * @var integer The objectId (number within the objects array) of the document catalog
  32   */
  33  public $catalogId;
  34
  35  /**
  36   * @var array Array carrying information about the fonts that the system currently knows about
  37   * Used to ensure that a font is not loaded twice, among other things
  38   */
  39  public $fonts = array();
  40
  41  /**
  42   * @var string The default font metrics file to use if no other font has been loaded.
  43   * The path to the directory containing the font metrics should be included
  44   */
  45  public $defaultFont = './fonts/Helvetica.afm';
  46
  47  /**
  48   * @string A record of the current font
  49   */
  50  public $currentFont = '';
  51
  52  /**
  53   * @var string The current base font
  54   */
  55  public $currentBaseFont = '';
  56
  57  /**
  58   * @var integer The number of the current font within the font array
  59   */
  60  public $currentFontNum = 0;
  61
  62  /**
  63   * @var integer
  64   */
  65  public $currentNode;
  66
  67  /**
  68   * @var integer Object number of the current page
  69   */
  70  public $currentPage;
  71
  72  /**
  73   * @var integer Object number of the currently active contents block
  74   */
  75  public $currentContents;
  76
  77  /**
  78   * @var integer Number of fonts within the system
  79   */
  80  public $numFonts = 0;
  81
  82  /**
  83   * @var integer Number of graphic state resources used
  84   */
  85  private $numStates = 0;
  86
  87  /**
  88   * @var array Current color for fill operations, defaults to inactive value, 
  89   * all three components should be between 0 and 1 inclusive when active
  90   */
  91  public $currentColor = null;
  92
  93  /**
  94   * @var array Current color for stroke operations (lines etc.)
  95   */
  96  public $currentStrokeColor = null;
  97
  98  /**
  99   * @var string Current style that lines are drawn in
 100   */
 101  public $currentLineStyle = '';
 102
 103  /**
 104   * @var array Current line transparency (partial graphics state)
 105   */
 106  public $currentLineTransparency = array("mode" => "Normal", "opacity" => 1.0);
 107
 108  /**
 109   * array Current fill transparency (partial graphics state)
 110   */
 111  public $currentFillTransparency = array("mode" => "Normal", "opacity" => 1.0);
 112
 113  /**
 114   * @var array An array which is used to save the state of the document, mainly the colors and styles
 115   * it is used to temporarily change to another state, the change back to what it was before
 116   */
 117  public $stateStack = array();
 118
 119  /**
 120   * @var integer Number of elements within the state stack
 121   */
 122  public $nStateStack = 0;
 123
 124  /**
 125   * @var integer Number of page objects within the document
 126   */
 127  public $numPages = 0;
 128
 129  /**
 130   * @var array Object Id storage stack
 131   */
 132  public $stack = array();
 133
 134  /**
 135   * @var integer Number of elements within the object Id storage stack
 136   */
 137  public $nStack = 0;
 138
 139  /**
 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
 142   */
 143  public $looseObjects = array();
 144
 145  /**
 146   * array contains infomation about how the loose objects are to be added to the document
 147   */
 148  public $addLooseObjects = array();
 149
 150  /**
 151   * @var integer The objectId of the information object for the document
 152   * this contains authorship, title etc.
 153   */
 154  public $infoObject = 0;
 155
 156  /**
 157   * @var integer Number of images being tracked within the document
 158   */
 159  public $numImages = 0;
 160
 161  /**
 162   * @var array An array containing options about the document
 163   * it defaults to turning on the compression of the objects
 164   */
 165  public $options = array('compression' => true);
 166
 167  /**
 168   * @var integer The objectId of the first page of the document
 169   */
 170  public $firstPageId;
 171
 172  /**
 173   * @var float 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.
 175   */
 176  public $wordSpaceAdjust = 0;
 177
 178  /**
 179   * @var float Used to track the last used value of the inter-letter spacing, this is so that it is known
 180   * when the spacing is changed.
 181   */
 182  public $charSpaceAdjust = 0;
 183
 184  /**
 185   * @var integer The object Id of the procset object
 186   */
 187  public $procsetObjectId;
 188
 189  /**
 190   * @var array Store the information about the relationship between font families
 191   * this used so that the code knows which font is the bold version of another font, etc.
 192   * the value of this array is initialised in the constuctor function.
 193   */
 194  public $fontFamilies = array();
 195
 196  /**
 197   * @var string Folder for php serialized formats of font metrics files.
 198   * If empty string, use same folder as original metrics files.
 199   * This can be passed in from class creator.
 200   * If this folder does not exist or is not writable, Cpdf will be **much** slower.
 201   * Because of potential trouble with php safe mode, folder cannot be created at runtime.
 202   */
 203  public $fontcache = '';
 204
 205  /**
 206   * @var integer The version of the font metrics cache file.
 207   * This value must be manually incremented whenever the internal font data structure is modified.
 208   */
 209  public $fontcacheVersion = 6;
 210
 211  /**
 212   * @var string Temporary folder.
 213   * If empty string, will attempty system tmp folder.
 214   * This can be passed in from class creator.
 215   * Only used for conversion of gd images to jpeg images.
 216   */
 217  public $tmp = '';
 218
 219  /**
 220   * @var string Track if the current font is bolded or italicised
 221   */
 222  public $currentTextState = '';
 223
 224  /**
 225   * @var string Messages are stored here during processing, these can be selected afterwards to give some useful debug information
 226   */
 227  public $messages = '';
 228
 229  /**
 230   * @var string The ancryption array for the document encryption is stored here
 231   */
 232  public $arc4 = '';
 233
 234  /**
 235   * @var integer The object Id of the encryption information
 236   */
 237  public $arc4_objnum = 0;
 238
 239  /**
 240   * @var string The file identifier, used to uniquely identify a pdf document
 241   */
 242  public $fileIdentifier = '';
 243
 244  /**
 245   * @var boolean A flag to say if a document is to be encrypted or not
 246   */
 247  public $encrypted = false;
 248
 249  /**
 250   * @var string The encryption key for the encryption of all the document content (structure is not encrypted)
 251   */
 252  public $encryptionKey = '';
 253
 254  /**
 255   * @var array Array which forms a stack to keep track of nested callback functions
 256   */
 257  public $callback = array();
 258
 259  /**
 260   * @var integer The number of callback functions in the callback array
 261   */
 262  public $nCallback = 0;
 263
 264  /**
 265   * @var array Store label->id pairs for named destinations, these will be used to replace internal links
 266   * done this way so that destinations can be defined after the location that links to them
 267   */
 268  public $destinations = array();
 269
 270  /**
 271   * @var array Store the stack for the transaction commands, each item in here is a record of the values of all the
 272   * publiciables within the class, so that the user can rollback at will (from each 'start' command)
 273   * note that this includes the objects array, so these can be large.
 274   */
 275  public $checkpoint = '';
 276
 277  /**
 278   * @var array Table of Image origin filenames and image labels which were already added with o_image().
 279   * Allows to merge identical images
 280   */
 281  public $imagelist = array();
 282
 283  /**
 284   * @var boolean Whether the text passed in should be treated as Unicode or just local character set.
 285   */
 286  public $isUnicode = false;
 287
 288  /**
 289   * @var string the JavaScript code of the document
 290   */
 291  public $javascript = '';
 292
 293  /**
 294   * @var boolean whether the compression is possible
 295   */
 296  protected $compressionReady = false;
 297
 298  /**
 299   * @var array Current page size
 300   */
 301  protected $currentPageSize = array("width" => 0, "height" => 0);
 302
 303  /**
 304   * @var array All the chars that will be required in the font subsets
 305   */
 306  protected $stringSubsets = array();
 307
 308  /**
 309   * @var string The target internal encoding
 310   */
 311  static protected $targetEncoding = 'iso-8859-1';
 312
 313  /**
 314   * @var array The list of the core fonts
 315   */
 316  static protected $coreFonts = array(
 317    'courier', 'courier-bold', 'courier-oblique', 'courier-boldoblique',
 318    'helvetica', 'helvetica-bold', 'helvetica-oblique', 'helvetica-boldoblique',
 319    'times-roman', 'times-bold', 'times-italic', 'times-bolditalic',
 320    'symbol', 'zapfdingbats'
 321  );
 322
 323  /**
 324   * Class constructor
 325   * This will start a new document
 326   *
 327   * @param array   $pageSize  Array of 4 numbers, defining the bottom left and upper right corner of the page. first two are normally zero.
 328   * @param boolean $isUnicode Whether text will be treated as Unicode or not.
 329   * @param string  $fontcache The font cache folder
 330   * @param string  $tmp       The temporary folder
 331   */
 332  function __construct($pageSize = array(0, 0, 612, 792), $isUnicode = false, $fontcache = '', $tmp = '') {
 333    $this->isUnicode = $isUnicode;
 334    $this->fontcache = $fontcache;
 335    $this->tmp = $tmp;
 336    $this->newDocument($pageSize);
 337
 338    $this->compressionReady = function_exists('gzcompress');
 339    
 340    if ( in_array('Windows-1252', mb_list_encodings()) ) {
 341      self::$targetEncoding = 'Windows-1252';
 342    }
 343
 344    // also initialize the font families that are known about already
 345    $this->setFontFamily('init');
 346    //  $this->fileIdentifier = md5('xxxxxxxx'.time());
 347  }
 348
 349  /**
 350   * Document object methods (internal use only)
 351   *
 352   * There is about one object method for each type of object in the pdf document
 353   * Each function has the same call list ($id,$action,$options).
 354   * $id = the object ID of the object, or what it is to be if it is being created
 355   * $action = a string specifying the action to be performed, though ALL must support:
 356   *           'new' - create the object with the id $id
 357   *           'out' - produce the output for the pdf object
 358   * $options = optional, a string or array containing the various parameters for the object
 359   *
 360   * These, in conjunction with the output function are the ONLY way for output to be produced
 361   * within the pdf 'file'.
 362   */
 363
 364  /**
 365   * Destination object, used to specify the location for the user to jump to, presently on opening
 366   */
 367  protected function o_destination($id, $action, $options = '') {
 368    if ($action !== 'new') {
 369      $o = &$this->objects[$id];
 370    }
 371
 372    switch ($action) {
 373    case 'new':
 374      $this->objects[$id] = array('t' => 'destination', 'info' => array());
 375      $tmp = '';
 376      switch ($options['type']) {
 377        case 'XYZ':
 378        case 'FitR':
 379          $tmp = ' '.$options['p3'].$tmp;
 380        case 'FitH':
 381        case 'FitV':
 382        case 'FitBH':
 383        case 'FitBV':
 384          $tmp = ' '.$options['p1'].' '.$options['p2'].$tmp;
 385        case 'Fit':
 386        case 'FitB':
 387          $tmp = $options['type'].$tmp;
 388          $this->objects[$id]['info']['string'] = $tmp;
 389          $this->objects[$id]['info']['page'] = $options['page'];
 390      }
 391      break;
 392
 393    case 'out':
 394      $tmp = $o['info'];
 395      $res = "\n$id 0 obj\n".'['.$tmp['page'].' 0 R /'.$tmp['string']."]\nendobj";
 396      return $res;
 397    }
 398  }
 399
 400  /**
 401   * set the viewer preferences
 402   */
 403  protected function o_viewerPreferences($id, $action, $options = '') {
 404    if ($action !== 'new') {
 405      $o = & $this->objects[$id];
 406    }
 407
 408    switch ($action) {
 409    case 'new':
 410      $this->objects[$id] = array('t' => 'viewerPreferences', 'info' => array());
 411      break;
 412
 413    case 'add':
 414      foreach ($options as $k => $v) {
 415        switch ($k) {
 416          case 'HideToolbar':
 417          case 'HideMenubar':
 418          case 'HideWindowUI':
 419          case 'FitWindow':
 420          case 'CenterWindow':
 421          case 'NonFullScreenPageMode':
 422          case 'Direction':
 423            $o['info'][$k] = $v;
 424            break;
 425        }
 426      }
 427      break;
 428
 429    case 'out':
 430      $res = "\n$id 0 obj\n<< ";
 431      foreach ($o['info'] as $k => $v) {
 432        $res.= "\n/$k $v";
 433      }
 434      $res.= "\n>>\n";
 435      return $res;
 436    }
 437  }
 438
 439  /**
 440   * define the document catalog, the overall controller for the document
 441   */
 442  protected function o_catalog($id, $action, $options = '') {
 443    if ($action !== 'new') {
 444      $o = & $this->objects[$id];
 445    }
 446
 447    switch ($action) {
 448      case 'new':
 449        $this->objects[$id] = array('t' => 'catalog', 'info' => array());
 450        $this->catalogId = $id;
 451        break;
 452
 453      case 'outlines':
 454      case 'pages':
 455      case 'openHere':
 456      case 'javascript':
 457        $o['info'][$action] = $options;
 458        break;
 459
 460      case 'viewerPreferences':
 461        if (!isset($o['info']['viewerPreferences'])) {
 462          $this->numObj++;
 463          $this->o_viewerPreferences($this->numObj, 'new');
 464          $o['info']['viewerPreferences'] = $this->numObj;
 465        }
 466
 467        $vp = $o['info']['viewerPreferences'];
 468        $this->o_viewerPreferences($vp, 'add', $options);
 469
 470        break;
 471
 472      case 'out':
 473        $res = "\n$id 0 obj\n<< /Type /Catalog";
 474
 475        foreach ($o['info'] as $k => $v) {
 476          switch ($k) {
 477            case 'outlines':
 478              $res.= "\n/Outlines $v 0 R";
 479              break;
 480
 481            case 'pages':
 482              $res.= "\n/Pages $v 0 R";
 483              break;
 484
 485            case 'viewerPreferences':
 486              $res.= "\n/ViewerPreferences $v 0 R";
 487              break;
 488
 489            case 'openHere':
 490              $res.= "\n/OpenAction $v 0 R";
 491              break;
 492
 493            case 'javascript':
 494              $res.= "\n/Names <</JavaScript $v 0 R>>";
 495              break;
 496          }
 497        }
 498
 499        $res.= " >>\nendobj";
 500        return $res;
 501    }
 502  }
 503
 504  /**
 505   * object which is a parent to the pages in the document
 506   */
 507  protected function o_pages($id, $action, $options = '') {
 508    if ($action !== 'new') {
 509      $o = & $this->objects[$id];
 510    }
 511
 512    switch ($action) {
 513    case 'new':
 514      $this->objects[$id] = array('t' => 'pages', 'info' => array());
 515      $this->o_catalog($this->catalogId, 'pages', $id);
 516      break;
 517
 518    case 'page':
 519      if (!is_array($options)) {
 520        // then it will just be the id of the new page
 521        $o['info']['pages'][] = $options;
 522      }
 523      else {
 524        // then it should be an array having 'id','rid','pos', where rid=the page to which this one will be placed relative
 525        // and pos is either 'before' or 'after', saying where this page will fit.
 526        if (isset($options['id']) && isset($options['rid']) && isset($options['pos'])) {
 527          $i = array_search($options['rid'], $o['info']['pages']);
 528          if (isset($o['info']['pages'][$i]) && $o['info']['pages'][$i] == $options['rid']) {
 529
 530            // then there is a match
 531            // make a space
 532            switch ($options['pos']) {
 533              case 'before':
 534                $k = $i;
 535                break;
 536
 537              case 'after':
 538                $k = $i+1;
 539                break;
 540
 541              default:
 542                $k = -1;
 543                break;
 544            }
 545
 546            if ($k >= 0) {
 547              for ($j = count($o['info']['pages'])-1; $j >= $k; $j--) {
 548                $o['info']['pages'][$j+1] = $o['info']['pages'][$j];
 549              }
 550
 551              $o['info']['pages'][$k] = $options['id'];
 552            }
 553          }
 554        }
 555      }
 556      break;
 557
 558    case 'procset':
 559      $o['info']['procset'] = $options;
 560      break;
 561
 562    case 'mediaBox':
 563      $o['info']['mediaBox'] = $options;
 564      // which should be an array of 4 numbers
 565      $this->currentPageSize = array('width' => $options[2], 'height' => $options[3]);
 566      break;
 567
 568    case 'font':
 569      $o['info']['fonts'][] = array('objNum' => $options['objNum'], 'fontNum' => $options['fontNum']);
 570      break;
 571
 572    case 'extGState':
 573      $o['info']['extGStates'][] = array('objNum' => $options['objNum'],  'stateNum' => $options['stateNum']);
 574      break;
 575
 576    case 'xObject':
 577      $o['info']['xObjects'][] = array('objNum' => $options['objNum'], 'label' => $options['label']);
 578      break;
 579
 580    case 'out':
 581      if (count($o['info']['pages'])) {
 582        $res = "\n$id 0 obj\n<< /Type /Pages\n/Kids [";
 583        foreach ($o['info']['pages'] as $v) {
 584          $res.= "$v 0 R\n";
 585        }
 586
 587        $res.= "]\n/Count ".count($this->objects[$id]['info']['pages']);
 588
 589        if ( (isset($o['info']['fonts']) && count($o['info']['fonts'])) ||
 590              isset($o['info']['procset']) ||
 591              (isset($o['info']['extGStates']) && count($o['info']['extGStates']))) {
 592          $res.= "\n/Resources <<";
 593
 594          if (isset($o['info']['procset'])) {
 595            $res.= "\n/ProcSet ".$o['info']['procset']." 0 R";
 596          }
 597
 598          if (isset($o['info']['fonts']) && count($o['info']['fonts'])) {
 599            $res.= "\n/Font << ";
 600            foreach ($o['info']['fonts'] as $finfo) {
 601              $res.= "\n/F".$finfo['fontNum']." ".$finfo['objNum']." 0 R";
 602            }
 603            $res.= "\n>>";
 604          }
 605
 606          if (isset($o['info']['xObjects']) && count($o['info']['xObjects'])) {
 607            $res.= "\n/XObject << ";
 608            foreach ($o['info']['xObjects'] as $finfo) {
 609              $res.= "\n/".$finfo['label']." ".$finfo['objNum']." 0 R";
 610            }
 611            $res.= "\n>>";
 612          }
 613
 614          if ( isset($o['info']['extGStates']) && count($o['info']['extGStates'])) {
 615            $res.= "\n/ExtGState << ";
 616            foreach ($o['info']['extGStates'] as $gstate) {
 617              $res.= "\n/GS" . $gstate['stateNum'] . " " . $gstate['objNum'] . " 0 R";
 618            }
 619            $res.= "\n>>";
 620          }
 621
 622          $res.= "\n>>";
 623          if (isset($o['info']['mediaBox'])) {
 624            $tmp = $o['info']['mediaBox'];
 625            $res.= "\n/MediaBox [".sprintf('%.3F %.3F %.3F %.3F', $tmp[0], $tmp[1], $tmp[2], $tmp[3]) .']';
 626          }
 627        }
 628
 629        $res.= "\n >>\nendobj";
 630      }
 631      else {
 632        $res = "\n$id 0 obj\n<< /Type /Pages\n/Count 0\n>>\nendobj";
 633      }
 634
 635      return $res;
 636    }
 637  }
 638
 639  /**
 640   * define the outlines in the doc, empty for now
 641   */
 642  protected function o_outlines($id, $action, $options = '') {
 643    if ($action !== 'new') {
 644      $o = &$this->objects[$id];
 645    }
 646
 647    switch ($action) {
 648      case 'new':
 649        $this->objects[$id] = array('t' => 'outlines', 'info' => array('outlines' => array()));
 650        $this->o_catalog($this->catalogId, 'outlines', $id);
 651        break;
 652
 653      case 'outline':
 654        $o['info']['outlines'][] = $options;
 655        break;
 656
 657      case 'out':
 658        if (count($o['info']['outlines'])) {
 659          $res = "\n$id 0 obj\n<< /Type /Outlines /Kids [";
 660          foreach ($o['info']['outlines'] as $v) {
 661            $res.= "$v 0 R ";
 662          }
 663
 664          $res.= "] /Count ".count($o['info']['outlines']) ." >>\nendobj";
 665        } else {
 666          $res = "\n$id 0 obj\n<< /Type /Outlines /Count 0 >>\nendobj";
 667        }
 668
 669        return $res;
 670    }
 671  }
 672
 673  /**
 674   * an object to hold the font description
 675   */
 676  protected function o_font($id, $action, $options = '') {
 677    if ($action !== 'new') {
 678      $o = &$this->objects[$id];
 679    }
 680
 681    switch ($action) {
 682    case 'new':
 683      $this->objects[$id] = array('t' => 'font', 'info' => array('name' => $options['name'], 'fontFileName' => $options['fontFileName'], 'SubType' => 'Type1'));
 684      $fontNum = $this->numFonts;
 685      $this->objects[$id]['info']['fontNum'] = $fontNum;
 686
 687      // deal with the encoding and the differences
 688      if (isset($options['differences'])) {
 689        // then we'll need an encoding dictionary
 690        $this->numObj++;
 691        $this->o_fontEncoding($this->numObj, 'new', $options);
 692        $this->objects[$id]['info']['encodingDictionary'] = $this->numObj;
 693      }
 694      else if (isset($options['encoding'])) {
 695        // we can specify encoding here
 696        switch ($options['encoding']) {
 697          case 'WinAnsiEncoding':
 698          case 'MacRomanEncoding':
 699          case 'MacExpertEncoding':
 700            $this->objects[$id]['info']['encoding'] = $options['encoding'];
 701            break;
 702
 703          case 'none':
 704            break;
 705
 706          default:
 707            $this->objects[$id]['info']['encoding'] = 'WinAnsiEncoding';
 708            break;
 709        }
 710      }
 711      else {
 712        $this->objects[$id]['info']['encoding'] = 'WinAnsiEncoding';
 713      }
 714
 715      if ($this->fonts[$options['fontFileName']]['isUnicode']) {
 716        // For Unicode fonts, we need to incorporate font data into
 717        // sub-sections that are linked from the primary font section.
 718        // Look at o_fontGIDtoCID and o_fontDescendentCID functions
 719        // for more informaiton.
 720        //
 721        // All of this code is adapted from the excellent changes made to
 722        // transform FPDF to TCPDF (http://tcpdf.sourceforge.net/)
 723
 724        $toUnicodeId = ++$this->numObj;
 725        $this->o_contents($toUnicodeId, 'new', 'raw');
 726        $this->objects[$id]['info']['toUnicode'] = $toUnicodeId;
 727
 728        $stream = <<<EOT
 729/CIDInit /ProcSet findresource begin
 73012 dict begin
 731begincmap
 732/CIDSystemInfo
 733<</Registry (Adobe)
 734/Ordering (UCS)
 735/Supplement 0
 736>> def
 737/CMapName /Adobe-Identity-UCS def
 738/CMapType 2 def
 7391 begincodespacerange
 740<0000> <FFFF>
 741endcodespacerange
 7421 beginbfrange
 743<0000> <FFFF> <0000>
 744endbfrange
 745endcmap
 746CMapName currentdict /CMap defineresource pop
 747end
 748end
 749EOT;
 750
 751        $res = "<</Length " . mb_strlen($stream, '8bit') . " >>\n";
 752        $res .= "stream\n" . $stream . "endstream";
 753
 754        $this->objects[$toUnicodeId]['c'] = $res;
 755
 756        $cidFontId = ++$this->numObj;
 757        $this->o_fontDescendentCID($cidFontId, 'new', $options);
 758        $this->objects[$id]['info']['cidFont'] = $cidFontId;
 759      }
 760
 761      // also tell the pages node about the new font
 762      $this->o_pages($this->currentNode, 'font', array('fontNum' => $fontNum, 'objNum' => $id));
 763      break;
 764
 765    case 'add':
 766      foreach ($options as $k => $v) {
 767        switch ($k) {
 768          case 'BaseFont':
 769            $o['info']['name'] = $v;
 770            break;
 771          case 'FirstChar':
 772          case 'LastChar':
 773          case 'Widths':
 774          case 'FontDescriptor':
 775          case 'SubType':
 776            $this->addMessage('o_font '.$k." : ".$v);
 777            $o['info'][$k] = $v;
 778            break;
 779        }
 780      }
 781
 782      // pass values down to descendent font
 783      if (isset($o['info']['cidFont'])) {
 784        $this->o_fontDescendentCID($o['info']['cidFont'], 'add', $options);
 785      }
 786      break;
 787
 788    case 'out':
 789      if ($this->fonts[$this->objects[$id]['info']['fontFileName']]['isUnicode']) {
 790        // For Unicode fonts, we need to incorporate font data into
 791        // sub-sections that are linked from the primary font section.
 792        // Look at o_fontGIDtoCID and o_fontDescendentCID functions
 793        // for more informaiton.
 794        //
 795        // All of this code is adapted from the excellent changes made to
 796        // transform FPDF to TCPDF (http://tcpdf.sourceforge.net/)
 797
 798        $res = "\n$id 0 obj\n<</Type /Font\n/Subtype /Type0\n";
 799        $res.= "/BaseFont /".$o['info']['name']."\n";
 800
 801        // The horizontal identity mapping for 2-byte CIDs; may be used
 802        // with CIDFonts using any Registry, Ordering, and Supplement values.
 803        $res.= "/Encoding /Identity-H\n";
 804        $res.= "/DescendantFonts [".$o['info']['cidFont']." 0 R]\n";
 805        $res.= "/ToUnicode ".$o['info']['toUnicode']." 0 R\n";
 806        $res.= ">>\n";
 807        $res.= "endobj";
 808      } else {
 809        $res = "\n$id 0 obj\n<< /Type /Font\n/Subtype /".$o['info']['SubType']."\n";
 810        $res.= "/Name /F".$o['info']['fontNum']."\n";
 811        $res.= "/BaseFont /".$o['info']['name']."\n";
 812
 813        if (isset($o['info']['encodingDictionary'])) {
 814          // then place a reference to the dictionary
 815          $res.= "/Encoding ".$o['info']['encodingDictionary']." 0 R\n";
 816        } else if (isset($o['info']['encoding'])) {
 817          // use the specified encoding
 818          $res.= "/Encoding /".$o['info']['encoding']."\n";
 819        }
 820
 821        if (isset($o['info']['FirstChar'])) {
 822          $res.= "/FirstChar ".$o['info']['FirstChar']."\n";
 823        }
 824
 825        if (isset($o['info']['LastChar'])) {
 826          $res.= "/LastChar ".$o['info']['LastChar']."\n";
 827        }
 828
 829        if (isset($o['info']['Widths'])) {
 830          $res.= "/Widths ".$o['info']['Widths']." 0 R\n";
 831        }
 832
 833        if (isset($o['info']['FontDescriptor'])) {
 834          $res.= "/FontDescriptor ".$o['info']['FontDescriptor']." 0 R\n";
 835        }
 836
 837        $res.= ">>\n";
 838        $res.= "endobj";
 839      }
 840
 841      return $res;
 842    }
 843  }
 844
 845  /**
 846   * a font descriptor, needed for including additional fonts
 847   */
 848  protected function o_fontDescriptor($id, $action, $options = '') {
 849    if ($action !== 'new') {
 850      $o = & $this->objects[$id];
 851    }
 852
 853    switch ($action) {
 854      case 'new':
 855        $this->objects[$id] = array('t' => 'fontDescriptor', 'info' => $options);
 856        break;
 857
 858      case 'out':
 859        $res = "\n$id 0 obj\n<< /Type /FontDescriptor\n";
 860        foreach ($o['info'] as $label => $value) {
 861          switch ($label) {
 862          case 'Ascent':
 863          case 'CapHeight':
 864          case 'Descent':
 865          case 'Flags':
 866          case 'ItalicAngle':
 867          case 'StemV':
 868          case 'AvgWidth':
 869          case 'Leading':
 870          case 'MaxWidth':
 871          case 'MissingWidth':
 872          case 'StemH':
 873          case 'XHeight':
 874          case 'CharSet':
 875            if (mb_strlen($value, '8bit')) {
 876              $res.= "/$label $value\n";
 877            }
 878
 879            break;
 880          case 'FontFile':
 881          case 'FontFile2':
 882          case 'FontFile3':
 883            $res.= "/$label $value 0 R\n";
 884            break;
 885
 886          case 'FontBBox':
 887            $res.= "/$label [$value[0] $value[1] $value[2] $value[3]]\n";
 888            break;
 889
 890          case 'FontName':
 891            $res.= "/$label /$value\n";
 892            break;
 893          }
 894        }
 895
 896        $res.= ">>\nendobj";
 897
 898        return $res;
 899    }
 900  }
 901
 902  /**
 903   * the font encoding
 904   */
 905  protected function o_fontEncoding($id, $action, $options = '') {
 906    if ($action !== 'new') {
 907      $o = & $this->objects[$id];
 908    }
 909
 910    switch ($action) {
 911    case 'new':
 912      // the options array should contain 'differences' and maybe 'encoding'
 913      $this->objects[$id] = array('t' => 'fontEncoding', 'info' => $options);
 914      break;
 915
 916    case 'out':
 917      $res = "\n$id 0 obj\n<< /Type /Encoding\n";
 918      if (!isset($o['info']['encoding'])) {
 919        $o['info']['encoding'] = 'WinAnsiEncoding';
 920      }
 921
 922      if ($o['info']['encoding'] !== 'none') {
 923        $res.= "/BaseEncoding /".$o['info']['encoding']."\n";
 924      }
 925
 926      $res.= "/Differences \n[";
 927
 928      $onum = -100;
 929
 930      foreach ($o['info']['differences'] as $num => $label) {
 931        if ($num != $onum+1) {
 932          // we cannot make use of consecutive numbering
 933          $res.= "\n$num /$label";
 934        } else {
 935          $res.= " /$label";
 936        }
 937
 938        $onum = $num;
 939      }
 940
 941      $res.= "\n]\n>>\nendobj";
 942      return $res;
 943    }
 944  }
 945
 946  /**
 947   * a descendent cid font, needed for unicode fonts
 948   */
 949  protected function o_fontDescendentCID($id, $action, $options = '') {
 950    if ($action !== 'new') {
 951      $o = & $this->objects[$id];
 952    }
 953
 954    switch ($action) {
 955    case 'new':
 956      $this->objects[$id] = array('t' => 'fontDescendentCID', 'info' => $options);
 957
 958      // we need a CID system info section
 959      $cidSystemInfoId = ++$this->numObj;
 960      $this->o_contents($cidSystemInfoId, 'new', 'raw');
 961      $this->objects[$id]['info']['cidSystemInfo'] = $cidSystemInfoId;
 962      $res = "<</Registry (Adobe)\n"; // A string identifying an issuer of character collections
 963      $res.= "/Ordering (UCS)\n"; // A string that uniquely names a character collection issued by a specific registry
 964      $res.= "/Supplement 0\n"; // The supplement number of the character collection.
 965      $res.= ">>";
 966      $this->objects[$cidSystemInfoId]['c'] = $res;
 967
 968      // and a CID to GID map
 969      $cidToGidMapId = ++$this->numObj;
 970      $this->o_fontGIDtoCIDMap($cidToGidMapId, 'new', $options);
 971      $this->objects[$id]['info']['cidToGidMap'] = $cidToGidMapId;
 972      break;
 973
 974    case 'add':
 975      foreach ($options as $k => $v) {
 976        switch ($k) {
 977        case 'BaseFont':
 978          $o['info']['name'] = $v;
 979          break;
 980
 981        case 'FirstChar':
 982        case 'LastChar':
 983        case 'MissingWidth':
 984        case 'FontDescriptor':
 985        case 'SubType':
 986          $this->addMessage("o_fontDescendentCID $k : $v");
 987          $o['info'][$k] = $v;
 988          break;
 989        }
 990      }
 991
 992      // pass values down to cid to gid map
 993      $this->o_fontGIDtoCIDMap($o['info']['cidToGidMap'], 'add', $options);
 994      break;
 995
 996    case 'out':
 997      $res = "\n$id 0 obj\n";
 998      $res.= "<</Type /Font\n";
 999      $res.= "/Subtype /CIDFontType2\n";
1000      $res.= "/BaseFont /".$o['info']['name']."\n";
1001      $res.= "/CIDSystemInfo ".$o['info']['cidSystemInfo']." 0 R\n";
1002//      if (isset($o['info']['FirstChar'])) {
1003//        $res.= "/FirstChar ".$o['info']['FirstChar']."\n";
1004//      }
1005
1006//      if (isset($o['info']['LastChar'])) {
1007//        $res.= "/LastChar ".$o['info']['LastChar']."\n";
1008//      }
1009      if (isset($o['info']['FontDescriptor'])) {
1010        $res.= "/FontDescriptor ".$o['info']['FontDescriptor']." 0 R\n";
1011      }
1012
1013      if (isset($o['info']['MissingWidth'])) {
1014        $res.= "/DW ".$o['info']['MissingWidth']."\n";
1015      }
1016
1017      if (isset($o['info']['fontFileName']) && isset($this->fonts[$o['info']['fontFileName']]['CIDWidths'])) {
1018        $cid_widths = &$this->fonts[$o['info']['fontFileName']]['CIDWidths'];
1019        $w = '';
1020        foreach ($cid_widths as $cid => $width) {
1021          $w .= "$cid [$width] ";
1022        }
1023        $res.= "/W [$w]\n";
1024      }
1025
1026      $res.= "/CIDToGIDMap ".$o['info']['cidToGidMap']." 0 R\n";
1027      $res.= ">>\n";
1028      $res.= "endobj";
1029
1030      return $res;
1031    }
1032  }
1033
1034  /**
1035   * a font glyph to character map, needed for unicode fonts
1036   */
1037  protected function o_fontGIDtoCIDMap($id, $action, $options = '') {
1038    if ($action !== 'new') {
1039      $o = & $this->objects[$id];
1040    }
1041
1042    switch ($action) {
1043    case 'new':
1044      $this->objects[$id] = array('t' => 'fontGIDtoCIDMap', 'info' => $options);
1045      break;
1046
1047    case 'out':
1048      $res = "\n$id 0 obj\n";
1049      $fontFileName = $o['info']['fontFileName'];
1050      $tmp = $this->fonts[$fontFileName]['CIDtoGID'] = base64_decode($this->fonts[$fontFileName]['CIDtoGID']);
1051
1052      $compressed = isset($this->fonts[$fontFileName]['CIDtoGID_Compressed']) &&
1053                    $this->fonts[$fontFileName]['CIDtoGID_Compressed'];
1054
1055      if (!$compressed && isset($o['raw'])) {
1056        $res.= $tmp;
1057      } else {
1058        $res.= "<<";
1059
1060        if (!$compressed && $this->compressionReady && $this->options['compression']) {
1061          // then implement ZLIB based compression on this content stream
1062          $compressed = true;
1063          $tmp = gzcompress($tmp, 6);
1064        }
1065        if ($compressed) {
1066          $res.= "\n/Filter /FlateDecode";
1067        }
1068
1069        $res.= "\n/Length ".mb_strlen($tmp, '8bit') .">>\nstream\n$tmp\nendstream";
1070      }
1071
1072      $res.= "\nendobj";
1073      return $res;
1074    }
1075  }
1076
1077  /**
1078   * the document procset, solves some problems with printing to old PS printers
1079   */
1080  protected function o_procset($id, $action, $options = '') {
1081    if ($action !== 'new') {
1082      $o = & $this->objects[$id];
1083    }
1084
1085    switch ($action) {
1086      case 'new':
1087        $this->objects[$id] = array('t' => 'procset', 'info' => array('PDF' => 1, 'Text' => 1));
1088        $this->o_pages($this->currentNode, 'procset', $id);
1089        $this->procsetObjectId = $id;
1090        break;
1091
1092      case 'add':
1093        // this is to add new items to the procset list, despite the fact that this is considered
1094        // obselete, the items are required for printing to some postscript printers
1095        switch ($options) {
1096        case 'ImageB':
1097        case 'ImageC':
1098        case 'ImageI':
1099          $o['info'][$options] = 1;
1100          break;
1101        }
1102        break;
1103
1104      case 'out':
1105        $res = "\n$id 0 obj\n[";
1106        foreach ($o['info'] as $label => $val) {
1107          $res.= "/$label ";
1108        }
1109        $res.= "]\nendobj";
1110        return $res;
1111    }
1112  }
1113
1114  /**
1115   * define the document information
1116   */
1117  protected function o_info($id, $action, $options = '') {
1118    if ($action !== 'new') {
1119      $o = & $this->objects[$id];
1120    }
1121
1122    switch ($action) {
1123      case 'new':
1124        $this->infoObject = $id;
1125        $date = 'D:'.@date('Ymd');
1126        $this->objects[$id] = array('t' => 'info', 'info' => array('Creator' => 'R and OS php pdf writer, http://www.ros.co.nz', 'CreationDate' => $date));
1127        break;
1128      case 'Title':
1129      case 'Author':
1130      case 'Subject':
1131      case 'Keywords':
1132      case 'Creator':
1133      case 'Producer':
1134      case 'CreationDate':
1135      case 'ModDate':
1136      case 'Trapped':
1137        $o['info'][$action] = $options;
1138        break;
1139
1140      case 'out':
1141        if ($this->encrypted) {
1142          $this->encryptInit($id);
1143        }
1144
1145        $res = "\n$id 0 obj\n<<\n";
1146        foreach ($o['info'] as $k => $v) {
1147          $res.= "/$k (";
1148
1149          if ($this->encrypted) {
1150            $v = $this->ARC4($v);
1151          }
1152
1153          // dates must be outputted as-is, without Unicode transformations
1154          elseif (!in_array($k, array('CreationDate', 'ModDate'))){
1155            $v = $this->filterText($v);
1156          }
1157
1158          $res.= $v;
1159          $res.= ")\n";
1160        }
1161
1162        $res.= ">>\nendobj";
1163        return $res;
1164    }
1165  }
1166
1167  /**
1168   * an action object, used to link to URLS initially
1169   */
1170  protected function o_action($id, $action, $options = '') {
1171    if ($action !== 'new') {
1172      $o = & $this->objects[$id];
1173    }
1174
1175    switch ($action) {
1176      case 'new':
1177        if (is_array($options)) {
1178          $this->objects[$id] = array('t' => 'action', 'info' => $options, 'type' => $options['type']);
1179        } else {
1180          // then assume a URI action
1181          $this->objects[$id] = array('t' => 'action', 'info' => $options, 'type' => 'URI');
1182        }
1183        break;
1184
1185      case 'out':
1186        if ($this->encrypted) {
1187          $this->encryptInit($id);
1188        }
1189
1190        $res = "\n$id 0 obj\n<< /Type /Action";
1191        switch ($o['type']) {
1192          case 'ilink':
1193            if (!isset($this->destinations[(string)$o['info']['label']])) break;
1194
1195            // there will be an 'label' setting, this is the name of the destination
1196            $res.= "\n/S /GoTo\n/D ".$this->destinations[(string)$o['info']['label']]." 0 R";
1197            break;
1198
1199          case 'URI':
1200            $res.= "\n/S /URI\n/URI (";
1201            if ($this->encrypted) {
1202              $res.= $this->filterText($this->ARC4($o['info']), true, false);
1203            } else {
1204              $res.= $this->filterText($o['info'], true, false);
1205            }
1206
1207            $res.= ")";
1208            break;
1209        }
1210
1211        $res.= "\n>>\nendobj";
1212        return $res;
1213    }
1214  }
1215
1216  /**
1217   * an annotation object, this will add an annotation to the current page.
1218   * initially will support just link annotations
1219   */
1220  protected function o_annotation($id, $action, $options = '') {
1221    if ($action !== 'new') {
1222      $o = & $this->objects[$id];
1223    }
1224
1225    switch ($action) {
1226      case 'new':
1227        // add the annotation to the current page
1228        $pageId = $this->currentPage;
1229        $this->o_page($pageId, 'annot', $id);
1230
1231        // and add the action object which is going to be required
1232        switch ($options['type']) {
1233          case 'link':
1234            $this->objects[$id] = array('t' => 'annotation', 'info' => $options);
1235            $this->numObj++;
1236            $this->o_action($this->numObj, 'new', $options['url']);
1237            $this->objects[$id]['info']['actionId'] = $this->numObj;
1238            break;
1239
1240          case 'ilink':
1241            // this is to a named internal link
1242            $label = $options['label'];
1243            $this->objects[$id] = array('t' => 'annotation', 'info' => $options);
1244            $this->numObj++;
1245            $this->o_action($this->numObj, 'new', array('type' => 'ilink', 'label' => $label));
1246            $this->objects[$id]['info']['actionId'] = $this->numObj;
1247            break;
1248        }
1249        break;
1250
1251      case 'out':
1252        $res = "\n$id 0 obj\n<< /Type /Annot";
1253        switch ($o['info']['type']) {
1254          case 'link':
1255          case 'ilink':
1256            $res.= "\n/Subtype /Link";
1257            break;
1258        }
1259        $res.= "\n/A ".$o['info']['actionId']." 0 R";
1260        $res.= "\n/Border [0 0 0]";
1261        $res.= "\n/H /I";
1262        $res.= "\n/Rect [ ";
1263
1264        foreach ($o['info']['rect'] as $v) {
1265          $res.= sprintf("%.4F ", $v);
1266        }
1267
1268        $res.= "]";
1269        $res.= "\n>>\nendobj";
1270        return $res;
1271    }
1272  }
1273
1274  /**
1275   * a page object, it also creates a contents object to hold its contents
1276   */
1277  protected function o_page($id, $action, $options = '') {
1278    if ($action !== 'new') {
1279      $o = & $this->objects[$id];
1280    }
1281
1282    switch ($action) {
1283    case 'new':
1284      $this->numPages++;
1285      $this->objects[$id] = array('t' => 'page', 'info' => array('parent' => $this->currentNode, 'pageNum' => $this->numPages));
1286
1287      if (is_array($options)) {
1288        // then this must be a page insertion, array should contain 'rid','pos'=[before|after]
1289        $options['id'] = $id;
1290        $this->o_pages($this->currentNode, 'page', $options);
1291      } else {
1292        $this->o_pages($this->currentNode, 'page', $id);
1293      }
1294
1295      $this->currentPage = $id;
1296      //make a contents object to go with this page
1297      $this->numObj++;
1298      $this->o_contents($this->numObj, 'new', $id);
1299      $this->currentContents = $this->numObj;
1300      $this->objects[$id]['info']['contents'] = array();
1301      $this->objects[$id]['info']['contents'][] = $this->numObj;
1302
1303      $match = ($this->numPages%2 ? 'odd' : 'even');
1304      foreach ($this->addLooseObjects as $oId => $target) {
1305        if ($target === 'all' || $match === $target) {
1306          $this->objects[$id]['info']['contents'][] = $oId;
1307        }
1308      }
1309      break;
1310
1311    case 'content':
1312      $o['info']['contents'][] = $options;
1313      break;
1314
1315    case 'annot':
1316      // add an annotation to this page
1317      if (!isset($o['info']['annot'])) {
1318        $o['info']['annot'] = array();
1319      }
1320
1321      // $options should contain the id of the annotation dictionary
1322      $o['info']['annot'][] = $options;
1323      break;
1324
1325    case 'out':
1326      $res = "\n$id 0 obj\n<< /Type /Page";
1327      $res.= "\n/Parent ".$o['info']['parent']." 0 R";
1328
1329      if (isset($o['info']['annot'])) {
1330        $res.= "\n/Annots [";
1331        foreach ($o['info']['annot'] as $aId) {
1332          $res.= " $aId 0 R";
1333        }
1334        $res.= " ]";
1335      }
1336
1337      $count = count($o['info']['contents']);
1338      if ($count == 1) {
1339        $res.= "\n/Contents ".$o['info']['contents'][0]." 0 R";
1340      } else if ($count > 1) {
1341        $res.= "\n/Contents [\n";
1342
1343        // reverse the page contents so added objects are below normal content
1344        //foreach (array_reverse($o['info']['contents']) as $cId) {
1345        // Back to normal now that I've got transparency working --Benj
1346        foreach ($o['info']['contents'] as $cId) {
1347          $res.= "$cId 0 R\n";
1348        }
1349        $res.= "]";
1350      }
1351
1352      $res.= "\n>>\nendobj";
1353      return $res;
1354    }
1355  }
1356
1357  /**
1358   * the contents objects hold all of the content which appears on pages
1359   */
1360  protected function o_contents($id, $action, $options = '') {
1361    if ($action !== 'new') {
1362      $o = & $this->objects[$id];
1363    }
1364
1365    switch ($action) {
1366    case 'new':
1367      $this->objects[$id] = array('t' => 'contents', 'c' => '', 'info' => array());
1368      if (mb_strlen($options, '8bit') && intval($options)) {
1369        // then this contents is the primary for a page
1370        $this->objects[$id]['onPage'] = $options;
1371      } else if ($options === 'raw') {
1372        // then this page contains some other type of system object
1373        $this->objects[$id]['raw'] = 1;
1374      }
1375      break;
1376
1377    case 'add':
1378      // add more options to the decleration
1379      foreach ($options as $k => $v) {
1380        $o['info'][$k] = $v;
1381      }
1382
1383    case 'out':
1384      $tmp = $o['c'];
1385      $res = "\n$id 0 obj\n";
1386
1387      if (isset($this->objects[$id]['raw'])) {
1388        $res.= $tmp;
1389      } else {
1390        $res.= "<<";
1391        if ($this->compressionReady && $this->options['compression']) {
1392          // then implement ZLIB based compression on this content stream
1393          $res.= " /Filter /FlateDecode";
1394          $tmp = gzcompress($tmp, 6);
1395        }
1396
1397        if ($this->encrypted) {
1398          $this->encryptInit($id);
1399          $tmp = $this->ARC4($tmp);
1400        }
1401
1402        foreach ($o['info'] as $k => $v) {
1403          $res.= "\n/$k $v";
1404        }
1405
1406        $res.= "\n/Length ".mb_strlen($tmp, '8bit') ." >>\nstream\n$tmp\nendstream";
1407      }
1408
1409      $res.= "\nendobj";
1410      return $res;
1411    }
1412  }
1413
1414  protected function o_embedjs($id, $action) {
1415    if ($action !== 'new') {
1416      $o = & $this->objects[$id];
1417    }
1418
1419    switch ($action) {
1420    case 'new':
1421      $this->objects[$id] = array('t' => 'embedjs', 'info' => array(
1422        'Names' => '[(EmbeddedJS) '.($id+1).' 0 R]'
1423      ));
1424      break;
1425
1426    case 'out':
1427      $res = "\n$id 0 obj\n<< ";
1428      foreach ($o['info'] as $k => $v) {
1429        $res.= "\n/$k $v";
1430      }
1431      $res.= "\n>>\nendobj";
1432      return $res;
1433    }
1434  }
1435
1436  protected function o_javascript($id, $action, $code = '') {
1437    if ($action !== 'new') {
1438      $o = & $this->objects[$id];
1439    }
1440
1441    switch ($action) {
1442    case 'new':
1443      $this->objects[$id] = array('t' => 'javascript', 'info' => array(
1444        'S' => '/JavaScript',
1445        'JS' => '('.$this->filterText($code).')',
1446      ));
1447      break;
1448
1449    case 'out':
1450      $res = "\n$id 0 obj\n<< ";
1451      foreach ($o['info'] as $k => $v) {
1452        $res.= "\n/$k $v";
1453      }
1454      $res.= "\n>>\nendobj";
1455      return $res;
1456    }
1457  }
1458
1459  /**
1460   * an image object, will be an XObject in the document, includes description and data
1461   */
1462  protected function o_image($id, $action, $options = '') {
1463    if ($action !== 'new') {
1464      $o = & $this->objects[$id];
1465    }
1466
1467    switch ($action) {
1468    case 'new':
1469      // make the new object
1470      $this->objects[$id] = array('t' => 'image', 'data' => &$options['data'], 'info' => array());
1471
1472      $info =& $this->objects[$id]['info'];
1473
1474      $info['Type'] = '/XObject';
1475      $info['Subtype'] = '/Image';
1476      $info['Width'] = $options['iw'];
1477      $info['Height'] = $options['ih'];
1478
1479      if (isset($options['masked']) && $options['masked']) {
1480        $info['SMask'] = ($this->numObj-1).' 0 R';
1481      }
1482
1483      if (!isset($options['type']) || $options['type'] === 'jpg') {
1484        if (!isset($options['channels'])) {
1485          $options['channels'] = 3;
1486        }
1487
1488        switch ($options['channels']) {
1489          case  1: $info['ColorSpace'] = '/DeviceGray'; break;
1490          case  4: $info['ColorSpace'] = '/DeviceCMYK'; break;
1491          default: $info['ColorSpace'] = '/DeviceRGB'; break;
1492        }
1493
1494        if ($info['ColorSpace'] === '/DeviceCMYK') {
1495          $info['Decode'] = '[1 0 1 0 1 0 1 0]';
1496        }
1497
1498        $info['Filter'] = '/DCTDecode';
1499        $info['BitsPerComponent'] = 8;
1500      } 
1501
1502      else if ($options['type'] === 'png') {
1503        $info['Filter'] = '/FlateDecode';
1504        $info['DecodeParms'] = '<< /Predictor 15 /Colors '.$options['ncolor'].' /Columns '.$options['iw'].' /BitsPerComponent '.$options['bitsPerComponent'].'>>';
1505
1506        if ($options['isMask']) {
1507          $info['ColorSpace'] = '/DeviceGray';
1508        }
1509        else {
1510          if (mb_strlen($options['pdata'], '8bit')) {
1511            $tmp = ' [ /Indexed /DeviceRGB '.(mb_strlen($options['pdata'], '8bit') /3-1) .' ';
1512            $this->numObj++;
1513            $this->o_contents($this->numObj, 'new');
1514            $this->objects[$this->numObj]['c'] = $options['pdata'];
1515            $tmp.= $this->numObj.' 0 R';
1516            $tmp.= ' ]';
1517            $info['ColorSpace'] = $tmp;
1518
1519            if (isset($options['transparency'])) {
1520              $transparency = $options['transparency'];
1521              switch ($transparency['type']) {
1522              case 'indexed':
1523                $tmp = ' [ '.$transparency['data'].' '.$transparency['data'].'] ';
1524                $info['Mask'] = $tmp;
1525                break;
1526
1527              case 'color-key':
1528                $tmp = ' [ '.
1529                  $transparency['r'] . ' ' . $transparency['r'] .
1530                  $transparency['g'] . ' ' . $transparency['g'] .
1531                  $transparency['b'] . ' ' . $transparency['b'] .
1532                  ' ] ';
1533                $info['Mask'] = $tmp;
1534                break;
1535              }
1536            }
1537          } else {
1538            if (isset($options['transparency'])) {
1539              $transparency = $options['transparency'];
1540
1541              switch ($transparency['type']) {
1542              case 'indexed':
1543                $tmp = ' [ '.$transparency['data'].' '.$transparency['data'].'] ';
1544                $info['Mask'] = $tmp;
1545                break;
1546
1547              case 'color-key':
1548                $tmp = ' [ '.
1549                  $transparency['r'] . ' ' . $transparency['r'] . ' ' .
1550                  $transparency['g'] . ' ' . $transparency['g'] . ' ' .
1551                  $transparency['b'] . ' ' . $transparency['b'] .
1552                  ' ] ';
1553                $info['Mask'] = $tmp;
1554                break;
1555              }
1556            }
1557            $info['ColorSpace'] = '/'.$options['color'];
1558          }
1559        }
1560
1561        $info['BitsPerComponent'] = $options['bitsPerComponent'];
1562      }
1563
1564      // assign it a place in the named resource dictionary as an external object, according to
1565      // the label passed in with it.
1566      $this->o_pages($this->currentNode, 'xObject', array('label' => $options['label'], 'objNum' => $id));
1567
1568      // also make sure that we have the right procset object for it.
1569      $this->o_procset($this->procsetObjectId, 'add', 'ImageC');
1570      break;
1571
1572    case 'out':
1573      $tmp = &$o['data'];
1574      $res = "\n$id 0 obj\n<<";
1575
1576      foreach ($o['info'] as $k => $v) {
1577        $res.= "\n/$k $v";
1578      }
1579
1580      if ($this->encrypted) {
1581        $this->encryptInit($id);
1582        $tmp = $this->ARC4($tmp);
1583      }
1584
1585      $res.= "\n/Length ".mb_strlen($tmp, '8bit') .">>\nstream\n$tmp\nendstream\nendobj";
1586
1587      return $res;
1588    }
1589  }
1590
1591  /**
1592   * graphics state object
1593   */
1594  protected function o_extGState($id, $action, $options = "") {
1595    static $valid_params = array("LW",  "LC",  "LC",  "LJ",  "ML",
1596                                   "D",  "RI",  "OP",  "op",  "OPM",
1597                                   "Font",  "BG",  "BG2",  "UCR",
1598                                   "TR",  "TR2",  "HT",  "FL",
1599                                   "SM",  "SA",  "BM",  "SMask",
1600                                   "CA",  "ca",  "AIS",  "TK");
1601
1602    if ($action !== "new") {
1603      $o = & $this->objects[$id];
1604    }
1605
1606    switch ($action) {
1607    case "new":
1608      $this->objects[$id] = array('t' => 'extGState', 'info' => $options);
1609
1610      // Tell the pages about the new resource
1611      $this->numStates++;
1612      $this->o_pages($this->currentNode, 'extGState', array("objNum" => $id, "stateNum" => $this->numStates));
1613      break;
1614
1615    case "out":
1616      $res = "\n$id 0 obj\n<< /Type /ExtGState\n";
1617
1618      foreach ($o["info"] as $k => $v) {
1619        if ( !in_array($k, $valid_params))
1620          continue;
1621        $res.= "/$k $v\n";
1622      }
1623
1624      $res.= ">>\nendobj";
1625      return $res;
1626    }
1627  }
1628
1629  /**
1630   * encryption object.
1631   */
1632  protected function o_encryption($id, $action, $options = '') {
1633    if ($action !== 'new') {
1634      $o = & $this->objects[$id];
1635    }
1636
1637    switch ($action) {
1638    case 'new':
1639      // make the new object
1640      $this->objects[$id] = array('t' => 'encryption', 'info' => $options);
1641      $this->arc4_objnum = $id;
1642
1643      // figure out the additional paramaters required
1644      $pad = chr(0x28) .chr(0xBF) .chr(0x4E) .chr(0x5E) .chr(0x4E) .chr(0x75) .chr(0x8A) .chr(0x41)
1645             .chr(0x64) .chr(0x00) .chr(0x4E) .chr(0x56) .chr(0xFF) .chr(0xFA) .chr(0x01) .chr(0x08)
1646             .chr(0x2E) .chr(0x2E) .chr(0x00) .chr(0xB6) .chr(0xD0) .chr(0x68) .chr(0x3E) .chr(0x80)
1647             .chr(0x2F) .chr(0x0C) .chr(0xA9) .chr(0xFE) .chr(0x64) .chr(0x53) .chr(0x69) .chr(0x7A);
1648
1649      $len = mb_strlen($options['owner'], '8bit');
1650
1651      if ($len > 32) {
1652        $owner = substr($options['owner'], 0, 32);
1653      } else if ($len < 32) {
1654        $owner = $options['owner'].substr($pad, 0, 32-$len);
1655      } else {
1656        $owner = $options['owner'];
1657      }
1658
1659      $len = mb_strlen($options['user'], '8bit');
1660      if ($len > 32) {
1661        $user = substr($options['user'], 0, 32);
1662      } else if ($len < 32) {
1663        $user = $options['user'].substr($pad, 0, 32-$len);
1664      } else {
1665        $user = $options['user'];
1666      }
1667
1668      $tmp = $this->md5_16($owner);
1669      $okey = substr($tmp, 0, 5);
1670      $this->ARC4_init($okey);
1671      $ovalue = $this->ARC4($user);
1672      $this->objects[$id]['info']['O'] = $ovalue;
1673
1674      // now make the u value, phew.
1675      $tmp = $this->md5_16($user.$ovalue.chr($options['p']) .chr(255) .chr(255) .chr(255) .$this->fileIdentifier);
1676
1677      $ukey = substr($tmp, 0, 5);
1678      $this->ARC4_init($ukey);
1679      $this->encryptionKey = $ukey;
1680      $this->encrypted = true;
1681      $uvalue = $this->ARC4($pad);
1682      $this->objects[$id]['info']['U'] = $uvalue;
1683      $this->encryptionKey = $ukey;
1684      // initialize the arc4 array
1685      break;
1686
1687    case 'out':
1688      $res = "\n$id 0 o…

Large files files are truncated, but you can click here to view the full file