Dynamically Create A PDF Using PHP

TheDevDrawer
5 min readSep 2, 2022

In this tutorial, I am going to show you how to use PPH to dynamically create a PDF. We will be using mPDF as our generator since it has the most functionality of all of the PDF generator packages.

View This On YouTube

Download mPDF

To get started, we need to get mPDF into our project. Open your project in either a terminal or CMD and run the following composer call.

composer require mpdf/mpdf

This will add mPDF to your project under the vendor folder. From there, you need to create a index.php file and require the composer autoloader using the following code.

require_once __DIR__ . '/vendor/autoload.php';

Now that you have included the autoloader, you can simply call the mPDF class using the following code:

$mpdf = new \Mpdf\Mpdf();

This will allow you to initiate the package when you need it. You can test it by adding the following to your file:

$mpdf->WriteHTML('<h1>Hello World</h1>');
$mpdf->Output();

Now, just browse out to your website and you should see a PDf with the words Hello World on it.

Password Protection

Just in case you need it, you can add a password to your document. You can either set the password to be used when the document is viewed, printed, or saved.

To do this, you use the following function. Add it just below where the $mpdf = new \Mpdf\Mpdf(); code you wrote previously.

SetProtection ([$permissions], $user_password, $owner_password, $length)$mpdf->SetProtection([], 'UserPassword', 'MyPassword');

Your protection permissions are as follows:

'copy'
'print'
'modify'
'annot-forms'
'fill-forms'
'extract'
'assemble'
'print-highres'

Set File Properties

You can easily add or change the file properties by adding the following methods just below the $mpdf = new \Mpdf\Mpdf(); code you wrote previously or if you are using the password protection above, just below that.

$mpdf->SetTitle('The DevDrawer Is Awesome'); // add a document title
$mpdf->SetAuthor('The DevDrawer'); // add the author name

Headers and Footers

Prior to adding any content to your PDF, you may want to set up your header or footer. The standard header and footer have a line attached to them. Once you set up your header or footer you can easily remove this line.

Header:

$mpdf->defaultheaderline = 0; //remove this if you want the line
$mpdf->setHeader('|Document Title|');

Footer:

$mpdf->defaultfooterline = 0; // remove this if you want the line
$mpdf->setFooter('Document Title|{DATE F j, Y}|{PAGENO}');

In both the header and the footer, you may notice the pipe characters(|). These allow you to space out your header or footer using left, center, and right. So essentially, something like this: left|center|right.

You can also use abstract shortcodes for certain things like a date {DATE F j, Y} or page number {PAGENO}. The date uses standard PHP date formatting.

Add A Stylesheet

You can use the basic formatting of the PDF (the best way is tables blah), but you can also use inline CSS or external CSS stylesheets.

First, create your stylesheet. Keep in mind that never every style will translate well into the PDF. In our case, we will create a simple /style.css to go with our PDF.

@import url('https://fonts.googleapis.com/css2?family=Open+Sans&family=Roboto&display=swap');
body {
font-family: 'Open Sans', sans-serif;
}
h1 {
font-family: 'Roboto', sans-serif;
}
ul {
list-style-type: none;
margin:0;
padding:0;
}

Now, we can use PHP to get the stylesheet and use it on our PDF. Add the following code prior to any HTML content.

$stylesheet = file_get_contents('style.css');
$mpdf->WriteHTML($stylesheet, \Mpdf\HTMLParserMode::HEADER_CSS);

This code will get the stylesheet and add it to our header to be used with the PDF. Keep in mind that you can also use inline CSS if you need to.

Add A Watermark

Sometimes you need to watermark your documents for legal or aesthetic purposes. You can add a watermark on every page pretty easily.

$mpdf->SetWatermarkText('THE DEV DRAWER'); // set the watermark
$mpdf->showWatermarkText = true; // make it show
$mpdf->watermarkTextAlpha = .1; // set the opacity

Add A Barcode

This is a pretty cool feature if you want to add a barcode to your PDF. You could add a barcode for tracking or accounting purposes if needed.

Simply add the barcode HTML to your document and it will parse it out for you. I recommend using ISBN for common barcodes.

$mpdf->WriteHTML('<br><barcode code="123-456-7890" text="ISBN" class="barcode" />');

Using PHP to Generate HTML

You can also call a class or method that produces HTML for the PDF instead of inline like we did previously.

For example, we can create a class called Foo.php in a folder called includes. It may look something like this:

class Foo {
public function bar() {
$test = 'This is a test from a class';
$test .= '<br><img src="images/1.jpg" style="width:300px; height:auto;">';
$test .= '
<ul>
<li>Item 1</li>
<li>Item 2</li>
<li>Item 3</li>
<li>Item 4</li>
</ul>';
return $test;
}
}

Then, we can add code to our index.php file to pull in the class so we can call it:

require_once __DIR__ . '/includes/Foo.php';

Then we call it using:

$mpdf->WriteHTML((new Foo())->bar());

There, now you have HTML code coming from an external class that you can build methods around.

PDF Output

You can either display your PDF in the browser or you can save it to a folder on your server or just have it download when it is called.

The standard display of the PDF is called like we have it in the first part of this tutorial above:

$mpdf->Output();

You can add flags to this call, to make it download (D) or save to your server (F). Those options would look like this:

$mpdf->Output('filename.pdf', 'D');

or

$mpdf->Output('filename.pdf', 'F');

Keep in mind, that you can only do one of the 3 options. The first one called is the one that mPDF uses.

mPDF Documentation

You can view more about mPDF by going to their website and viewing their documentation. There are a lot of features. In this tutorial, I cover the basics and most commonly used features.

Full mPDF Documentation

Conclusion

Now you should be able to successfully make a PDF using only PHP. The more content in the PDF the longer it takes to load, but this small library is a big resource when you need to make dynamic PDFs on the fly.

--

--

TheDevDrawer
TheDevDrawer

Written by TheDevDrawer

Join me as I discuss programming in a way that can help you get started. Created based on a need I have had. Let’s get started.