📅  最后修改于: 2023-12-03 15:20:41.748000             🧑  作者: Mango
In web development, there may be instances when we need to generate PDF files from HTML templates. Twig is a popular template engine in PHP that allows developers to build flexible and efficient templates. In this article, we will explore how to generate PDFs from Twig templates using popular PHP libraries.
Before we dive into the code, let's first ensure that we have the following prerequisites:
In this tutorial, we will be using the knplabs/knp-snappy
library to generate the PDFs. It uses wkhtmltopdf
or wkhtmltoimage
, a powerful command-line tool, to generate PDFs from HTML. To install this library, we need to add it to our project via Composer:
composer require knplabs/knp-snappy
Let's create a Twig template that we will use to generate the PDF. We will create a simple template that displays the name of a person and their email address.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>PDF Example</title>
</head>
<body>
<h1>{{ name }}</h1>
<p>Email: {{ email }}</p>
</body>
</html>
Now that we have our template, we can generate a PDF from it using the Knp\Snappy\Pdf
class from the knplabs/knp-snappy
library.
require 'vendor/autoload.php';
use Knp\Snappy\Pdf;
$pdf = new Pdf();
$pdf->setOption('encoding', 'utf-8');
$pdf->setOption('margin-top', '10mm');
$pdf->setOption('margin-bottom', '10mm');
$pdf->setOption('margin-left', '10mm');
$pdf->setOption('margin-right', '10mm');
$html = $twig->render('template.twig', [
'name' => 'John Doe',
'email' => 'john.doe@example.com'
]);
$pdf->generateFromHtml($html, 'example.pdf');
echo 'PDF generated!';
Let's go over the above code:
Knp\Snappy\Pdf
class.Pdf
class and set some options like encoding and margins. We can add any option that wkhtmltopdf
command-line tool accepts.generateFromHtml
method with the HTML and the output filename.In this tutorial, we learned how to generate PDFs from Twig templates in PHP using the knplabs/knp-snappy
library. We first installed the required library via Composer and created a simple Twig template. We then used the Knp\Snappy\Pdf
class to generate a PDF from the template.