Howto center text vertically and horizontally on a single page in mpdf
(I know the answer, stackoverflow just makes me write a longer question to be allowed to post it with my answer here ...)
While mpdf supports some css, a couple of things that would allow you to center via CSS are not working:
display: flex
is not working<table>
with height: 100%
is not working<div style="position: absolute; top: 50%; left: 50%;"></div>
is not workingBut, I did find one trick: $mpdf->hPt
and $mpdf->wPt
return the pages dimensions in points.
Which means you can use a table cell with height: {$mpdf->hPt}pt; vertical-align: middle; text-align: center;
:
$mpdf = new \Mpdf\Mpdf($options);
$h = $mpdf->hPt;
$w = $mpdf->wPt;
$html = <<<HTML
<html>
<body style="margin: 0; padding: 0;">
<table style="width: {$w}pt; margin: 0; padding: 0;" cellpadding="0" cellspacing="0">
<tr>
<td style="height: {$h}pt; text-align: center; vertical-align: middle; padding: 0px 5px; margin: 0;">
Hello World
</td>
</tr>
</table>
</body>
</html>
HTML;
$mpdf->WriteHTML($html);
Obviously, using the dpi to calculate that value yourself would be an option, but using mpdfs calculation ensures you have the same rounding and handling of edge cases.