Click here to Skip to main content
15,887,267 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Please help me. I want to include pdf file which I use mpdf in another page php and html page. I have create a searching page for user to key in their detail such as month and name. Then, they have to click submit button.

Based on their searching, user can get their document in email attachment after click submit.

How do I save the attachment (in another mpdf page: example: printout.php) in temporary file after user click submit and when email send, the temporary file should be unlink from the temporary file.

What I have tried:

PHP
$myWHERE = '';
$myWHERECond = array();

$myWHERE = '';
$myWHERECond = array();
if (!empty($filter['month'])){
	$myWHERECond[] = 'A.payroll_month = "' . $filter['month'] . '"';
}

if (!empty($filter['user'])){
	$myWHERECond[] = 'B.user_id = ' . $filter['user'];
	//$myWHERECond[] = 'C.id = ' . $filter['user'];
}

if (count($myWHERECond) > 0){
	$myWHERE = ' WHERE ('.implode(' AND ', $myWHERECond).')';
}

$ListData = array();

if (isset($_GET['btnaction'])){
	if ($_GET['btnaction'] == 'search'){
		$mySQL = 'SELECT A.status, B.* FROM payroll_monthly A INNER JOIN payroll_monthly_detail B ON A.payroll_month = B.payroll_month '.$myWHERE.' AND B.estatement_type > 0 ORDER BY A.id';
		$result = mysql_query($mySQL);
		if ($result){
			if (mysql_num_rows($result) > 0){
				while ($row = mysql_fetch_assoc($result)){	

					if ($row['status'] == 2){
						$ListData[$row['payroll_id']]['payroll_id'] = $row['payroll_id'];
						$ListData[$row['payroll_id']]['month'] = $row['payroll_month'];
						$ListData[$row['payroll_id']]['company'] = $row['company'];
						$ListData[$row['payroll_id']]['estatement_type'] = $row['estatement_type'];
						$ListData[$row['payroll_id']]['fullname'] = $row['staff_ic_name'];
						$ListData[$row['payroll_id']]['staff_no'] = $row['staff_no'];

						if ($filter['user'] > 0){
							$ValidProcess = true;
							if ($ValidProcess){
								
								//GET EMAIL
								$Receiver = array();
								$mySQL2 = 'SELECT email FROM system_user WHERE id = ' . $filter['user'];
								$result2 = mysql_query($mySQL2);
								if ($result2){
									if (mysql_num_rows($result2) > 0){
										$row2 = mysql_fetch_assoc($result2);						
										$Receiver = $row2['email'];
									}
								}
								
								
								//if ($GlobalSendEmail){
									require_once './library/swiftmailer/swift_required.php';

										$body2 = '';
										$body2 .= '';
										$body2 .= 'Sample Payslip for the month of '.$filter['month'].'.';
										$body2 .= 'Please find the attached eStatement for the month of '.$filter['month'].'.';
										$body2 .= 'To access your payslip, please key in the password of your birth date.Ex: XX-XX-XXXX';
										$body2 .= '';
										
										$transport2 = Swift_SmtpTransport::newInstance($EmailNotifyHost, $EmailNotifyPort)
										->setUsername($EmailNotifyUsername)
										->setPassword($EmailNotifyPassword)
										;

										$message2 = Swift_Message::newInstance()
										->setSubject('SAMPLE PAYSLIP FOR THE MONTH OF '. $filter['month'])
										->setFrom(array($EmailNotifyUsername => TITLE))
										->setTo($Receiver)
										->setBody($body2, 'text/html')
										->setPriority(2)
										//->addAttachment($html, 'application/pdf', $filename, 'attachment')
										;	
					
										//$result2 = $mailer2->send($message2);
								//}
				
								$_SESSION[AppName]['sessionmessage']['type'] = 'info';
								$_SESSION[AppName]['sessionmessage']['message'][] = 'Your paslip has been emailed.';
								
							}
							else{
								$_SESSION[AppName]['sessionmessage']['type'] = 'danger';
								$_SESSION[AppName]['sessionmessage']['message'][] = 'Payslip not ready yet.';
							}
						}
					}
					else{
						//status management belum approved
						$_SESSION[AppName]['sessionmessage']['type'] = 'danger';
						$_SESSION[AppName]['sessionmessage']['message'][] = 'In progress.';
					}
				}
				
			}
			else{
				//bulan kedepan
				$_SESSION[AppName]['sessionmessage']['type'] = 'danger';
				$_SESSION[AppName]['sessionmessage']['message'][] = 'No record.';
			}
		}
	}/*
	else if ($_GET['btnaction'] == 'email'){

	}*/
}


HTML
<pre><div class="row">
	<div class="col-md-12">
		<div class="form-group">
			<label class="col-md-2 control-label sbold text-right">Month & Year</label>
			<div class="col-md-6">
				<input class="form-control input-small date-picker bg-grey" type="text" name="month" value="<?php echo $filter['month']; ?>" />
			</div>
	</div>

	<div class="form-group">
		<label class="col-md-2 control-label sbold text-right">Staff Name</label>
		<div class="col-md-6">
		<select class="form-control select2" name="user">
		<?php
			foreach ($ListStaff as $key => $value){
			$filter['user'] == $key ? $xSelect = ' selected="selected"' : $xSelect = '';
			echo '<option value="'.$key.'"'.$xSelect.'>'.$value.'</option>';
		}
	?>
	</select>		
	</div>
	</div>
										
<div class="form-group">
	<div class="col-md-offset-2 col-md-6">	
		<button type="submit" class="btn red" name="btnaction" value="search">Search</button>
	
	</div>
	</div>
	</div>
									
									
	<div class="row">
		<div class="col-md-offset-2 col-md-10">	
			<?php
				echo '<div class="font-yellow-casablanca" style="font-size:1.2em;font-weight: bold;">'.(array_key_exists($filter['user'],$ListStaff) ? $ListStaff[$filter['user']] : '').'\'s eStatement Details</div>';
	?>
	<table class="table table-border-black table-nonfluid table-striped" style="margin-top:15px;color: #000;">
	<thead>
	<tr class="bg-default">
	<th class="text-center colNo"> # </th>
	<th class=""> Fullname </th>
	<th class="text-center"> Month </th>
	<th class="text-center"> Company </th>
	<th class="text-center">Type</th>
    </tr>
	</thead>
	<tbody>
	<?php
	$i = 0;
	foreach($ListData as $key => $value){
	$i++;
	echo '<tr>';													
	echo '<td>'.$i.'.</td>';
	echo '<td>'.$value['fullname'].'</td>';
	echo '<td>'.$value['month'].'</td>';
	echo '<td>'.$ListCompany[$value['company']].'</td>';
	echo '<td>'.$ListStatementType[$value['estatement_type']].'</td>';
	echo '</tr>';
	}
	?>
	</tbody>
	</table>
</div>
</div>
</div>
Posted
Updated 13-Aug-23 0:42am

1 solution

Modify your existing HTML/PHP search page to include a link or a button that directs the user to the 'printout.php' page. Make sure it includes the necessary parameters (month and user etc.) in your query string to retrieve the specific data for the PDF.

Create the 'printout.php' page which will generate the PDF using mPDF based on the parameters from your query string. An example will look like this, you need to modify it to suit your needs -
PHP
<?php
require_once 'path/to/mpdf/vendor/autoload.php';

//Get the parameters from your query string...
$month = $_GET['month'];
$user = $_GET['user'];

//Generate the PDF content...
$mpdf = new \Mpdf\Mpdf();
//Build the PDF content/file based on your retrieved parameters...

//Save the PDF to a temp file...
$tempFilePath = 'path/to/temporary/folder/' . uniqid('pdf_temp_') . '.pdf';
$mpdf->Output($tempFilePath, 'F');

//Close your PDF object...
$mpdf->Output();

//Display success message if all went well...
echo 'PDF generated successfully.';
?>


To email the PDF as an attachment, modify your existing code in the search page to send the email with the PDF attachment after the user submits the search form. As you have not specified which mailer object/library you are using, you can use the 'Swift Mailer' library (Documentation | Swift Mailer: A feature-rich PHP Mailer[^]) for this purpose (make sure to change the settings to your own) -
PHP
//After the user submits the search form...
if (isset($_GET['btnaction']) && $_GET['btnaction'] == 'search') {
    //Your existing code...

    //Check if the user wants to send the email...
    if (isset($_GET['send_email']) && $_GET['send_email'] == 1) {
        //Send the email with the PDF attachment...
        //Change to your own configuration for Swift Mailer...
        $mailer = new Swift_Mailer($transport);
        $message = (new Swift_Message('Your Payslip'))
            ->setFrom(['your@example.com' => 'Your Name'])
            ->setTo([$Receiver])
            ->setBody('Please find your payslip attached.')
            ->attach(Swift_Attachment::fromPath($tempFilePath));
        $result = $mailer->send($message);

        //Check if the email was sent successfully...
        if ($result) {
            //Display success message...
            echo 'Email sent successfully.';
        } else {
            //Display error message...
            echo 'Failed to send email.';
        }

        //Unlink (delete) the temporary PDF file...
        unlink($tempFilePath);
    }
}


Note that Swift Mailer will not be maintained much longer, maybe have a look at using PHPMailer as the built-in email function - How to Send Emails in PHP Using PHPMailer Library[^]

Your code will then be like (change settings...) -
<?php
//Include mPDF and PHPMailer libraries...
require_once 'path/to/mpdf/vendor/autoload.php';
require 'path/to/PHPMailer/PHPMailerAutoload.php';

//Retrieve parameters from the query string...
$month = $_GET['month'];
$user = $_GET['user'];

//Generate the PDF content using mPDF...
$mpdf = new \Mpdf\Mpdf();
//Build the PDF content/file based on your retrieved parameters...

//Save the PDF to a temporary file...
$tempFilePath = 'path/to/temporary/folder/' . uniqid('pdf_temp_') . '.pdf';
$mpdf->Output($tempFilePath, 'F');

//Send the email with the PDF attachment...
$mail = new PHPMailer;
$mail->isSMTP();
$mail->Host = 'smtp.example.com';  //Your SMTP server...
$mail->SMTPAuth = true;
$mail->Username = 'your@example.com';  //Your SMTP username...
$mail->Password = 'your_password';  //Your SMTP password...
$mail->SMTPSecure = 'tls';  //Use TLS if required...
$mail->Port = 587;  //TLS port...

$mail->setFrom('your@example.com', 'Your Name');
$mail->addAddress($Receiver);

$mail->Subject = 'Your Payslip';
$mail->Body = 'Please find your payslip attached.';
$mail->addAttachment($tempFilePath, 'payslip.pdf');

//Send the email...
if ($mail->send()) {
    //Display success message...
    echo 'Email sent successfully.';
} else {
    //Display error message...
    echo 'Failed to send email: ' . $mail->ErrorInfo;
}

//Unlink (delete) the temporary PDF file...
unlink($tempFilePath);
?>
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900