Template Structure
Templates are simple PHP files that use a mix of HTML and PHP. Data from the n8n webhook request is passed to the PHP script, which then renders the HTML dynamically.
Here’s the basic structure of a template file (e.g., invoice.php
):
php
<?php
// Get the JSON data from the request body
$data = json_decode(file_get_contents('php://input'), true);
// Extract variables for easier use in HTML
$invoiceNumber = $data['invoiceNumber'];
$clientName = $data['clientName'];
$items = $data['items'];
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Invoice #<?php echo htmlspecialchars($invoiceNumber); ?></title>
<style>
body { font-family: sans-serif; }
.container { width: 800px; margin: 0 auto; }
h1 { color: #333; }
/* Add your custom CSS here */
</style>
</head>
<body>
<div class="container">
<h1>Invoice</h1>
<p><strong>Invoice Number:</strong> <?php echo htmlspecialchars($invoiceNumber); ?></p>
<p><strong>Client:</strong> <?php echo htmlspecialchars($clientName); ?></p>
<h2>Items</h2>
<table>
<thead>
<tr>
<th>Description</th>
<th>Quantity</th>
<th>Price</th>
</tr>
</thead>
<tbody>
<?php foreach ($items as $item): ?>
<tr>
<td><?php echo htmlspecialchars($item['description']); ?></td>
<td><?php echo htmlspecialchars($item['quantity']); ?></td>
<td>$<?php echo htmlspecialchars($item['price']); ?></td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
</body>
</html>
Creating a New Template
To create a new PDF template, follow these steps:
- Create a new PHP file in the
./templates/
directory (e.g.,certificate.php
). - Add your HTML and CSS. This content will form the visual layout of your PDF. Since Gotenberg renders this HTML, you can use modern CSS to style the document.
- Use PHP to embed dynamic data.
- The webhook data is available as a JSON string in the request body. You must first decode it using
json_decode(file_get_contents('php://input'), true)
. - Access the data using array keys, like
$data['key']
. - Always use
htmlspecialchars()
when echoing data to prevent XSS (Cross-Site Scripting) vulnerabilities. - Use PHP control structures like
foreach
to loop through arrays (e.g., a list of invoice items).
Using a New Template in n8n
After creating your new template file, you need to update the n8n workflow to use it.
- Open the n8n workflow in your browser.
- Find the HTTP Request node that sends the data to the Gotenberg service.
- Update the URL. Change the URL to point to your new template file. For example, if your new file is
certificate.php
, the URL will behttp://nginx/certificate.php
. The namephp
is the service name defined indocker-compose.yml,
allowing the n8n container to communicate with the PHP-FPM container.
By following these steps, you can create a wide variety of professional and branded PDF documents.