how to convert html to pdf in php using fpdf

how to convert html to pdf in php using fpdf To convert a PDF from HTML we use open source fpdf library.

This class allows to convert HTML to PDF. It was designed to export my blog entries to PDFs.
Also Available Main fpdf features are:

  • provides for underlined, bold, italics text
  • provides for headlines <h1>, <h2>, <h3> & <h4>
  • provides for images
  • simple provides for tables
  • full provides for lists <li>
  • full provides for <blockquote>
  • provides for pseudo-tags <red> & <blue>
  • <pre> will be shown using Courier font, other text with Times
  • provides for <br>, <br /> & <p>
  • provides for <hr> & <hr />
  • document header is created with publishing date, article title, URL, company
  • document footer is created with current & total pagination numbers
  • built-in provides for iconv (character conversions)

Step 1: how to convert html to pdf in php using fpdf?

First of all you can free download FPDF Library from official main website http://www.fpdf.org/

Read Also:  Send Emails Using Laravel 6 Mailable Class?

and then this downloaded unzip file & copy as well as paste FPDF library in your main PHP project library folder.

Call fpdf.php main class where you want apply the PDF download feature, If you want to make a PDF directly with HTML then display as below official great basic and simple example.

require('lib/fpdf/fpdf.php');
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Welcome To Pakainfo!');
$pdf->Output();

Also second example to generate table format in pdf data content example for “how to convert html to pdf in php using fpdf”

require('lib/fpdf/fpdf.php');
class PDF extends FPDF
{
	// Simple table
	function BasicTable($header, $data)
	{
		// Header
		foreach($header as $col)
			$this->Cell(40,7,$col,1);
		$this->Ln();
		// Data
		foreach($data as $row)
		{
			foreach($row as $col)
				$this->Cell(40,6,$col,1);
			$this->Ln();
		}
	}
}

Now You can call BasicTable() methods where you want to generate dynamic product table in PDF format.

$pdf = new PDF();
$header = array('ID', 'Product Name', 'Price (Rs)');
$data = array(
	          array('1', 'Mobile', '5000'),
	          array('2', 'Laptop', '1200'),
	          array('3', 'Computer', '1800'),
	         );
$pdf->SetFont('Arial','',14);
$pdf->AddPage();
$pdf->BasicTable($header,$data);
$pdf->Output();

how to convert html to pdf in php using fpdf
how to convert html to pdf in php using fpdf

php convert html to pdf

Source Code
bellow a form where the user can html input some Form and convert it to PDF:

Read Also:  How to make the number pyramid program in php?

<?php
require('html2pdf.php');

if(isset($_POST['html']))
{
    $pdf = new createPDF(
        $_POST['html'],   // html text to publish
        $_POST['title'],  // article title
        $_POST['url'],    // article URL
        $_POST['company'], // company name
        time()
    );
    $pdf->run();
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html><head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>HTML2PDF - www.pakainfo.com</title>
<style type='text/css'>
  fieldset{padding:10px}
  body{font-size:small}
</style>
</head><body>
<h1>HTML2PDF</h1>
  <form name="pdfgen" method="post" target="_blank" action="<?php echo $_SERVER['PHP_SELF']; ?>">
  <div>
    <fieldset><legend>HTML2PDF - www.pakainfo.com</legend>
    <p>Title: <input type="text" maxlength="30" name="title"></p>
    <p>URL: <input type="text" maxlength="30" name="url"></p>
    <p>company: <input type="text" maxlength="30" name="company"></p>
    <p><textarea name="html" cols="50" rows="15"></textarea></p>
    <p><input type="submit" value="Generate PDF"></p>
    </fieldset>
  </div>
  </form>
</body></html>

How to Convert HTML to PDF Document in PHP using fpdf?

HTML form to submit the data

<html>
<body>
 
<form method="post" action="createpdf.php">
 
             <input id="name" name="name" type="text">
             <input id="email" name="email" type="text">
             <input id="mobile" name="mobile" type="text">
                            
<button type="submit">Submit</button>
                           
</body>
</html>

createpdf.php

<?php

require('getTableData.php');

$pdf=new PDF_HTML();
$pdf->AliasNbPages();

$pdf->SetAutoPageBreak(true, 15);
$pdf->AddPage();

//add logo image here

$pdf->Image('images/pakainfo.png',18,13,33);

//set font style

$pdf->SetFont('Arial','B',14);
$pdf->getTableData('<para><h1>pakainfo.com - API and Web development Tutorial Website</h1><br>
Website: <u>www.pakainfo.com</u></para><br><br>How to Convert HTML to PDF with fpdf example');
 
//set the form of pdf
 
$pdf->SetFont('Arial','B',8);
 
//assign the form post value in a variable and pass it. 
 
$htmlTable='<TABLE>
<TR>
<TD>Name:</TD>
<TD>'.$_POST['name'].'</TD>
</TR>
<TR>
<TD>Email:</TD>
<TD>'.$_POST['email'].'</TD>
</TR>
<TR>
<TD>mobile:</TD>
<TD>'.$_POST['mobile'].'</TD>
</TR>
</TABLE>';

//Write HTML to pdf file and output that file on the web browser.

$pdf->getTableData2("<br><br>$htmlTable");
$pdf->SetFont('Arial','B',6);
$pdf->Output(); 

?>

Creating PDF Files using PHP FPDF library - Convert HTML to PDF
Creating PDF Files using PHP FPDF library – Convert HTML to PDF

getTableData.php code file
<?php
require('./fpdf.php');

class PDF_HTML extends FPDF
{
	var $B=0;
	var $I=0;
	var $U=0;
	var $HREF='';
	var $ALIGN='';

	function getTableData($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)
			{
				if($this->HREF)
					$this->PutLink($this->HREF,$e);
				elseif($this->ALIGN=='center')
					$this->Cell(0,5,$e,0,1,'C');
				else
					$this->Write(5,$e);
			}
			else
			{
				if($e[0]=='/')
					$this->CloseTag(strtoupper(substr($e,1)));
				else
				{
					$a2=explode(' ',$e);
					$tag=strtoupper(array_shift($a2));
					$prop=array();
					foreach($a2 as $v)
					{
						if(preg_match('/([^=]*)=["\']?([^"\']*)/',$v,$a3))
							$prop[strtoupper($a3[1])]=$a3[2];
					}
					$this->OpenTag($tag,$prop);
				}
			}
		}
	}

	function OpenTag($tag,$prop)
	{
		if($tag=='B' || $tag=='I' || $tag=='U')
			$this->SetStyle($tag,true);
		if($tag=='A')
			$this->HREF=$prop['HREF'];
		if($tag=='BR')
			$this->Ln(5);
		if($tag=='P')
			$this->ALIGN=$prop['ALIGN'];
		if($tag=='HR')
		{
			if( !empty($prop['WIDTH']) )
				$Width = $prop['WIDTH'];
			else
				$Width = $this->w - $this->lMargin-$this->rMargin;
			$this->Ln(2);
			$x = $this->GetX();
			$y = $this->GetY();
			$this->SetLineWidth(0.4);
			$this->Line($x,$y,$x+$Width,$y);
			$this->SetLineWidth(0.2);
			$this->Ln(2);
		}
	}

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

	function SetStyle($tag,$enable)
	{
		$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)
	{
		$this->SetTextColor(0,0,255);
		$this->SetStyle('U',true);
		$this->Write(5,$txt,$URL);
		$this->SetStyle('U',false);
		$this->SetTextColor(0);
	}
}
?>

Ref : http://www.fpdf.org/