How to Generate PDFs in PHP 8.2 Using mPDF Library – Step by Step Guide
Welcome back to CodeWithTanveer, your go-to platform for coding tutorials and tips! Today, we’ll learn how to generate PDF files in PHP 8.2 using the mPDF library. PDF generation is a common requirement in web applications, whether for invoices, reports, or downloadable content. The mPDF library makes this process simple and efficient.
In this guide, we’ll walk through the installation, configuration, and implementation of mPDF in PHP 8.2. Let’s get started!
Prerequisites
Before we begin, ensure you have:
- PHP 8.2 installed
- Composer (for dependency management)
- A web server (Apache, Nginx, or PHP built-in server)
Step 1: Install mPDF via Composer
First, we need to install the mPDF library using Composer. Open your terminal or command prompt and navigate to your project directory. Run the following command:
composer require mpdf/mpdf
This will download and install the latest version of mPDF along with its dependencies.
Step 2: Create a Basic PDF Generation Script
Now, let’s create a PHP script to generate a simple PDF.
- Create a new file called
generate_pdf.php
. - Add the following code:
<?php
require_once __DIR__ . '/vendor/autoload.php'; // Include Composer autoloader
// Create new mPDF instance
$mpdf = new \Mpdf\Mpdf();
// PDF content
$html = '
<h1 style="color: #0066cc;">Welcome to CodeWithTanveer!</h1>
<p>This is a sample PDF generated using mPDF in PHP 8.2.</p>
<ul>
<li>Step-by-step guide</li>
<li>Easy to implement</li>
<li>Customizable PDFs</li>
</ul>
';
// Write HTML content to PDF
$mpdf->WriteHTML($html);
// Output the PDF
$mpdf->Output('sample_document.pdf', \Mpdf\Output\Destination::DOWNLOAD);
?>
Explanation:
- We include the Composer autoloader to load mPDF.
- Initialize a new
mPDF
object. - Define HTML content that will be converted to PDF.
- Use
WriteHTML()
to parse the HTML into PDF format. - Finally,
Output()
generates the PDF and forces a download.
Step 3: Customizing the PDF
mPDF allows extensive customization. Let’s modify our script to include:
- Custom fonts
- Page headers/footers
- CSS styling
<?php
require_once __DIR__ . '/vendor/autoload.php';
$mpdf = new \Mpdf\Mpdf([
'mode' => 'utf-8',
'format' => 'A4',
'margin_header' => 10,
'margin_footer' => 10,
]);
// Set a header
$mpdf->SetHeader('CodeWithTanveer | PDF Tutorial');
// Set a footer with page number
$mpdf->SetFooter('{PAGENO}');
// CSS styling
$stylesheet = '
body { font-family: Arial; }
h1 { color: #0066cc; }
ul { margin-left: 20px; }
';
// Add stylesheet
$mpdf->WriteHTML($stylesheet, \Mpdf\HTMLParserMode::HEADER_CSS);
// HTML content
$html = '
<h1>Custom PDF Example</h1>
<p>This PDF includes custom styling, headers, and footers.</p>
<ul>
<li>Dynamic content</li>
<li>Professional formatting</li>
<li>Easy integration</li>
</ul>
';
$mpdf->WriteHTML($html);
$mpdf->Output('custom_document.pdf', \Mpdf\Output\Destination::DOWNLOAD);
?>
Key Improvements:
- Added custom page format and margins.
- Included a header and footer.
- Applied CSS styling for better appearance.
Step 4: Generating PDF from Dynamic Data
In real-world applications, you’ll often generate PDFs from database content. Here’s an example using mock data:
<?php
require_once __DIR__ . '/vendor/autoload.php';
$mpdf = new \Mpdf\Mpdf();
// Mock data (replace with database query in real use)
$users = [
['id' => 1, 'name' => 'Tanveer', 'email' => 'tanveer@codewithtanveer.com'],
['id' => 2, 'name' => 'Alice', 'email' => 'alice@example.com'],
['id' => 3, 'name' => 'Bob', 'email' => 'bob@example.com'],
];
// Build HTML table dynamically
$html = '<h1>User Report</h1><table border="1" cellpadding="10">
<tr><th>ID</th><th>Name</th><th>Email</th></tr>';
foreach ($users as $user) {
$html .= "<tr><td>{$user['id']}</td><td>{$user['name']}</td><td>{$user['email']}</td></tr>";
}
$html .= '</table>';
$mpdf->WriteHTML($html);
$mpdf->Output('user_report.pdf', \Mpdf\Output\Destination::DOWNLOAD);
?>
Conclusion
Generating PDFs in PHP 8.2 with mPDF is straightforward and highly customizable. Whether you need invoices, reports, or certificates, mPDF provides the flexibility to create professional documents effortlessly.
Try experimenting with different styles, templates, and dynamic data to enhance your PDFs further.
For more coding tutorials, visit CodeWithTanveer and happy coding!