📜  twig to pdf - PHP (1)

📅  最后修改于: 2023-12-03 15:20:41.748000             🧑  作者: Mango

Twig to PDF in PHP

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.

1. Requirements

Before we dive into the code, let's first ensure that we have the following prerequisites:

  • PHP (version 5.6 or higher)
  • Composer
  • A project directory to work with
2. Dependencies

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
3. Twig Template

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>
4. Generate PDF

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:

  • We first require the Composer autoload file and import the Knp\Snappy\Pdf class.
  • We instantiate the Pdf class and set some options like encoding and margins. We can add any option that wkhtmltopdf command-line tool accepts.
  • We then render the Twig template with the data and retrieve the HTML.
  • Finally, we call the generateFromHtml method with the HTML and the output filename.
Conclusion

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.