Location: PHPKode > projects > crVCL PHP Framework > pdf.lib.php
<?PHP

/*

The contents of this file are subject to the Mozilla Public License
Version 1.1 (the "License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.mozilla.org/MPL/MPL-1.1.html or see MPL-1.1.txt in directory "license"

Software distributed under the License is distributed on an "AS IS" basis,
WITHOUT WARRANTY OF ANY KIND, either expressed or implied. See the License for
the specific language governing rights and limitations under the License.

The Initial Developers of the Original Code are: 
Copyright (c) 2003-2012, CR-Solutions (http://www.cr-solutions.net), Ricardo Cescon
All Rights Reserved.

Contributor(s): Ricardo Cescon

crVCL PHP Framework Version 2.4
*/

///////////////////////////////////////////////////////////////////////////////////////
// Special Thanks to Nicola Asuni - http://www.tcpdf.org
///////////////////////////////////////////////////////////////////////////////////////


############################################################
if(!defined("PDF_LIB")){
   define ("PDF_LIB", 1);
############################################################


if(!isset($GLOBALS["CRVCL"]["TCPDF_VERSION"]) || !is_dir($GLOBALS["CRVCL"]["PATH"]."/external/tcpdf/".$GLOBALS["CRVCL"]["TCPDF_VERSION"])){
   $GLOBALS["CRVCL"]["TCPDF_VERSION"] = "4.9.018";   
}

//-------------------------------------------------------------------------------------------------------------------------------------         
//-------------------------------------------------------------------------------------------------------------------------------------         
/**
 * disable the original config of TCPDF (tcpdf_config.php)
 *
 */
define('K_TCPDF_EXTERNAL_CONFIG', 1); 
/**
 * (overwritten by crVCL)
 *
 */
define ('K_PATH_MAIN', $GLOBALS["CRVCL"]["PATH"]."/external/tcpdf/".$GLOBALS["CRVCL"]["TCPDF_VERSION"]."/");

/**
 * (overwritten by crVCL)
 *
 */
define ('K_PATH_URL', $GLOBALS["CRVCL"]["URL"]."/external/tcpdf/".$GLOBALS["CRVCL"]["TCPDF_VERSION"]."/");

/**
 * path for PDF fonts
 * use K_PATH_MAIN.'fonts/old/' for old non-UTF8 fonts
 */
define ('K_PATH_FONTS', K_PATH_MAIN.'fonts/');

/**
 * cache directory for temporary files (full path)
 */
define ('K_PATH_CACHE', K_PATH_MAIN.'cache/');

/**
 * cache directory for temporary files (url path)
 */
define ('K_PATH_URL_CACHE', K_PATH_URL.'cache/');

/**
 *images directory
 */
define ('K_PATH_IMAGES', K_PATH_MAIN.'images/');

/**
 * blank image
 */
define ('K_BLANK_IMAGE', K_PATH_IMAGES.'_blank.png');

/**
 * page format (not required, only for the examples and overwritten by crVCL)
 */
define ('PDF_PAGE_FORMAT', 'A4');

/**
 * page orientation (P=portrait, L=landscape) - (not required, only for the examples and overwritten by crVCL)
 */
define ('PDF_PAGE_ORIENTATION', 'P');

/**
 * document creator (not required, only for the examples and overwritten by crVCL)
 */
define ('PDF_CREATOR', 'TCPDF');

/**
 * document author (not required, only for the examples and overwritten by crVCL)
 */
define ('PDF_AUTHOR', 'TCPDF');

/**
 * header title (not required, only for the examples and overwritten by crVCL)
 */
define ('PDF_HEADER_TITLE', '');

/**
 * header description string (not required, only for the examples and overwritten by crVCL)
 */
define ('PDF_HEADER_STRING', "");

/**
 * image logo (not required, only for the examples and overwritten by crVCL)
 */
define ('PDF_HEADER_LOGO', '');

/**
 * header logo image width [mm] (not required, only for the examples and overwritten by crVCL)
 */
define ('PDF_HEADER_LOGO_WIDTH', 30);

/**
 *  document unit of measure [pt=point, mm=millimeter, cm=centimeter, in=inch] (not required, only for the examples and overwritten by crVCL)
 */
define ('PDF_UNIT', 'mm');

/**
 * header margin (not required, only for the examples and overwritten by crVCL)
 */
define ('PDF_MARGIN_HEADER', 5);

/**
 * footer margin (not required, only for the examples and overwritten by crVCL)
 */
define ('PDF_MARGIN_FOOTER', 10); 

/**
 * top margin (not required, only for the examples and overwritten by crVCL)
 */
define ('PDF_MARGIN_TOP', 27);

/**
 * bottom margin (not required, only for the examples and overwritten by crVCL)
 */
define ('PDF_MARGIN_BOTTOM', 25);

/**
 * left margin (not required, only for the examples and overwritten by crVCL)
 */
define ('PDF_MARGIN_LEFT', 15);

/**
 * right margin (not required, only for the examples and overwritten by crVCL)
 */
define ('PDF_MARGIN_RIGHT', 15);

/**
 * default main font name (not required, only for the examples and overwritten by crVCL)
 */
define ('PDF_FONT_NAME_MAIN', 'helvetica');

/**
 * default main font size (not required, only for the examples and overwritten by crVCL)
 */
define ('PDF_FONT_SIZE_MAIN', 10);

/**
 * default data font name (not required, only for the examples and overwritten by crVCL)
 */
define ('PDF_FONT_NAME_DATA', 'helvetica');

/**
 * default data font size (not required, only for the examples and overwritten by crVCL)
 */
define ('PDF_FONT_SIZE_DATA', 8);

/**
 * default monospaced font name (not required, only for the examples and overwritten by crVCL)
 */
define ('PDF_FONT_MONOSPACED', 'courier');

/**
 * ratio used to adjust the conversion of pixels to user units (not required, only for the examples and overwritten by crVCL)
 */
define ('PDF_IMAGE_SCALE_RATIO', 1);

/**
 * magnification factor for titles 
 */
define('HEAD_MAGNIFICATION', 1.1);

/**
 * height of cell repect font height 
 */
define('K_CELL_HEIGHT_RATIO', 1.25);

/**
 * title magnification respect main font size (not required, only for the examples and overwritten by crVCL)
 */
define('K_TITLE_MAGNIFICATION', 1.3);

/**
 * reduction factor for small font 
 */
define('K_SMALL_RATIO', 2/3);

/**
 * set to true to enable the special procedure used to avoid the overlappind of symbols on Thai language 
 */
define('K_THAI_TOPCHARS', true);

/**
 * if true allows to call TCPDF methods using HTML syntax
 * IMPORTANT: For security reason, disable this feature if you are printing user HTML content.	  
 */
define('K_TCPDF_CALLS_IN_HTML', true);



//-------------------------------------------------------------------------------------------------------------------------------------         
//-------------------------------------------------------------------------------------------------------------------------------------         

require($GLOBALS["CRVCL"]["PATH"]."/external/tcpdf/".$GLOBALS["CRVCL"]["TCPDF_VERSION"]."/tcpdf.php");


if(defined('PDF_PRODUCER')){
   throw new Exception("crVCL implementation error, please commented out the define of PDF_PRODUCER in the tcpdf.php of the original code");
}


/**
 * Native PDF library based and derived on TCPDF of Nicola Asuni (http://www.tecnick.com)<br>tanti saluti alla Italia and special thanks to Olivier Plathey (http://www.fpdf.de/)<br><br>$pdf = new PDF();<br>$pdf->setPDFVersion('1.3');<br>$pdf->addPage();<br><br><br>for extended/full unicode support see the readme in the font directory and the variable $GLOBALS["CRVCL"]["FONT_EXTENSION_PATH"] in the config.inc.php<br><br>// standard<br>$pdf->setFont('Arial', '', 10);<br><br>// extended (koi8-ru, koi8-r, iso8859-15, iso8859-10, iso8859-9, iso8859-8, iso8859-7, iso8859-6, iso8859-5, iso8859-4, iso8859-3, iso8859-2, iso8859-1)<br>$pdf->setFont("TimesUnicode", '', 9);<br><br>// full unicode support (but create big pdf files)<br>$pdf->setFont("ArialUnicodeMS");<br><br>$pdf->text(10, 10, 'Test PDF'.U_EURO);<br>$pdf->output('./test.pdf');<br><br>for more unicode fonts see the fonts directory of the framework<br><br>
 */
class PDF extends TCPDF{      
   private $m_last_used_font = array();
//-------------------------------------------------------------------------------------------------------------------------------------         
   /**
   * init pdf object
   *
   * @param string $orientation page orientation. Possible values are (case insensitive):<ul><li>P or Portrait (default)</li><li>L or Landscape</li></ul>
   * @param string $unit User measure unit. Possible values are:<ul><li>pt: point</li><li>mm: millimeter (default)</li><li>cm: centimeter</li><li>in: inch</li></ul><br />A point equals 1/72 of inch, that is to say about 0.35 mm (an inch being 2.54 cm). This is a very common unit in typography; font sizes are expressed in that unit.
   * @param mixed $format The format used for pages. It can be either one of the following values (case insensitive) or a custom format in the form of a two-element array containing the width and the height (expressed in the unit given by unit).<ul><li>4A0</li><li>2A0</li><li>A0</li><li>A1</li><li>A2</li><li>A3</li><li>A4 (default)</li><li>A5</li><li>A6</li><li>A7</li><li>A8</li><li>A9</li><li>A10</li><li>B0</li><li>B1</li><li>B2</li><li>B3</li><li>B4</li><li>B5</li><li>B6</li><li>B7</li><li>B8</li><li>B9</li><li>B10</li><li>C0</li><li>C1</li><li>C2</li><li>C3</li><li>C4</li><li>C5</li><li>C6</li><li>C7</li><li>C8</li><li>C9</li><li>C10</li><li>RA0</li><li>RA1</li><li>RA2</li><li>RA3</li><li>RA4</li><li>SRA0</li><li>SRA1</li><li>SRA2</li><li>SRA3</li><li>SRA4</li><li>LETTER</li><li>LEGAL</li><li>EXECUTIVE</li><li>FOLIO</li></ul>
   * @param boolean $unicode TRUE means that the input text is unicode (default = true)   
   * @param string $encoding charset encoding; default is UTF-8
   * @param boolean $diskcache if TRUE reduce the RAM memory usage by caching temporary data on filesystem (slower).
   * @return PDF
   */   
   function __construct($orientation='P', $unit='mm', $format='A4', $unicode=true, $encoding='UTF-8', $diskcache=false){                         
       $pdfcreator = "crVCL PHP Framework Version " . CRVCL_VERSION . " (www.cr-solutions.net) / TCPDF ".$GLOBALS["CRVCL"]["TCPDF_VERSION"]." (http://www.tcpdf.org)";
       if(!isset($GLOBALS["CRVCL"]["EXCLUSIVE_LICENSE"])){$GLOBALS["CRVCL"]["EXCLUSIVE_LICENSE"]=false;}
       if($GLOBALS["CRVCL"]["EXCLUSIVE_LICENSE"] == false){ // only allowed to set true for Initial Developers or Contributors with exclusive license
	       define('PDF_PRODUCER', $pdfcreator);
       }else{
          if(!isset($GLOBALS["CRVCL"]["PDF_CREATOR"])){$GLOBALS["CRVCL"]["PDF_CREATOR"]=$pdfcreator;}          
          define('PDF_PRODUCER', $GLOBALS["CRVCL"]["PDF_CREATOR"]);
       }
      
      
       return parent::__construct($orientation,$unit,$format,$unicode,$encoding,$diskcache);       
   }
//-------------------------------------------------------------------------------------------------------------------------------------            
   private function _nbLines($w, $txt)
   {
       return $this->getNumLines($txt, $w);
       // replaced by Nicolas method to support all unicode chars
       /*
       if($this->isunicode){
          $txt = utf8_fix($txt);
       }   
       
       
       //Computes the number of lines a MultiCell of width w will take
       $cw=&$this->CurrentFont['cw'];
       if($w==0)
           $w=$this->w-$this->rMargin-$this->x;
       $wmax=($w-2*$this->cMargin)*$this->FontSize/1000;       
              
       
       $s=str_replace("\r", '', $txt);
       $nb=strlen($s);
       if($nb>0 and $s[$nb-1]=="\n")
           $nb--;
       $sep=-1;
       $i=0;
       $j=0;
       $l=0;
       $nl=1;
       while($i<$nb)
       {
           $c=$s[$i];
           if($c=="\n")
           {
               $i++;
               $sep=-1;
               $j=$i;
               $l=0;
               $nl++;
               continue;
           }
           if($c==' ')
               $sep=$i;
           $l+=$cw[$c];
           
           //if($l>$wmax)    // not allow chars smaller 32 and count it
           if(is_int($c) && $c >= 32 && $l>$wmax)
           {
               if($sep==-1)
               {
                   if($i==$j)
                       $i++;
               }
               else
                   $i=$sep+1;
               $sep=-1;
               $j=$i;
               $l=0;
               $nl++;
           }
           else
               $i++;
       }
       return $nl;
       */
   }
//-------------------------------------------------------------------------------------------------------------------------------------            
   private function _checkPageBreak($h)
   {
      return $this->checkPageBreak($h);
      // replaced by Nicolas method to support all unicode chars
      /*
      
       //If the height h would cause an overflow, add a new page immediately
       if($this->getY()+$h>$this->PageBreakTrigger)
          $this->addPage($this->CurOrientation);
      */     
   }   
//-------------------------------------------------------------------------------------------------------------------------------------         
   /**
    * create a row of a table<br><br>sample:$pdf->TableRow(array($desc, number_format($price, 2, ',', '')) ,array("R","R"), array(165, 25), 1);
    *
    * @param array $columns
    * @param array $aligns
    * @param array $widths
    * @param int $border
    * @param int $rowspacing
    */
   public function TableRow($columns, $aligns, $widths, $border=0, $rowspacing=5){
                           
      //Calculate the height of the row
      $nb=0;
      for($i=0; $i<count($columns); $i++)
         $nb=max($nb, $this->_nbLines($widths[$i], $columns[$i]));
      $h=5*$nb;
      //Issue a page break first if needed
      $this->_checkPageBreak($h);
      //Draw the cells of the row
      for($i=0;$i<count($columns);$i++)
      {
          $txt = $columns[$i];
          $w=$widths[$i];
          $a=isset($aligns[$i]) ? $aligns[$i] : 'L';
          //Save the current position
          $x=$this->GetX();
          $y=$this->GetY();

          //Print the image
          if(strpos(strtolower($txt),"img:")!==false){
             $settings = explode(";",$txt);

             $img = "";
             $breaks = "";
             while(list($key, $val) = each($settings)){
                if(strtolower(substr($val,0,4))=="img:"){
                   $img = substr($val,4);
                }
                if(strtolower(substr($val,0,7))=="breaks:"){
                   $breaks = substr($val,7);
                }
             }

             $this->Image($img,$x,$y,$w,$h);
             $txt = $breaks;
          }
          //Draw the border
          if($border != 0){
            $this->Rect($x, $y, $w, $h);
          }
          //Print the text
          $this->MultiCell($w, $rowspacing, $txt, 0, $a);
          

          //Put the position to the right of the cell
          $this->SetXY($x+$w, $y);
      }
      //Go to the next line
      $this->Ln($h);
   }   
//-------------------------------------------------------------------------------------------------------------------------------------         
   /**
	* Sets the font used to print character strings. For full unicode support, see also the documentation of the constructor
	*
	* @param string $family Family font. It can be either a name defined by AddFont() or one of the standard Type1 families (case insensitive):<ul><li>times (Times-Roman)</li><li>timesb (Times-Bold)</li><li>timesi (Times-Italic)</li><li>timesbi (Times-BoldItalic)</li><li>helvetica (Helvetica)</li><li>helveticab (Helvetica-Bold)</li><li>helveticai (Helvetica-Oblique)</li><li>helveticabi (Helvetica-BoldOblique)</li><li>courier (Courier)</li><li>courierb (Courier-Bold)</li><li>courieri (Courier-Oblique)</li><li>courierbi (Courier-BoldOblique)</li><li>symbol (Symbol)</li><li>zapfdingbats (ZapfDingbats)</li></ul> It is also possible to pass an empty string. In that case, the current family is retained.
	* @param string $style Font style. Possible values are (case insensitive):<ul><li>empty string: regular</li><li>B: bold</li><li>I: italic</li><li>U: underline</li><li>D: line trough</li></ul> or any combination. The default value is regular. Bold and italic styles do not apply to Symbol and ZapfDingbats basic fonts or other fonts when not defined.
	* @param float $size Font size in points. The default value is the current size. If no size has been specified since the beginning of the document, the value taken is 12
	* @param string $fontfile The font definition file. By default, the name is built from the family and style, in lower case with no spaces.
	*/
	public function SetFont($family, $style='', $size=0, $fontfile=''){	   
	   if(parent::empty_string($family)){
	      return; // fix inheritance problems and problems called from external code
	   }
	   if(parent::empty_string($fontfile)){	  
	      // check for external font file
   	   $GLOBALS["CRVCL"]["FONT_EXTENSION_PATH"] = fixpath($GLOBALS["CRVCL"]["FONT_EXTENSION_PATH"]);   	   
   	   if(file_exists($GLOBALS["CRVCL"]["FONT_EXTENSION_PATH"]."/".strtolower($family).".z") && file_exists($GLOBALS["CRVCL"]["FONT_EXTENSION_PATH"]."/".strtolower($family).".php")){
   	      $fontfile = $GLOBALS["CRVCL"]["FONT_EXTENSION_PATH"]."/".strtolower($family).".php";   	      
   	   
   	   // check for internal font file
   	   }else if(file_exists(K_PATH_FONTS.strtolower($family).".php")){
   	      $fontfile = K_PATH_FONTS.strtolower($family).".php";   	      
   	   }else{
   	      return; // fix inheritance problems and problems called from external code
   	   }
	   }
	   
	   return parent::SetFont($family, $style, $size, $fontfile);
	}
//-------------------------------------------------------------------------------------------------------------------------------------         
   /**
	* Imports a TrueType, Type1, core, or CID0 font and makes it available. For full unicode support, see also the documentation of the constructor
	* 	
	* @param string $family Font family. The name can be chosen arbitrarily. If it is a standard family name, it will override the corresponding font.
	* @param string $style Font style. Possible values are (case insensitive):<ul><li>empty string: regular (default)</li><li>B: bold</li><li>I: italic</li><li>BI or IB: bold italic</li></ul>
	* @param string $fontfile The font definition file. By default, the name is built from the family and style, in lower case with no spaces.
	* @return array containing the font data, or false in case of error.
	*/
	public function AddFont($family, $style='', $fontfile=''){	   
	   if(parent::empty_string($family)){
	      return; // fix inheritance problems and problems called from external code	      
	   }
	   if(parent::empty_string($fontfile)){
	      // check for external font file
   	   $GLOBALS["CRVCL"]["FONT_EXTENSION_PATH"] = fixpath($GLOBALS["CRVCL"]["FONT_EXTENSION_PATH"]);
   	   if(file_exists($GLOBALS["CRVCL"]["FONT_EXTENSION_PATH"]."/".strtolower($family).".z") && file_exists($GLOBALS["CRVCL"]["FONT_EXTENSION_PATH"]."/".strtolower($family).".php")){
   	      $fontfile = $GLOBALS["CRVCL"]["FONT_EXTENSION_PATH"]."/".strtolower($family).".php";   	      
   	   
   	   // check for internal font file
   	   }else if(file_exists(K_PATH_FONTS.strtolower($family).".php")){
   	      $fontfile = K_PATH_FONTS.strtolower($family).".php";   	      
   	   }else{
   	      return; // fix inheritance problems and problems called from external code
   	   }
	   }
	   
      return parent::AddFont($family, $style, $fontfile);
	}

//-------------------------------------------------------------------------------------------------------------------------------------         		
   /**
	* This method is automatically called in case of fatal error and throw an exception	
	* 
	* @param string $msg 		
	*/

	public function Error($msg){			      
		$this->_destroy(true);
		throw new Exception($msg);		
	}

	
//-------------------------------------------------------------------------------------------------------------------------------------         		
}
############################################################
}
############################################################
?>
Return current item: crVCL PHP Framework