Generate a PDF Containing Variable Data in PHP

Information

PSPDFKit Processor has been deprecated and replaced by Document Engine. To start using Document Engine, refer to the migration guide. With Document Engine, you’ll have access to robust new capabilities (read the blog for more information).

When generating a PDF, it may not be possible to foresee all of its contents ahead of time. For that reason, we advise using a templating language such as Mustache.

Templating languages allow for the injection of data at runtime. In regard to the PDF Generation feature, this means it gives you the possibility to customize HTML before sending it along for generation. Injecting data can be useful in situations such as name and date replacement, or when generating dynamic lists in invoices.

In this guide, you’ll take the letter example from the [Creating a PDF from Scratch][creating-a-pdf] guide and implement date and name replacement with the use of Mustache in PHP. (Note {{name}} and {{date}} in the following HTML):

<!DOCTYPE html>
<head>
  ...
</head>
<html>
  <body>
    <div class="address">
      John Smith<br/>
      123 Smith Street<br/>
      90568 TA<br/>
      <br/>
      {{date}}
    </div>
    <div class="subject">Subject: PDF Generation FTW!</div>
    <div>
      <p>
        ...
      </p>
    </div>
    <div>{{name}}<br/></div>
  </body>
</html>

Next, you need to replace your template data with something real. Define the data to replace the template arguments in code, though in practice, this data may come from an external source or database.

To perform the replacement, you’ll use the Mustache.php, package which is an implementation of the Mustache templating system.

The following will open the page.mustache file (the HTML seen above) from the views directory as a template and then call render to perform the replacement of {{name}} and {{date}}, which is echoed to the command line:

$mustache = new Mustache_Engine(array(
    'entity_flags' => ENT_QUOTES,
    'loader' => new Mustache_Loader_FilesystemLoader(dirname(__FILE__).'/views')
));
$tpl = $mustache->loadTemplate('page');
echo $tpl->render(array('name' => 'John Smith', 'date' => '29 February, 2020'));

This example shows how you can use Mustache.php in PHP, although it’s worth noting that there are many other templating language alternatives that may better suit your environment.