Create Dynamic PDF and Send as Attachment with Email in PHP?

Here we have use TCPDF for PDF generation and PHPMailer for sending an email. We will create live demo example for dynamically generate PDF file and send an email as attachment.

TCPDF is now one of the world’s most active Open Source projects, used daily by millions of users and included in thousands of CMS and Web applications.

PHPMailer is a code library to send emails safely and easily via PHP code from a web server. Sending emails directly by PHP code requires a high-level familiarity to SMTP protocol standards and related issues and vulnerabilities about Email injection for spamming.

Now let’s start the step by step code configuration and database setup for generating PDF dynamically and send as attachment.

  • Step 1: Firstly login in to your database and Execute below SQL statements.
CREATE TABLE `INVOICE_MST` (
  `MST_ID` int(11) NOT NULL AUTO_INCREMENT,
  `INV_NO` varchar(100) DEFAULT NULL,
  `CUSTOMER_NAME` varchar(255) DEFAULT NULL,
  `CUSTOMER_MOBILENO` varchar(10) DEFAULT NULL,
  `ADDRESS` text DEFAULT NULL,
  PRIMARY KEY (`MST_ID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

insert into `INVOICE_MST`(`MST_ID`,`INV_NO`,`CUSTOMER_NAME`,`CUSTOMER_MOBILENO`,`ADDRESS`) values (1,'INV01','DIVYESH PATEL','9825121212','VALSAD, GUJARAT');
insert into `INVOICE_MST`(`MST_ID`,`INV_NO`,`CUSTOMER_NAME`,`CUSTOMER_MOBILENO`,`ADDRESS`) values (2,'INV02','ROSHNI PATEL','8457878878','CHIKHLI, GUJARAT');
insert into `INVOICE_MST`(`MST_ID`,`INV_NO`,`CUSTOMER_NAME`,`CUSTOMER_MOBILENO`,`ADDRESS`) values (3,'INV03','DITYA PATEL','7487878788','JESPOR, VALSAD');

CREATE TABLE `INVOICE_DET` (
  `DET_ID` int(11) NOT NULL AUTO_INCREMENT,
  `MST_ID` int(11) DEFAULT NULL,
  `PRODUCT_NAME` varchar(255) DEFAULT NULL,
  `AMOUNT` double(11,2) DEFAULT NULL,
  PRIMARY KEY (`DET_ID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

insert into `INVOICE_DET`(`DET_ID`,`MST_ID`,`PRODUCT_NAME`,`AMOUNT`) values (1,1,'DOMAIN WWW.SHINERWEB.COM',899);
insert into `INVOICE_DET`(`DET_ID`,`MST_ID`,`PRODUCT_NAME`,`AMOUNT`) values (2,1,'DATABASE MYSQL',3499);
insert into `INVOICE_DET`(`DET_ID`,`MST_ID`,`PRODUCT_NAME`,`AMOUNT`) values (3,1,'EMAIL SERVICES',799);
insert into `INVOICE_DET`(`DET_ID`,`MST_ID`,`PRODUCT_NAME`,`AMOUNT`) values (4,2,'DOMAIN WWW.GOOGLE.COM',4500);
insert into `INVOICE_DET`(`DET_ID`,`MST_ID`,`PRODUCT_NAME`,`AMOUNT`) values (5,2,'EMAIL SERVICES',799);
insert into `INVOICE_DET`(`DET_ID`,`MST_ID`,`PRODUCT_NAME`,`AMOUNT`) values (6,3,'DOMAIN WWW.FACEBOOK.COM',7999);

Above sample data will be used for generating invoice PDF.

Step 2: Create database connection file like database_connection.php which is used to get data from the database.

<?php
$hostname = "localhost";
$username = "root";
$password = "";  
$database = "shinerweb_db";   
$con=mysqli_connect($hostname,$username,$password,$database);    
?>

Step 3: Make one index.php where we will display our data as below.

<!doctype html>
<html lang="en">
<head>
<title>How to generate PDF in PHP dynamically by using TCPDF</title>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width" />
<!-- *Note: You must have internet connection on your laptop or pc other wise below code is not working -->
<!-- Add icon library -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<!-- bootstrap css and js -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"/>
<!-- JS for jQuery -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
	<div class="row">
		<div class="col-lg-12" align="center">
			<br>
			<h5 align="center">How to generate PDF in PHP dynamically by using TCPDF</h5>
			<br>
			<table class="table table-striped">
			<thead>
			  <tr>
				<th>Invoice #</th>
				<th>Customer name</th>
				<th>Contact #</th>
				<th>Address</th>
				<th>Action</th>
			  </tr>
			</thead>
			<tbody>
			<?php                
			require 'database_connection.php'; 
			$display_query = "SELECT T1.MST_ID, T1.INV_NO, T1.CUSTOMER_NAME, T1.CUSTOMER_MOBILENO, T1.ADDRESS FROM INVOICE_MST T1";             
			$results = mysqli_query($con,$display_query);   
			$count = mysqli_num_rows($results);			
			if($count>0) 
			{
				while($data_row = mysqli_fetch_array($results, MYSQLI_ASSOC))
				{
					?>
				 <tr>
				 	<td><?php echo $data_row['INV_NO']; ?></td>
				 	<td><?php echo $data_row['CUSTOMER_NAME']; ?></td>
				 	<td><?php echo $data_row['CUSTOMER_MOBILENO']; ?></td>
				 	<td><?php echo $data_row['ADDRESS']; ?></td>
				 	<td>
				 		<a href="pdf_maker.php?MST_ID=<?php echo $data_row['MST_ID']; ?>&ACTION=VIEW" class="btn btn-success"><i class="fa fa-file-pdf-o"></i> View PDF</a> &nbsp;&nbsp; 
				 		<a href="pdf_maker.php?MST_ID=<?php echo $data_row['MST_ID']; ?>&ACTION=DOWNLOAD" class="btn btn-danger"><i class="fa fa-download"></i> Download PDF</a>
						&nbsp;&nbsp; 
				 		<a href="pdf_maker.php?MST_ID=<?php echo $data_row['MST_ID']; ?>&ACTION=UPLOAD" class="btn btn-warning"><i class="fa fa-upload"></i> Upload PDF</a>
				 		&nbsp;&nbsp; 
				 		<a href="pdf_maker.php?MST_ID=<?php echo $data_row['MST_ID']; ?>&ACTION=EMAIL" class="btn btn-info"><i class="fa fa-envelope"></i> Email PDF</a>
					</td>
				 </tr>
				 <?php
				}
			}
			?>
			</tbody>
			</table>
		</div>
	</div>
</div>
<br>
<center>Developed by <a href="https://shinerweb.com/">Shinerweb</a></center>
</body>
</html> 

In above code we included font-awesome.min.css, bootstrap.min.css, jquery.min.js and bootstrap.min.js which is used for webpage design and some icons setup.

Inside <tbody> tag we dynamically display invoice data from the database and that data will be use for further code.

Step 4: Now finally create one file pdf_maker.php and inside this file we will write all the logic for generate PDF and send an email that PDF.

<?php                
require 'database_connection.php'; 
include_once('tcpdf_6_2_13/tcpdf/tcpdf.php');

$MST_ID=$_GET['MST_ID'];

$inv_mst_query = "SELECT T1.MST_ID, T1.INV_NO, T1.CUSTOMER_NAME, T1.CUSTOMER_MOBILENO, T1.ADDRESS FROM INVOICE_MST T1 WHERE T1.MST_ID='".$MST_ID."' ";             
$inv_mst_results = mysqli_query($con,$inv_mst_query);   
$count = mysqli_num_rows($inv_mst_results);  
if($count>0) 
{
	$inv_mst_data_row = mysqli_fetch_array($inv_mst_results, MYSQLI_ASSOC);

	//----- Code for generate pdf
	$pdf = new TCPDF('P', PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
	$pdf->SetCreator(PDF_CREATOR);  
	//$pdf->SetTitle("Export HTML Table data to PDF using TCPDF in PHP");  
	$pdf->SetHeaderData('', '', PDF_HEADER_TITLE, PDF_HEADER_STRING);  
	$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));  
	$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));  
	$pdf->SetDefaultMonospacedFont('helvetica');  
	$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);  
	$pdf->SetMargins(PDF_MARGIN_LEFT, '5', PDF_MARGIN_RIGHT);  
	$pdf->setPrintHeader(false);  
	$pdf->setPrintFooter(false);  
	$pdf->SetAutoPageBreak(TRUE, 10);  
	$pdf->SetFont('helvetica', '', 12);  
	$pdf->AddPage(); //default A4
	//$pdf->AddPage('P','A5'); //when you require custome page size 
	
	$content = ''; 

	$content .= '
	<style type="text/css">
	body{
	font-size:12px;
	line-height:24px;
	font-family:"Helvetica Neue", "Helvetica", Helvetica, Arial, sans-serif;
	color:#000;
	}
	</style>    
	<table cellpadding="0" cellspacing="0" style="border:1px solid #ddc;width:100%;">
	<table style="width:100%;" >
	<tr><td colspan="2">&nbsp;</td></tr>
	<tr><td colspan="2" align="center"><b>SHINERWEB TECHNOLOGIES</b></td></tr>
	<tr><td colspan="2" align="center"><b>CONTACT: +91 97979  97979</b></td></tr>
	<tr><td colspan="2" align="center"><b>WEBSITE: WWW.SHINERWEB.COM</b></td></tr>
	<tr><td colspan="2"><b>CUST.NAME: '.$inv_mst_data_row['CUSTOMER_NAME'].' </b></td></tr>
	<tr><td><b>MOB.NO: '.$inv_mst_data_row['CUSTOMER_MOBILENO'].' </b></td><td align="right"><b>BILL DT.: '.date("d-m-Y").'</b> </td></tr>
	<tr><td>&nbsp;</td><td align="right"><b>BILL NO.: '.$inv_mst_data_row['INV_NO'].'</b></td></tr>
	<tr><td colspan="2" align="center"><b>INVOICE</b></td></tr>
	<tr class="heading" style="background:#eee;border-bottom:1px solid #ddd;font-weight:bold;">
		<td>
			TYPE OF WORK
		</td>
		<td align="right">
			AMOUNT
		</td>
	</tr>';
		$total=0;
		$inv_det_query = "SELECT T2.PRODUCT_NAME, T2.AMOUNT FROM INVOICE_DET T2 WHERE T2.MST_ID='".$MST_ID."' ";
		$inv_det_results = mysqli_query($con,$inv_det_query);    
		while($inv_det_data_row = mysqli_fetch_array($inv_det_results, MYSQLI_ASSOC))
		{	
		$content .= '
		  <tr class="itemrows">
			  <td>
				  <b>'.$inv_det_data_row['PRODUCT_NAME'].'</b>
				  <br>
				  <i>Write any remarks</i>
			  </td>
			  <td align="right"><b>
				  '.$inv_det_data_row['AMOUNT'].'
			  </b></td>
		  </tr>';
		$total=$total+$inv_det_data_row['AMOUNT'];
		}
		$content .= '<tr class="total"><td colspan="2" align="right">------------------------</td></tr>
		<tr><td colspan="2" align="right"><b>GRAND&nbsp;TOTAL:&nbsp;'.$total.'</b></td></tr>
		<tr><td colspan="2" align="right">------------------------</td></tr>
	<tr><td colspan="2" align="right"><b>PAYMENT MODE: CASH/ONLINE </b></td></tr>
	<tr><td colspan="2">&nbsp;</td></tr>
	<tr><td colspan="2" align="center"><b>THANK YOU ! VISIT AGAIN</b></td></tr>
	<tr><td colspan="2">&nbsp;</td></tr>
	</table>
</table>'; 
$pdf->writeHTML($content);

$file_location = "/home/fbi1glfa0j7p/public_html/examples/generate_pdf/uploads/"; //add your full path of your server
//$file_location = "/opt/lampp/htdocs/examples/generate_pdf/uploads/"; //for local xampp server

$datetime=date('dmY_hms');
$file_name = "INV_".$datetime.".pdf";
ob_end_clean();

if($_GET['ACTION']=='VIEW') 
{
	$pdf->Output($file_name, 'I'); // I means Inline view
} 
else if($_GET['ACTION']=='DOWNLOAD')
{
	$pdf->Output($file_name, 'D'); // D means download
}
else if($_GET['ACTION']=='UPLOAD')
{
$pdf->Output($file_location.$file_name, 'F'); // F means upload PDF file on some folder
echo "Upload successfully!!";
}
else if($_GET['ACTION']=='EMAIL')
{
$pdf->Output($file_location.$file_name, 'F'); // F means upload PDF file on some folder
//echo "Email send successfully!!";
	error_reporting(E_ALL ^ E_DEPRECATED);	
	include_once('PHPMailer/class.phpmailer.php');	
	require ('PHPMailer/PHPMailerAutoload.php');

	$body='';
	$body .="<html>
	<head>
	<style type='text/css'> 
	body {
	font-family: Calibri;
	font-size:16px;
	color:#000;
	}
	</style>
	</head>
	<body>
	Dear Customer,
	<br>
	Please find attached invoice copy.
	<br>
	Thank you!
	</body>
	</html>";

	$mail = new PHPMailer();
	$mail->CharSet = 'UTF-8';
	$mail->IsMAIL();
	$mail->IsSMTP();
	$mail->Subject    = "Invoice details";
	$mail->From = "[email protected]";
	$mail->FromName = "Shinerweb Technologies";
	$mail->IsHTML(true);
	$mail->AddAddress('[email protected]'); // To mail id
	//$mail->AddCC('[email protected]'); // Cc mail id
	//$mail->AddBCC('[email protected]'); // Bcc mail id

	$mail->AddAttachment($file_location.$file_name);
	$mail->MsgHTML ($body);
	$mail->WordWrap = 50;
	$mail->Send();	
	$mail->SmtpClose();
	if($mail->IsError()) {
	echo "Mailer Error: " . $mail->ErrorInfo;
	} else {
		echo "Message sent!";					
	};
}
//----- End Code for generate pdf
	
}
else
{
	echo 'Record not found for PDF.';
}

?>

Once your created above file you must have to include TCPDF and PHPMailer library and that library you can download from below Source Code button. We provide full source code so can easily configure or setup your project for dynamic PDF generation and Email send.


Invoice copy attachment in email

Note*: If you don’t know how to configure PHPMailer then please see below blog link.

Kindly note below some points or configuration while setup this code.

1) When you required different page size instead of A4 at that time you must have to add below code.

$pdf->AddPage('P','A5'); //when you require custom page size 

2) When you want to view PDF file.

$pdf->Output($file_name, 'I'); // I means Inline view

3) When you need to Download PDF on your local computer.

$pdf->Output($file_name, 'D'); // D means download

4) Upload your dynamic PDF file on server.

$file_location = "/home/fbi1glfa0j7p/public_html/examples/generate_pdf/uploads/"; //add your full path of your server
$pdf->Output($file_location.$file_name, 'F'); // F means upload PDF file on some folder

Related Posts

Divyesh Patel

I'm Divyesh Patel, Web & App developer. I want to make things that make a difference. With every line of code, i strive to make the web a beautiful place.

Leave a Reply