Outputting in Landscape with FPDF

smetterd
smetterd used Ask the Experts™
on
I switch orientation to 'L' (see line 13) but script still outputs Portrait and I can't understand why. Thanks in advance for your help.
<?php
error_reporting(-1);
require('../../../dwzExport/fpdf/fpdf.php');
require('htmlparser.inc');

class PDF_HTML_Table extends FPDF
{
var $B;
var $I;
var $U;
var $HREF;

function PDF($orientation='L', $unit='mm', $format='A4')
{
	//Call parent constructor
	$this->FPDF($orientation,$unit,$format);
	//Initialization
	$this->B=0;
	$this->I=0;
	$this->U=0;
	$this->HREF='';
}

function WriteHTML2($html)
{
	//HTML parser
	$html=str_replace("\n",' ',$html);
	$a=preg_split('/<(.*)>/U',$html,-1,PREG_SPLIT_DELIM_CAPTURE);
	foreach($a as $i=>$e)
	{
		if($i%2==0)
		{
			//Text
			if($this->HREF)
				$this->PutLink($this->HREF,$e);
			else
				$this->Write(5,$e);
		}
		else
		{
			//Tag
			if($e[0]=='/')
				$this->CloseTag(strtoupper(substr($e,1)));
			else
			{
				//Extract attributes
				$a2=explode(' ',$e);
				$tag=strtoupper(array_shift($a2));
				$attr=array();
				foreach($a2 as $v)
				{
					if(preg_match('/([^=]*)=["\']?([^"\']*)/',$v,$a3))
						$attr[strtoupper($a3[1])]=$a3[2];
				}
				$this->OpenTag($tag,$attr);
			}
		}
	}
}

function OpenTag($tag, $attr)
{
	//Opening tag
	if($tag=='B' || $tag=='I' || $tag=='U')
		$this->SetStyle($tag,true);
	if($tag=='A')
		$this->HREF=$attr['HREF'];
	if($tag=='BR')
		$this->Ln(5);
	if($tag=='P')
		$this->Ln(10);
}

function CloseTag($tag)
{
	//Closing tag
	if($tag=='B' || $tag=='I' || $tag=='U')
		$this->SetStyle($tag,false);
	if($tag=='A')
		$this->HREF='';
	if($tag=='P')
		$this->Ln(10);
}

function SetStyle($tag, $enable)
{
	//Modify style and select corresponding font
	$this->$tag+=($enable ? 1 : -1);
	$style='';
	foreach(array('B','I','U') as $s)
		if($this->$s>0)
			$style.=$s;
	$this->SetFont('',$style);
}

function PutLink($URL, $txt)
{
	//Put a hyperlink
	$this->SetTextColor(0,0,255);
	$this->SetStyle('U',true);
	$this->Write(5,$txt,$URL);
	$this->SetStyle('U',false);
	$this->SetTextColor(0);
}

function WriteTable($data, $w)
{
	$this->SetLineWidth(.3);
	$this->SetFillColor(255,255,255);
	$this->SetTextColor(0);
	$this->SetFont('');
	foreach($data as $row)
	{
		$nb=0;
		for($i=0;$i<count($row);$i++)
			$nb=max($nb,$this->NbLines($w[$i],trim($row[$i])));
		$h=5*$nb;
		$this->CheckPageBreak($h);
		for($i=0;$i<count($row);$i++)
		{
			$x=$this->GetX();
			$y=$this->GetY();
			$this->Rect($x,$y,$w[$i],$h);
			$this->MultiCell($w[$i],5,trim($row[$i]),0,'C');
			//Put the position to the right of the cell
			$this->SetXY($x+$w[$i],$y);					
		}
		$this->Ln($h);

	}
}

function NbLines($w, $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)*1000/$this->FontSize;
	$s=str_replace("\r",'',$txt);
	$nb=strlen($s);
	if($nb>0 && $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)
		{
			if($sep==-1)
			{
				if($i==$j)
					$i++;
			}
			else
				$i=$sep+1;
			$sep=-1;
			$j=$i;
			$l=0;
			$nl++;
		}
		else
			$i++;
	}
	return $nl;
}

function CheckPageBreak($h)
{
	//If the height h would cause an overflow, add a new page immediately
	if($this->GetY()+$h>$this->PageBreakTrigger)
		$this->AddPage($this->CurOrientation);
}

function ReplaceHTML($html)
{
	$html = str_replace( '<li>', "\n<br> - " , $html );
	$html = str_replace( '<LI>', "\n - " , $html );
	$html = str_replace( '</ul>', "\n\n" , $html );
	$html = str_replace( '<strong>', "<b>" , $html );
	$html = str_replace( '</strong>', "</b>" , $html );
	$html = str_replace( '&#160;', "\n" , $html );
	$html = str_replace( '&nbsp;', " " , $html );
	$html = str_replace( '&quot;', "\"" , $html ); 
	$html = str_replace( '&#39;', "'" , $html );
	return $html;
}

function ParseTable($Table)
{
	$_var='';
	$htmlText = $Table;
	$parser = new HtmlParser ($htmlText);
	while ($parser->parse())
	{
		if(strtolower($parser->iNodeName)=='table')
		{
			if($parser->iNodeType == NODE_TYPE_ENDELEMENT)
				$_var .='/::';
			else
				$_var .='::';
		}

		if(strtolower($parser->iNodeName)=='tr')
		{
			if($parser->iNodeType == NODE_TYPE_ENDELEMENT)
				$_var .='!-:'; //opening row
			else
				$_var .=':-!'; //closing row
		}
		if(strtolower($parser->iNodeName)=='td' && $parser->iNodeType == NODE_TYPE_ENDELEMENT)
		{
			$_var .='#,#';
		}
		if ($parser->iNodeName=='Text' && isset($parser->iNodeValue))
		{
			$_var .= $parser->iNodeValue;
		}
	}
	$elems = explode(':-!',str_replace('/','',str_replace('::','',str_replace('!-:','',$_var)))); //opening row
	foreach($elems as $key=>$value)
	{
		if(trim($value)!='')
		{
			$elems2 = explode('#,#',$value);
			array_pop($elems2);
			$data[] = $elems2;
		}
	}
	return $data;
}

function WriteHTML($html)
{
	$html = $this->ReplaceHTML($html);
	//Search for a table
	$start = strpos(strtolower($html),'<table');
	$end = strpos(strtolower($html),'</table');
	if($start!==false && $end!==false)
	{
		$this->WriteHTML2(substr($html,0,$start).'<BR>');

		$tableVar = substr($html,$start,$end-$start);
		$tableData = $this->ParseTable($tableVar);
		for($i=1;$i<=count($tableData[0]);$i++)
		{
			if($this->CurOrientation=='L')
				$w[] = abs(120/(count($tableData[0])-1))+24;
			else
				$w[] = abs(120/(count($tableData[0])-1))+5;
		}
		$this->WriteTable($tableData,$w);

		$this->WriteHTML2(substr($html,$end+8,strlen($html)-1).'<BR>');
	}
	else
	{
		$this->WriteHTML2($html);
	}
}

}

Open in new window

Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Without seeing other code, here is my thought.

When you call PDF_HTML_Table::PDF you're giving a value (ie: PDF_HTML_Table::PDF('P'); ). The $orientation you have set will only fire if the value is not submitted with the function call.

Author

Commented:
Sorry, here's the code that outputs the PDF...
<?php ini_set('error_reporting', E_ALL);
require_once('../../../Connections/connElearn.php'); 
if (!function_exists("GetSQLValueString")) {
function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
{
  if (PHP_VERSION < 6) {
    $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
  }

  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;    
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}
}

mysql_select_db($database_connElearn, $connElearn);
$query_rs = "SELECT * FROM apps_pdas WHERE locked > 0 LIMIT 1";
$rs = mysql_query($query_rs, $connElearn) or die(mysql_error());
$row_rs = mysql_fetch_assoc($rs);
$totalRows_rs = mysql_num_rows($rs);

require_once('html_table.php');
$htmlTable='<table cellpadding="2" cellspacing="0"  border="1">
    <tr>
      <td colspan="5" nowrap bgcolor="#F0F0F0">
              <table border="0" width="100%">
                <tr valign="top" >
                  <td width="50%">Appraiser Signature: <em>"'.$row_rs['appraiser_signature'].'"</em><br>
        At:'. date("F j, Y, g:i a",$row_rs['appraiser_signature_timestamp']).'</td>
                  <td>Teacher Signature<br />
                    Teacher Sig Epoch</td>
                </tr>
              </table>
      </td>
    </tr>
    <tr>
      <td colspan="5" ><div align="center"><strong>DOMAIN I: ACTIVE, SUCCESSFUL STUDENT PARTICIPATION IN THE LEARNING PROCESS </strong></div></td>
    </tr>
    <tr>
      <td colspan="5"><table width="100%" border="1">
        <tr>
          <td> <strong>DATEOBS from IN - " OUT</strong></td>
          <td><strong>Teacher:  TEACHR SIG AND ID</strong></td>
          <td><strong>Appraiser: APPRSR SIG AND ID</strong></td>
        </tr>
      </table></td>
    </tr>
    <td colspan="5"  nowrap> Assignment/Grade:
        <strong>GRADE ASSIGNMENT</strong></td>
  </tr>
  <tr>
    <td >&nbsp;</td>
    <td><div align="center">Exceeds <br>
      (x5)</div></td>
    <td><div align="center">Proficient <br>
      (x3)</div></td>
    <td><div align="center">Below <br>
      (x1)</div></td>
    <td><div align="center">Unsatis-<br>
      factory<br>
      (x0)</div></td>
  </tr>
  <tr>
    <td >1. Engaged in learning</td>
    <td><div align="center"></div></td>
    <td><div align="center"></div></td>
    <td><div align="center"></div></td>
    <td><div align="center"></div></td>
  </tr>
  <tr>
    <td >2. Successful in learning</td>
    <td><div align="center"></div></td>
    <td><div align="center"></div></td>
    <td><div align="center"></div></td>
    <td><div align="center"></div></td>
  </tr>
  <tr>
    <td >3. Critical thinking/ problem solving</td>
    <td><div align="center"></div></td>
    <td><div align="center"></div></td>
    <td><div align="center"></div></td>
    <td><div align="center"></div></td>
    </tr>
  <tr>
    <td >4. Self-directed</td>
    <td><div align="center"></div></td>
    <td><div align="center"></div></td>
    <td><div align="center"></div></td>
    <td><div align="center"></div></td>
    </tr>
  <tr>
    <td >5. Connects learning</td>
    <td><div align="center"></div></td>
    <td><div align="center"></div></td>
    <td><div align="center"></div></td>
    <td><div align="center"></div></td>
    </tr>
  <tr>
    <td class="floatRight" ><strong>Domain I Total:</strong></td>
    <td colspan="4"><div align="center"></div></td>
  </tr>
  <tr>
    <td colspan="5" class="floatRight" >20 to 25 Exceeds Expectations<br>
      12 to 19 Proficient<br>
      4 to 11 Below Expectations<br>
      0 to 3 Unsatisfactory<br></td>
  </tr>
  <tr>
    <td colspan="5" ><label for="one_c">Comments </label>
      <br></td>
  </tr>
  <tr>
    <td ><label for="one_s">Strengths:</label>
      <br>      <br></td>
    <td colspan="4" ><label for="one_a">Areas to Address:</label>
      <br></td>
  </tr>
  </table>';
$pdf=new PDF_HTML_Table();
$pdf->AddPage();
$pdf->SetFont('Courier','',10);
$pdf->WriteHTML("PROFESSIONAL DEVELOPMENT AND APPRAISAL SYSTEM Ending Time:_______
2 0 0 4 R E V I S I O N<BR>$htmlTable<BR>End of the table.");
$pdf->Output();

Open in new window

In your fpdf.php file, what is the orientation set in the __construct() function? You don't appear to be calling the PDF_HTML_Table::PDF function at all, which would explain why it isn't accepting your orientation change.
OWASP: Avoiding Hacker Tricks

Learn to build secure applications from the mindset of the hacker and avoid being exploited.

Not answering your question as such, but I've had a lot of success with the DOMPDF class, linked to below.  This converts HTML (formatted with CSS) to PDF on the fly.  Systems of mine generate fully formatted letters and reports using this.  It cuts out a lot of the faff associated with other classes, building the propietry constructs.

Just thought I'd share my experience.

http://code.google.com/p/dompdf/
Most Valuable Expert 2011
Top Expert 2016

Commented:
http://www.laprbass.com/RAY_fpdf_hello_world_landscape.php creates the blue PDF in Landscape orientation, using the "L" in the constructor and creates the red PDF in portrait orientation by omitting the "L" from the constructor and using the default value.  So it appears that the error is not inherent in FPDF.

It might be that you have an error in the way you call the parent constructor?  Not sure - I cannot follow all of the code, but here is what I would do to try to test this before I fleshed it out...

Write a new version of class PDF_HTML_Table extends FPDF with only a simple "hello world" exercise in it.  Make sure you are using the appropriate PHP5 OOP techniques with constructors, destructors, etc.  Make sure your class overrides only the methods you really want to override.  Once you have the orientation settings working in the simple test case, then add the other information to your class.  Some reference material you may want to look at is here:
http://us.php.net/manual/en/language.oop5.php
<?php // RAY_fpdf_hello_world_landscape.php


// DEMONSTRATE THE BASICS OF FPDF


// BRING IN THE PDF THING
require_once('fpdf16/fpdf.php');


// SYNTHESIZE THE PDF FILE INFORMATION
$pdf_file_link = '/RAY_junk/' . 'temp_pdf_blue' . '.pdf';
$pdf_file_name = getcwd()     . $pdf_file_link;

// DO THE HELLO WORLD EXERCISE IN WHITE ON A BLUE BACKGROUND
$pdf=new FPDF('L', 'mm', 'Letter');
$pdf->AddPage();
$pdf->SetFont('Arial', 'B', 16);
$pdf->SetFillColor(  0,   0, 255);
$pdf->SetTextColor(255, 255, 255);
$pdf->Cell(40, 10, 'Hello World!', 0, 2, 'L', TRUE);

// WRITE THE PDF TO DISK
$pdf->Output($pdf_file_name, 'F');

// PRESENT A LINK
echo '<a target="my_PDF" href="' . $pdf_file_link . '">Blue PDF</a>';


// START OVER FOR A NEW PDF
unset($pdf);
echo PHP_EOL . "<br/>";

// SYNTHESIZE THE PDF FILE INFORMATION
$pdf_file_link = '/RAY_junk/' . 'temp_pdf_red' . '.pdf';
$pdf_file_name = getcwd()     . $pdf_file_link;

// DO THE HELLO WORLD EXERCISE IN WHITE ON A RED BACKGROUND
$pdf=new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial', 'B', 16);
$pdf->SetFillColor(255,   0,   0);
$pdf->SetTextColor(255, 255, 255);
$pdf->Cell(40, 10, 'Hello World!', 0, 2, 'L', TRUE);

// WRITE THE PDF TO DISK
$pdf->Output($pdf_file_name, 'F');

// PRESENT A LINK
echo '<a target="my_PDF" href="' . $pdf_file_link . '">Red PDF</a>';

Open in new window

Author

Commented:
Thank you all, but this pdf class is wicked easy, fast, and beautiful. All I can say is THANK YOU and WOW!

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial