Nova Framework

MPDF is my go to library when I need to generate a PDF using PHP. It’s perfect for taking a html/php page and outputting that to a PDF.

To install the package add this to the composer.json file:

"mpdf/mpdf": "^6.1" 

This will install MPDF into the vendor directory.

To use it import the namespace:

use mPDF;

Then create a method that will use the library, in this example all records from a contacts model is added to $contacts then it’s passed to a view using View::fetch to return the contents of the view instead of outputting it.

It’s worth noting this example View::fetch is coming from a module called Contacts if running from a app/Controllers/ namespace then the third parameter is not needed.

The contents of the View is a regular HTML marked up page, it can contain both HTML and PHP.

Once the body is set create a new PDF by calling new mPDF() the parameters inside mPDF() are not required but find these are needed in most cases to have the page layout and padding setup.

To add the html to the PDF using ->WriteHTML() another optional item is using ->setFooter() to add a footer the bottom of the pages.

Finally to save the PDF call ->Output() give it a name in this case I set a name and add a date and time to filename to ensure it’s always unique. The last option ‘D’ set this to force a download.

public function pdf()
    //fetch records
    $contacts = Contacts::all();

    //fetch view contents from a module called Contacts
    $body = View::fetch('Contacts/Pdf', ['contacts' => $contacts], 'Contacts');

    //generate the PDF
    $mpdf= new mPDF('utf-8', 'A4', '', '', 5, 5, 5, 5, 0, 0);
    $mpdf->setFooter("© ".Config::get('').' - '.date('Y')." - Private & Confidential.");
    $mpdf->Output("contacts-".date('Y-m-d-h-i-s').'.pdf', 'D');