Sunday, February 23, 2014

Tips on Creating PDF using mPDF PHP library

In this post I will describe several ways to format HTML documents that will be converted into PDF file using mPDF PHP library.

1. Change Page Orientation

Use CSS3 page and sheet-size attribute to change page orientation. 

<style type="text/css">
    .landscape {
        page: a4landscape;
    .portrait {
        page: a4portrait;

    @page a4portrait {
        sheet-size: A4;
    @page a4landscape {
        sheet-size: A4-L;

<div class="landscape"> Portrait page </div>
<div class="landscape"> Landscape page </div>

 2. Change page margins

To change page margins, you need to give additional parameter to mPDF's constructors. The page margins are in milimeters. Note the example uses Yii pdf extension instead of calling mPDF directly.

                $mPDF1 = Yii::app()->ePdf->mpdf('', 'A4',0,'',5,5);

3. Fit a table into one page

 To fit a table in entirety onto single page, we could use CSS attribute page-break-inside:avoid on the table.

<table style="page-break-inside: avoid;"> ... </table>

And you might want to enlarge the maximum shrink factor (the larger the value, the smaller we allow mPDF to shrink tables) :
                $mPDF1->shrink_tables_to_fit = 10;

4. Fit contents of a div into one page

We might need to fit not only one table but one DIV containing many tables and other tags. The DIV should be only one DIV and directly under HTML BODY.
<div style="bottom: 0; left: 0; position: fixed; right: 0; top: 0;">
</div> </body>

5. Change center to other tag with center class

The center tag is deprecated and not supported by mPDF library.
<center> This is a title </center>

should be changed onto
<div class="center"> This is another title</div>

<style type="text/css">

.center {

   text-align: center;



6. Accelerate page rendering

Sometimes mPDF takes a long time to render pages because it iteratively tries to fit elements. So you might want to change this parameter to speed things up (the normal value is 10, meaning mPDF iterates in 1/10 increments):
                $mPDF1->incrementFPR1 = 4;

No comments: