Official Resources
Advantages Over Other Libraries
Compared to libraries like TCPDF, mPDF offers better support for complex table layouts and CSS styling, making it ideal for generating contracts or other structured documents. It also handles Chinese characters well and generates smaller PDF files compared to alternatives.
Requirements
mPDF 7.0 requires:
- PHP version ^5.6 || ~7.0.0 || ~7.1.0 || ~7.2.0
- Extensions: mbstring and gd
- Optional extensions for advanced features: zlib, bcmath, xml
Enstallation
The recommended installation method is via Composer:
$ composer require mpdf/mpdf
Basic Usage
Here's a simple example of using mPDF:
<?php
require_once __DIR__ . '/vendor/autoload.php';
$pdfGenerator = new \Mpdf\Mpdf();
$pdfGenerator->WriteHTML('<h1>Hello world!</h1>');
$pdfGenerator->Output();
This will output the PDF inline as an application/pdf content type.
Configuration
All configuration options can be set through the constructor's $config parameter. For instance, setting a custom temporary directory:
<?php
$pdfGenerator = new \Mpdf\Mpdf(['tempDir' => __DIR__ . '/tmp']);
Advanced Example
Below is an example that demonstrates more advanced usage, including embedding images and handling tables:
<?php
use Mpdf\Mpdf;
$pdfGenerator = new Mpdf([
'mode' => 'utf-8',
'format' => 'A4',
'default_font_size' => 16,
'margin_left' => 10,
'margin_right' => 10,
'margin_top' => 15,
'margin_bottom' => 1,
]);
$pdfGenerator->SetDisplayMode('fullpage');
$pdfGenerator->autoScriptToLang = true;
$pdfGenerator->autoLangToFont = true;
$sealImage = 'images/seal/150.png';
$pdfGenerator->WriteHTML($htmlContent);
$pdfGenerator->Image($sealImage, 140, 200);
$pdfGenerator->Output('output.pdf', 'I'); // 'D' for download
Sample HTML for Contract
Here’s an excerpt of the HTML used to generate a contract:
<table style="border-collapse: collapse; width: 900px; font-family: 宋体;">
<tr>
<td colspan="8" style="font-weight: bold; font-size: 40px; text-align: center;">购 销 合 同</td>
</tr>
<tr>
<td colspan="8"> </td>
</tr>
<tr>
<td colspan="4">买方:{buyer_company_name}</td>
<td colspan="2" style="text-align: right;">合同编号:</td>
<td colspan="2">{order_key}</td>
</tr>
...
</table>
PHP 7 Compatibility
In PHP 7, constructors with the same name as their class are deprecated. To resolve this issue in mPDF, rename the constructors to __construct in the following files:
- mpdf/mpdf.php
- mpdf/classes/grad
- mpdf/classes/mpdfform
- mpdf/classes/cssmgr
After making these changes, the library should work without deprecation warnings.
Function Parameters
The mPDF constructor accepts several parameters for customization:
$pdfGenerator = new Mpdf(
$mode='utf-8',
$format='A4',
$default_font_size=0,
$default_font='',
$mgl=15,
$mgr=15,
$mgt=16,
$mgb=16,
$mgh=9,
$mgf=9,
$orientation='P'
);