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
require_once 'path/to/mpdf/vendor/autoload.php';
$month = $_GET['month'];
$user = $_GET['user'];
$mpdf = new \Mpdf\Mpdf();
$tempFilePath = 'path/to/temporary/folder/' . uniqid('pdf_temp_') . '.pdf';
$mpdf->Output($tempFilePath, 'F');
$mpdf->Output();
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) -
if (isset($_GET['btnaction']) && $_GET['btnaction'] == 'search') {
if (isset($_GET['send_email']) && $_GET['send_email'] == 1) {
$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);
if ($result) {
echo 'Email sent successfully.';
} else {
echo 'Failed to send email.';
}
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
require_once 'path/to/mpdf/vendor/autoload.php';
require 'path/to/PHPMailer/PHPMailerAutoload.php';
$month = $_GET['month'];
$user = $_GET['user'];
$mpdf = new \Mpdf\Mpdf();
$tempFilePath = 'path/to/temporary/folder/' . uniqid('pdf_temp_') . '.pdf';
$mpdf->Output($tempFilePath, 'F');
$mail = new PHPMailer;
$mail->isSMTP();
$mail->Host = 'smtp.example.com';
$mail->SMTPAuth = true;
$mail->Username = 'your@example.com';
$mail->Password = 'your_password';
$mail->SMTPSecure = 'tls';
$mail->Port = 587;
$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');
if ($mail->send()) {
echo 'Email sent successfully.';
} else {
echo 'Failed to send email: ' . $mail->ErrorInfo;
}
unlink($tempFilePath);
?>