<?php

  define('FPDF_FONTPATH','modules/EcmDocumentTemplates/html2fpdf-3.0.2b/font/');  
  require_once('html2fpdf-3.0.2b/html2fpdf.php');
  
  class DocumentPDF extends HTML2FPDF {
    
    private $blnShowHeader = true;
    private $blnShowFooter = true;
    
    var $iconvFrom = "UTF-8";
    var $iconvTo = "ISO-8859-2";
    
    public function DocumentPDF($orientation='P',$unit='mm',$format='A4') {
      parent::HTML2FPDF($orientation,$unit,$format);
      $this->AddFont('arialpl', '', 'arial.php');
      $this->AddFont('arialpl', 'I', 'ariali.php');
      $this->AddFont('arialpl', 'B', 'arialbd.php');
      $this->AddFont('arialpl', 'BI', 'arialbi.php');
      $this->SetFont('arialpl', '', 9);

      $this->rMargin = 15;
      $this->lMargin = 25;
      $this->bMargin = 19;
      $this->SetTopMargin(10);
      $this->SetAutoPageBreak(true,$this->bMargin+$this->tMarign+5);
	  $this->pgwidth = $this->fw - $this->lMargin - $this->rMargin ;
      $this->ZoomMode = 73;
      
    }

    public function enableHeader() { $this->blnShowHeader = true; }
    public function disableHeader() { $this->blnShowHeader = false; }
    public function enableFooter() { $this->blnShowFooter = true; }
    public function disableFooter() { $this->blnShowFooter = false; }
    

    function iconvArray($from,$to,$arr) {
      if(is_array($arr)) {
        foreach($arr as $key => $value)
          $arr[$key] = iconvArray($from,$to,$value);
      } else $arr = iconv($from,$to,$arr);
      return $arr;
    } 

    /*
    function Cell($w,$h=0,$txt='',$border=0,$ln=0,$align='',$fill=0,$link='',$currentx=0) {
      return parent::Cell($w,$h=0,iconv("UTF-8","ISO-8859-2",$txt),$border,$ln,$align,$fill,$link,$currentx);
    }
    function MultiCell($w,$h,$txt,$border=0,$align='J',$fill=0,$link='') {
      return parent::MultiCell($w,$h,iconv("UTF-8","ISO-8859-2",$txt),$border,$align,$fill,$link);
    }
    */
  
    public function Header($content='') {}
    public function Footer() {}
    function Main() {}

    function DrawTable($table, $headers = null, $ctm = 1, $cbm = 1, $cth = 4) {
      if(is_array($headers) && count($headers) > 0) {
	  	$arr = array();
		foreach($headers as $key => $value) $arr[] = $table[$value];
		$headers = $arr;
	  }
	  foreach($table as $row)
        $this->DrawTableRow($row, $headers, $ctm, $cbm, $cth);
    }



function CalcCell($cell) {
  $cell_tmp = array();
	$cw=&$this->CurrentFont['cw'];
	$w = $cell['width']*(($this->fw-$this->lMargin-$this->rMargin)/100);
	$wmax=($w-2*$this->cMargin)*1000/$this->FontSize;
	$s=str_replace("\r",'',$cell['value']);
	$nb=strlen($s);
	if($nb>0 and $s[$nb-1]=="\n")	$nb--;
	$sep=-1;
	$i=0;
	$j=0;
	$l=0;
	$ns=0;
	$nl=1;
  $rc = 0;
	while($i<$nb) 
  {
		//Get next character
		$c=$s{$i};
		if($c=="\n")
		{
			//Explicit line break
      //$rc++;
	    $cell_tmp[] = substr($s,$j,$i-$j); //$j=$i; $rc = 0;//add next full page
			$i++;
			$sep=-1;
			$j=$i;
			$l=0;
			$ns=0;
			$nl++;
			continue;
		}
		if($c==' ')
		{
			$sep=$i;
			$ls=$l;
			$ns++;
		}
		$l+=$cw[$c];
		if($l>$wmax)
		{
			//Automatic line break
			if($sep==-1)
			{
				if($i==$j) $i++;
				$rc++;
	      $cell_tmp[] = substr($s,$j,$i-$j); //$j=$i; $rc = 0;//add next full page

			}
			else
			{
        $rc++;
	      $cell_tmp[] = substr($s,$j,$sep-$j); //$j=$i; $rc = 0;//add next full page
				$i=$sep+1;
			}
			$sep=-1;
			$j=$i;
			$l=0;
			$ns=0;
			$nl++;
	    //$cell_tmp[] = substr($s,$j,$i-$j); //$j=$i; $rc = 0;//add next full page
		}
		else $i++;
	}
	//Last chunk
	//$this->Cell($w,$h,substr($s,$j,$i-$j),$b,2,$align,$fill,$link);
	$cell_tmp[] = substr($s,$j,$i-$j);
	//$this->x=$this->lMargin;
	
	return $cell_tmp;
}

	function getScaledImageHeight($file, $w) {
		$pos=strrpos($file,'.');
		if(!$pos)	$this->Error('Image file has no extension and no type was specified: '.$file);
		$type=substr($file,$pos+1);
		
		if($type=='jpg' or $type=='jpeg')	$info=$this->_parsejpg($file);
		elseif($type=='png') $info=$this->_parsepng($file);
		elseif($type=='gif') $info=$this->_parsegif($file); 
		
		if(!isset($info)) return 0;
		
		$h=$w*$info['h']/$info['w'];
		
		return $h;
	}

    function DrawTableRow($row, $headers = null, $ctm = 1, $cbm = 1, $cth = 4) {
      $lm = $this->lMargin;
      $rm = $this->rMargin;
      $fw = $this->fw-$lm-$rm;
      $pr = $fw/100;
      
	  $img_result_bottom = 0;
      //$ctm = 1; //cell top margin
      //$cbm = 1; //cell bottom margin
      //$cth = 4; //cell text height
      
    //prepare row to draw
      $row_tmp = array();
	    $maxRows = 0;
      foreach($row as $key => $cell) {
//	      $row_tmp[$key] = $this->CalcCell($row[$key],$this->fh-($this->GetY()+$ctm)-($this->bMargin+$cbm),$ctm,$cbm);
        $this->SetFont( 
                        (isset($cell['font-family'])?$cell['font-family']:'arialpl'),
                        (isset($cell['font-style'])?$cell['font-style']:''),
                        (isset($cell['font-size'])?$cell['font-size']:8)
                      );
		  if(!isset($cell['image_path'])) {
	      	$row_tmp[$key] = $this->CalcCell($row[$key]);
            if(count($row_tmp[$key]) > $maxRows) $maxRows = count($row_tmp[$key]);
          } else {
		  	$row_tmp[$key] = '';
		  }	
		  
	  }
      

	  $img_path_bool = true;
	  $img_height = 0;
      for($i=0;$i<$maxRows;$i++) {
        $row_pre[$i] = $row;
        foreach($row_tmp as $key => $cell) {
		  if(isset($row_pre[$i][$key]['image_path'])) {
		  	if($row_pre[$i][$key]['image_path'] != '' && $img_path_bool == true) { 
				if(file_exists($row_pre[$i][$key]['image_path'])) {
					$img_path_ = $row_pre[$i][$key]['image_path']; 
					$img_path_bool = false; 
					$img_height = $this->getScaledImageHeight($row_pre[$i][$key]['image_path'], $row_pre[$i][$key]['width']*$pr);	
				}
			} else $img_path_ = 'none';
		  	$row_pre[$i][$key]['image_path'] = $img_path_;
		  }
          $row_pre[$i][$key]['value'] = isset($cell[$i])?$cell[$i]:'';
		}    
      }
	  if(($this->GetY() + $img_height) > $this->getBreakLine()) { 
	  	  $this->AddPage(); 
		  if(is_array($headers) && count($headers) > 0) $this->DrawTable($headers); 
	  }
	  
	  if($img_height != 0) {
	  	$rows_height = count($row_pre) * $cth;
	  	if($img_height > $rows_height) $cbm = $cbm + $img_height - $rows_height; else { $img_height = 0; } 
	  }
$rows_height = count($row_pre) * ($cth + $ctm + $cbm); 
if($this->GetY()+$rows_height > $this->fh-$this->bMargin) { 
  $this->AddPage(); 
  $this->Ln(0); 
  $img_result_bottom = 0;
  //table headers
  if(is_array($headers) && count($headers) > 0) $this->DrawTable($headers);
  $this->Ln(0);  
  }
for($rows=0; $rows<count($row_pre); $rows++) {
      $row = $row_pre[$rows];
    //row draw
      $maxy = 0;
      //drawing a row
	 if($this->GetY()+$cth*5 > $this->fh-$this->bMargin) { 
 		$this->AddPage(); 
 		$mar = null;
		if ($this->getX()!=$this->lMargin)	 	
			$mar = $this->getX();
		
		$this->Ln(0, $mar); 
		$new_x = $this->getX();
		$img_result_bottom = 0;

		//table headers
		if(is_array($headers) && count($headers) > 0) $this->DrawTable($headers);
		$this->Ln(0, $mar);	 
	 }     
	 /*if($this->GetY()>  130){
	 	$this->AddPage(); 
	 } */ 
      $cp1 = $this->page;
      $cp2 = $this->page;
      $cy = $this->GetY();
      $sx = $this->GetX(); //start X
      $sy = $this->GetY(); //start Y
      $cx = $sx;

	  $cell_countner = 0;
      foreach($row as $key => $cell) {
      
      //set font
        $this->SetFont( 
                        (isset($cell['font-family'])?$cell['font-family']:'arialpl'),
                        (isset($cell['font-style'])?$cell['font-style']:''),
                        (isset($cell['font-size'])?$cell['font-size']:8)
                      );
      
      //set text color    
        $this->SetTextColor((isset($cell['color'])?$cell['color']:'0,0,0'));
      
      //set fill color
        if(isset($cell['background']))
          $this->SetFillColor($cell['background'][0],$cell['background'][1],$cell['background'][2]);
        else
          $this->SetFillColor(255,255,255);
          
      //draw top cell margin
        if($rows == 0) {
          //if($this->GetY()+$cth*2 > $this->fh-$this->bMargin) { $this->AddPage(); $this->Ln(0); }
          $xtmp = $this->GetX();
          $ytmp = $this->GetY();
          $this->Cell($cell['width']*$pr,$ctm,'',($cell['border']==1?'LTR':''),0,0,1);
          $this->SetXY($xtmp,$ytmp+$ctm);
          $cell['border'].='T';
        }
        if($rows == $maxRows-1) {
          if($this->GetY()+$cth*2 > $this->fh-$this->bMargin) { 
		  	$this->AddPage(); 
			$this->Ln(0);		  
			//table headers
			$img_result_bottom = 0;
			$this->Ln(0);	 
		  }
          $xtmp = $this->GetX();
          $ytmp = $this->GetY();
          $this->SetXY($xtmp,$ytmp+$cth);
		  if(isset($cell['image_path'])) {
		  } else
          	$this->Cell($cell['width']*$pr,$cbm,'',($cell['border']==1?'LBR':''),0,0,1);
          $this->SetXY($xtmp,$ytmp);
          //$this->Rect($this->GetX(),$this->GetY()+$cth,$cell['width']*$pr,$cbm,'DF');
        }
      //draw cell text
	    //if($this->GetY()+$cth*2 > $this->fh-$this->bMargin) { $this->AddPage(); $this->Ln(0); }
        if(isset($cell['image_path']) && $cell['image_path'] != '') {
			if(file_exists($cell['image_path'])) {
				$img_y = $this->GetY();
				$img_result = $this->Image($cell['image_path'],$this->GetX(),$img_y,$cell['width']*$pr,0);
				$img_result_bottom = $img_y + $img_result['HEIGHT'];		
				$this->SetXY($this->GetX(), $img_y);
				//if($img_y + $img_result['HEIGHT'] > $maxy) $maxy = $img_y + $img_result['HEIGHT'];
			}
			$c_tmp=$cell['width']*$pr;
			
		} else 
			$this->Cell($c_tmp=$cell['width']*$pr,$cth,$cell['value'],($cell['border']==1?'LR':''),0,$cell['align'],1);
		
        $this->SetXY($this->GetX(),$this->GetY()+$cth);
      //draw bottom cell margin
        if($rows == $maxRows-1) $this->SetXY($this->GetX(),$this->GetY()+$cbm);
      
      //set end of text  
        if(($this->GetY()) > $maxy) $maxy = $this->GetY();
        
        if($this->page > $cp1) { $cy = $this->tMargin; $img_result_bottom = 0; $cp1=$this->page; }  
        $this->SetXY($cx+=$c_tmp,$cy);   
      }   

      $this->SetXY($sx,$maxy); 
}
if(isset($img_result_bottom) && $img_result_bottom > $this->GetY()) $this->SetXY($this->GetX(), $img_result_bottom);
    }
    
    function DrawHorizontalDottedLine($x1,$x2,$y,$r) {
      for($i=$x1,$j=0;$i<$x2-$r;$i+=$r,$j++) {
        if($j%2) $this->_out('1 1 1 RG'); else $this->_out($this->DrawColor);
        $this->Line($i,$y,$i+$r,$y);
      }
      $this->_out($this->DrawColor);
    }

  }
  
?>