i wanna to use FPDF to convert html page to pdf file, user will input the item(s) they ordered from a form, after will come out the items for each will listed in a html table format and output as pdf for offline reference.
Now is what i annoyed to deal with fpdf, i want to copy all content from the html table items which user entered previously, convert it to a pdf file and email to the user, but from the example tough by fpdf are no guidance of how to pass previous page contents into it class -> cell(),
PHP Code:
$pdf->Cell(0,10,'Content_of_previous_page');
hope somebody here can give me an assist of that,
thanks in advance.
i had 6 input fields in the form, just a very normal html table show in the page, regard field_01 to field_06 and has a cell data into each.
does anyone have an idea?
This will save your data as a simple table (no header, no frills) in a file called "myFile.pdf".
I used a simple table because you were not very helpful on how you wanted the finished table to look like.
Then you can attach "myFile.pdf" to an email.
pdf.php
PHP Code:
<?php require('fpdf.php');
class PDF extends FPDF { //Load data function LoadData($file) { //Read file lines $lines=file($file); $data=array(); foreach($lines as $line) $data[]=explode(';',chop($line)); return $data; }
//Simple table function BasicTable($header,$data,$column_width) { //Header if($header) { foreach($header as $col) $this->Cell(20,7,$col,1); $this->Ln(); } //Data foreach($data as $row) { foreach($row as $col) $this->Cell($column_width,10,$col,1); $this->Ln(); } } }
class FPDF { var $page; //current page number var $n; //current object number var $offsets; //array of object offsets var $buffer; //buffer holding in-memory PDF var $pages; //array containing pages var $state; //current document state var $compress; //compression flag var $k; //scale factor (number of points in user unit) var $DefOrientation; //default orientation var $CurOrientation; //current orientation var $PageFormats; //available page formats var $DefPageFormat; //default page format var $CurPageFormat; //current page format var $PageSizes; //array storing non-default page sizes var $wPt,$hPt; //dimensions of current page in points var $w,$h; //dimensions of current page in user unit var $lMargin; //left margin var $tMargin; //top margin var $rMargin; //right margin var $bMargin; //page break margin var $cMargin; //cell margin var $x,$y; //current position in user unit var $lasth; //height of last printed cell var $LineWidth; //line width in user unit var $CoreFonts; //array of standard font names var $fonts; //array of used fonts var $FontFiles; //array of font files var $diffs; //array of encoding differences var $FontFamily; //current font family var $FontStyle; //current font style var $underline; //underlining flag var $CurrentFont; //current font info var $FontSizePt; //current font size in points var $FontSize; //current font size in user unit var $DrawColor; //commands for drawing color var $FillColor; //commands for filling color var $TextColor; //commands for text color var $ColorFlag; //indicates whether fill and text colors are different var $ws; //word spacing var $images; //array of used images var $PageLinks; //array of links in pages var $links; //array of internal links var $AutoPageBreak; //automatic page breaking var $PageBreakTrigger; //threshold used to trigger page breaks var $InHeader; //flag set when processing header var $InFooter; //flag set when processing footer var $ZoomMode; //zoom display mode var $LayoutMode; //layout display mode var $title; //title var $subject; //subject var $author; //author var $keywords; //keywords var $creator; //creator var $AliasNbPages; //alias for total number of pages var $PDFVersion; //PDF version number
function SetMargins($left, $top, $right=null) { //Set left, top and right margins $this->lMargin=$left; $this->tMargin=$top; if($right===null) $right=$left; $this->rMargin=$right; }
function SetLeftMargin($margin) { //Set left margin $this->lMargin=$margin; if($this->page>0 && $this->x<$margin) $this->x=$margin; }
function SetTopMargin($margin) { //Set top margin $this->tMargin=$margin; }
function SetRightMargin($margin) { //Set right margin $this->rMargin=$margin; }
function SetAutoPageBreak($auto, $margin=0) { //Set auto page break mode and triggering margin $this->AutoPageBreak=$auto; $this->bMargin=$margin; $this->PageBreakTrigger=$this->h-$margin; }
function AddPage($orientation='', $format='') { //Start a new page if($this->state==0) $this->Open(); $family=$this->FontFamily; $style=$this->FontStyle.($this->underline ? 'U' : ''); $size=$this->FontSizePt; $lw=$this->LineWidth; $dc=$this->DrawColor; $fc=$this->FillColor; $tc=$this->TextColor; $cf=$this->ColorFlag; if($this->page>0) { //Page footer $this->InFooter=true; $this->Footer(); $this->InFooter=false; //Close page $this->_endpage(); } //Start new page $this->_beginpage($orientation,$format); //Set line cap style to square $this->_out('2 J'); //Set line width $this->LineWidth=$lw; $this->_out(sprintf('%.2F w',$lw*$this->k)); //Set font if($family) $this->SetFont($family,$style,$size); //Set colors $this->DrawColor=$dc; if($dc!='0 G') $this->_out($dc); $this->FillColor=$fc; if($fc!='0 g') $this->_out($fc); $this->TextColor=$tc; $this->ColorFlag=$cf; //Page header $this->InHeader=true; $this->Header(); $this->InHeader=false; //Restore line width if($this->LineWidth!=$lw) { $this->LineWidth=$lw; $this->_out(sprintf('%.2F w',$lw*$this->k)); } //Restore font if($family) $this->SetFont($family,$style,$size); //Restore colors if($this->DrawColor!=$dc) { $this->DrawColor=$dc; $this->_out($dc); } if($this->FillColor!=$fc) { $this->FillColor=$fc; $this->_out($fc); } $this->TextColor=$tc; $this->ColorFlag=$cf; }
function Header() { //To be implemented in your own inherited class }
function Footer() { //To be implemented in your own inherited class }
function PageNo() { //Get current page number return $this->page; }
function SetDrawColor($r, $g=null, $b=null) { //Set color for all stroking operations if(($r==0 && $g==0 && $b==0) || $g===null) $this->DrawColor=sprintf('%.3F G',$r/255); else $this->DrawColor=sprintf('%.3F %.3F %.3F RG',$r/255,$g/255,$b/255); if($this->page>0) $this->_out($this->DrawColor); }
function SetFillColor($r, $g=null, $b=null) { //Set color for all filling operations if(($r==0 && $g==0 && $b==0) || $g===null) $this->FillColor=sprintf('%.3F g',$r/255); else $this->FillColor=sprintf('%.3F %.3F %.3F rg',$r/255,$g/255,$b/255); $this->ColorFlag=($this->FillColor!=$this->TextColor); if($this->page>0) $this->_out($this->FillColor); }
function SetTextColor($r, $g=null, $b=null) { //Set color for text if(($r==0 && $g==0 && $b==0) || $g===null) $this->TextColor=sprintf('%.3F g',$r/255); else $this->TextColor=sprintf('%.3F %.3F %.3F rg',$r/255,$g/255,$b/255); $this->ColorFlag=($this->FillColor!=$this->TextColor); }
function GetStringWidth($s) { //Get width of a string in the current font $s=(string)$s; $cw=&$this->CurrentFont['cw']; $w=0; $l=strlen($s); for($i=0;$i<$l;$i++) $w+=$cw[$s[$i]]; return $w*$this->FontSize/1000; }
function SetLineWidth($width) { //Set line width $this->LineWidth=$width; if($this->page>0) $this->_out(sprintf('%.2F w',$width*$this->k)); }
function Line($x1, $y1, $x2, $y2) { //Draw a line $this->_out(sprintf('%.2F %.2F m %.2F %.2F l S',$x1*$this->k,($this->h-$y1)*$this->k,$x2*$this->k,($this->h-$y2)*$this->k)); }
function Rect($x, $y, $w, $h, $style='') { //Draw a rectangle if($style=='F') $op='f'; elseif($style=='FD' || $style=='DF') $op='B'; else $op='S'; $this->_out(sprintf('%.2F %.2F %.2F %.2F re %s',$x*$this->k,($this->h-$y)*$this->k,$w*$this->k,-$h*$this->k,$op)); }
function SetFont($family, $style='', $size=0) { //Select a font; size given in points global $fpdf_charwidths;
$family=strtolower($family); if($family=='') $family=$this->FontFamily; if($family=='arial') $family='helvetica'; elseif($family=='symbol' || $family=='zapfdingbats') $style=''; $style=strtoupper($style); if(strpos($style,'U')!==false) { $this->underline=true; $style=str_replace('U','',$style); } else $this->underline=false; if($style=='IB') $style='BI'; if($size==0) $size=$this->FontSizePt; //Test if font is already selected if($this->FontFamily==$family && $this->FontStyle==$style && $this->FontSizePt==$size) return; //Test if used for the first time $fontkey=$family.$style; if(!isset($this->fonts[$fontkey])) { //Check if one of the standard fonts if(isset($this->CoreFonts[$fontkey])) { if(!isset($fpdf_charwidths[$fontkey])) { //Load metric file $file=$family; if($family=='times' || $family=='helvetica') $file.=strtolower($style); include($this->_getfontpath().$file.'.php'); if(!isset($fpdf_charwidths[$fontkey])) $this->Error('Could not include font metric file'); } $i=count($this->fonts)+1; $name=$this->CoreFonts[$fontkey]; $cw=$fpdf_charwidths[$fontkey]; $this->fonts[$fontkey]=array('i'=>$i, 'type'=>'core', 'name'=>$name, 'up'=>-100, 'ut'=>50, 'cw'=>$cw); } else $this->Error('Undefined font: '.$family.' '.$style); } //Select it $this->FontFamily=$family; $this->FontStyle=$style; $this->FontSizePt=$size; $this->FontSize=$size/$this->k; $this->CurrentFont=&$this->fonts[$fontkey]; if($this->page>0) $this->_out(sprintf('BT /F%d %.2F Tf ET',$this->CurrentFont['i'],$this->FontSizePt)); }
function SetFontSize($size) { //Set font size in points if($this->FontSizePt==$size) return; $this->FontSizePt=$size; $this->FontSize=$size/$this->k; if($this->page>0) $this->_out(sprintf('BT /F%d %.2F Tf ET',$this->CurrentFont['i'],$this->FontSizePt)); }
function AddLink() { //Create a new internal link $n=count($this->links)+1; $this->links[$n]=array(0, 0); return $n; }
function SetLink($link, $y=0, $page=-1) { //Set destination of internal link if($y==-1) $y=$this->y; if($page==-1) $page=$this->page; $this->links[$link]=array($page, $y); }
function Link($x, $y, $w, $h, $link) { //Put a link on the page $this->PageLinks[$this->page][]=array($x*$this->k, $this->hPt-$y*$this->k, $w*$this->k, $h*$this->k, $link); }
function Write($h, $txt, $link='') { //Output text in flowing mode $cw=&$this->CurrentFont['cw']; $w=$this->w-$this->rMargin-$this->x; $wmax=($w-2*$this->cMargin)*1000/$this->FontSize; $s=str_replace("\r",'',$txt); $nb=strlen($s); $sep=-1; $i=0; $j=0; $l=0; $nl=1; while($i<$nb) { //Get next character $c=$s[$i]; if($c=="\n") { //Explicit line break $this->Cell($w,$h,substr($s,$j,$i-$j),0,2,'',0,$link); $i++; $sep=-1; $j=$i; $l=0; if($nl==1) { $this->x=$this->lMargin; $w=$this->w-$this->rMargin-$this->x; $wmax=($w-2*$this->cMargin)*1000/$this->FontSize; } $nl++; continue; } if($c==' ') $sep=$i; $l+=$cw[$c]; if($l>$wmax) { //Automatic line break if($sep==-1) { if($this->x>$this->lMargin) { //Move to next line $this->x=$this->lMargin; $this->y+=$h; $w=$this->w-$this->rMargin-$this->x; $wmax=($w-2*$this->cMargin)*1000/$this->FontSize; $i++; $nl++; continue; } if($i==$j) $i++; $this->Cell($w,$h,substr($s,$j,$i-$j),0,2,'',0,$link); } else { $this->Cell($w,$h,substr($s,$j,$sep-$j),0,2,'',0,$link); $i=$sep+1; } $sep=-1; $j=$i; $l=0; if($nl==1) { $this->x=$this->lMargin; $w=$this->w-$this->rMargin-$this->x; $wmax=($w-2*$this->cMargin)*1000/$this->FontSize; } $nl++; } else $i++; } //Last chunk if($i!=$j) $this->Cell($l/1000*$this->FontSize,$h,substr($s,$j),0,0,'',0,$link); }
function Ln($h=null) { //Line feed; default value is last cell height $this->x=$this->lMargin; if($h===null) $this->y+=$this->lasth; else $this->y+=$h; }
function Image($file, $x=null, $y=null, $w=0, $h=0, $type='', $link='') { //Put an image on the page if(!isset($this->images[$file])) { //First use of this image, get info if($type=='') { $pos=strrpos($file,'.'); if(!$pos) $this->Error('Image file has no extension and no type was specified: '.$file); $type=substr($file,$pos+1); } $type=strtolower($type); if($type=='jpeg') $type='jpg'; $mtd='_parse'.$type; if(!method_exists($this,$mtd)) $this->Error('Unsupported image type: '.$type); $info=$this->$mtd($file); $info['i']=count($this->images)+1; $this->images[$file]=$info; } else $info=$this->images[$file]; //Automatic width and height calculation if needed if($w==0 && $h==0) { //Put image at 72 dpi $w=$info['w']/$this->k; $h=$info['h']/$this->k; } elseif($w==0) $w=$h*$info['w']/$info['h']; elseif($h==0) $h=$w*$info['h']/$info['w']; //Flowing mode if($y===null) { if($this->y+$h>$this->PageBreakTrigger && !$this->InHeader && !$this->InFooter && $this->AcceptPageBreak()) { //Automatic page break $x2=$this->x; $this->AddPage($this->CurOrientation,$this->CurPageFormat); $this->x=$x2; } $y=$this->y; $this->y+=$h; } if($x===null) $x=$this->x; $this->_out(sprintf('q %.2F 0 0 %.2F %.2F %.2F cm /I%d Do Q',$w*$this->k,$h*$this->k,$x*$this->k,($this->h-($y+$h))*$this->k,$info['i'])); if($link) $this->Link($x,$y,$w,$h,$link); }
function GetX() { //Get x position return $this->x; }
function SetX($x) { //Set x position if($x>=0) $this->x=$x; else $this->x=$this->w+$x; }
function GetY() { //Get y position return $this->y; }
function SetY($y) { //Set y position and reset x $this->x=$this->lMargin; if($y>=0) $this->y=$y; else $this->y=$this->h+$y; }
function SetXY($x, $y) { //Set x and y positions $this->SetY($y); $this->SetX($x); }
function Output($name='', $dest='') { //Output PDF to some destination if($this->state<3) $this->Close(); $dest=strtoupper($dest); if($dest=='') { if($name=='') { $name='doc.pdf'; $dest='I'; } else $dest='F'; } switch($dest) { case 'I': //Send to standard output if(ob_get_length()) $this->Error('Some data has already been output, can\'t send PDF file'); if(php_sapi_name()!='cli') { //We send to a browser header('Content-Type: application/pdf'); if(headers_sent()) $this->Error('Some data has already been output, can\'t send PDF file'); header('Content-Length: '.strlen($this->buffer)); header('Content-Disposition: inline; filename="'.$name.'"'); header('Cache-Control: private, max-age=0, must-revalidate'); header('Pragma: public'); ini_set('zlib.output_compression','0'); } echo $this->buffer; break; case 'D': //Download file if(ob_get_length()) $this->Error('Some data has already been output, can\'t send PDF file'); header('Content-Type: application/x-download'); if(headers_sent()) $this->Error('Some data has already been output, can\'t send PDF file'); header('Content-Length: '.strlen($this->buffer)); header('Content-Disposition: attachment; filename="'.$name.'"'); header('Cache-Control: private, max-age=0, must-revalidate'); header('Pragma: public'); ini_set('zlib.output_compression','0'); echo $this->buffer; break; case 'F': //Save to local file $f=fopen($name,'wb'); if(!$f) $this->Error('Unable to create output file: '.$name); fwrite($f,$this->buffer,strlen($this->buffer)); fclose($f); break; case 'S': //Return as a string return $this->buffer; default: $this->Error('Incorrect output destination: '.$dest); } return ''; }
/******************************************************************************* * * * Protected methods * * * *******************************************************************************/ function _dochecks() { //Check availability of %F if(sprintf('%.1F',1.0)!='1.0') $this->Error('This version of PHP is not supported'); //Check mbstring overloading if(ini_get('mbstring.func_overload') & 2) $this->Error('mbstring overloading must be disabled'); //Disable runtime magic quotes if(get_magic_quotes_runtime()) @set_magic_quotes_runtime(0); }
function _escape($s) { //Escape special characters in strings $s=str_replace('\\','\\\\',$s); $s=str_replace('(','\\(',$s); $s=str_replace(')','\\)',$s); $s=str_replace("\r",'\\r',$s); return $s; }
function _textstring($s) { //Format a text string return '('.$this->_escape($s).')'; }
function _readstream($f, $n) { //Read n bytes from stream $res=''; while($n>0 && !feof($f)) { $s=fread($f,$n); if($s===false) $this->Error('Error while reading stream'); $n-=strlen($s); $res.=$s; } if($n>0) $this->Error('Unexpected end of stream'); return $res; }
function _readint($f) { //Read a 4-byte integer from stream $a=unpack('Ni',$this->_readstream($f,4)); return $a['i']; }
function _parsegif($file) { //Extract info from a GIF file (via PNG conversion) if(!function_exists('imagepng')) $this->Error('GD extension is required for GIF support'); if(!function_exists('imagecreatefromgif')) $this->Error('GD has no GIF read support'); $im=imagecreatefromgif($file); if(!$im) $this->Error('Missing or incorrect image file: '.$file); imageinterlace($im,0); $tmp=tempnam('.','gif'); if(!$tmp) $this->Error('Unable to create a temporary file'); if(!imagepng($im,$tmp)) $this->Error('Error while saving to temporary file'); imagedestroy($im); $info=$this->_parsepng($tmp); unlink($tmp); return $info; }
function _newobj() { //Begin a new object $this->n++; $this->offsets[$this->n]=strlen($this->buffer); $this->_out($this->n.' 0 obj'); }
function _putstream($s) { $this->_out('stream'); $this->_out($s); $this->_out('endstream'); }
function _out($s) { //Add a line to the document if($this->state==2) $this->pages[$this->page].=$s."\n"; else $this->buffer.=$s."\n"; }
thanks job0107, the sample your shown is nice used in form input conversion, but its doesn't look what i need.
you can just ignore the form input part, because user input will print to html table onward for temporary data hold, once they ensure all record(s) is firm, will click a button to generate a pdf and send to user email, the pdf will look exactly same like previous page as seen, its included user info on header other than the html table.
Your post on php scripts were very helpful, would you know how to set up your scripts to offer 2 columns? I like the result of the layout but I need to make my document in 2 columns so I can fit everything into 1 page. I've been trying to find scripts that can layout the received pdfs nicely but nothing is working.
Your post on php scripts were very helpful, would you know how to set up your scripts to offer 2 columns? I like the result of the layout but I need to make my document in 2 columns so I can fit everything into 1 page. I've been trying to find scripts that can layout the received pdfs nicely but nothing is working.
Thanks a bunch!
Shary
The $data array is a multidimensional array, arranged by row and column.
So the inner arrays represent the columns.
And the more elements you have in the inner arrays, the more columns you will have.
This version of the $data array is set up with three rows and two columns.
PHP Code:
<?php require('fpdf.php');
class PDF extends FPDF { //Load data function LoadData($file) { //Read file lines $lines=file($file); $data=array(); foreach($lines as $line) $data[]=explode(';',chop($line)); return $data; }
//Simple table function BasicTable($header,$data,$column_width) { //Header if($header) { foreach($header as $col) $this->Cell(20,7,$col,1); $this->Ln(); } //Data foreach($data as $row) { foreach($row as $col) $this->Cell($column_width,10,$col,1); // Change the value 10, to change the height of the rows. $this->Ln(); } } }
$pdf=new PDF(); //Data loading $data = array();
// This configuration gives you three rows and two columns. // $data[] = array($_POST["field_01"],$_POST["field_02"]); $data[] = array($_POST["field_03"],$_POST["field_04"]); $data[] = array($_POST["field_05"],$_POST["field_06"]);
// This would be two rows and three columns. // /* $data[] = array($_POST["field_01"],$_POST["field_02"],$_POST["field_03"]); $data[] = array($_POST["field_04"],$_POST["field_05"],$_POST["field_06"]); */ //////////////////////////////////////////////
// And this would be one row and six columns. // /* $data[] = array($_POST["field_01"],$_POST["field_02"],$_POST["field_03"],$_POST["field_04"],$_POST["field_05"],$_POST["field_06"]); */ //////////////////////////////////////////////
$pdf->SetFont('Arial','',14); $pdf->AddPage(); $pdf->BasicTable("",$data,50); // Change the value 50, to change the width oh the columns.
// Disable this line and enable the next line to output to a file. // $pdf->Output(); // $pdf->Output("myFile.pdf","F"); ?>
YES!! You're the best, the only thing I need to figure out now is how to add specific styles (ex: bold or underline attributes) to certain areas. For instance, I've set up my arrays like this:
I basically want everything in the first column to be bold so the $_POST information is displayed as the response and is NOT bold in the final PDF. But everything I try like bold tags in [] or altering the set font either won't work or works on all the text in my document.
I also can't figure out why the text runs off the page of my PDF for the COMMENTS section (last line in set of arrays). Does this have to do with my actual form or is it my pdf.php / fpdf.php files?
Thank you so much btw, its really hard to find someone who can understand and actually deliver a resourceful response. You've been a big help
First, I put your labels in an array for easier reference ($labels).
Second, I added a way to assign a few attributes to each cell (fontFamily, fontWeight/fontDecoration (ie: B = bold, U = underline and I = italics), fontSize and text alignment within the cell (ie:L = left, R = right and C = center)).
The font attributes can be added to any cell by appending them to the text string.
Unfortunately there is no easy way to assign different font attributes to single characters, unless each character were in a different cell.
The font attributes must be in a specific order.
First they must start with the "*" symbol.
Then the fontFamily, fontWeight, fontSize and text alignment, separated by the ":" symbol.
Example: "*Arial;B;12;C"
PHP Code:
<?php require('fpdf.php');
class PDF extends FPDF { //Load data function LoadData($file) { //Read file lines $lines=file($file); $data=array(); foreach($lines as $line) $data[]=explode(';',chop($line)); return $data; } //Simple table function BasicTable($header,$data,$column_width) { //Header if($header) { foreach($header as $col) $this->Cell(20,7,$col,1); $this->Ln(); } //Data foreach($data as $row) { foreach($row as $col) { $col_parts = explode("*",$col); if($col_parts[1]) { list($font_family,$font_weight,$font_size,$align) = explode(";",$col_parts[1]); $this->SetFont($font_family,$font_weight,$font_size); } $this->Cell($column_width,10,$col_parts[0],1,0,$align); // Change the value 10, to change the height of the rows. } $this->Ln(); } } }
Thank you so much!! Would you know anything about text wrapping issues? It's the only problem I have left that I still can't figure out. I'm not sure if its my form or if its my pdf.php / fpdf.php files. Basically my text goes off the emailed PDF page when a comment is added. If the comment is too long it just keeps going as if there is no right margin