When developing a CRM system based on WordPress, a requirement arose to generate a PDF file based on information provided by the user and send it to the customer via email. Friends who haven’t done this might think it’s a relatively troublesome requirement, but in fact, if we break this requirement down, it’s quite simple: first, get user information, then use that information to generate a PDF file, and finally send the generated PDF file to the customer via Email.
knp-snappy is a PHP library that can help us generate PDFs from URLs or HTML files. This library relies on wkhtmltopdf; if it’s not installed in the operating system, just install it according to the instructions at the previous address. After installation, we install it via Composer and then include the Composer-generated autoload file into our theme or plugin.
composer require knplabs/knp-snappy
Generating PDF Files Using knp-snappy
First, we need to specify where the generated PDF file will be saved, and then specify the URL file or HTML file/string used for generation. With these two pieces of information, calling the corresponding method of knp-snappy can generate the PDF file.
use KnpSnappyPdf;
use WenpriseFacadesView;
// The generated PDF file
$file = WP_CONTENT_DIR . '/pdf/register-' . $client->ID . '.pdf';
// If the file already exists, delete it and regenerate
if (file_exists($file)) {
unlink($file);
}
// The HTML file used to generate the PDF
$html = View::make($view)->with($data);
// Start using knp-snappy to generate the PDF file
$snappy = new Pdf('/usr/local/bin/wkhtmltopdf');
try {
$snappy->generateFromHtml($html, $file);
} catch (Exception $e) {
}
The View class in the code above is a method in our MVC framework; you can replace it with your own function, or you can generate the PDF directly from a URL. For specific usage, please refer to the knp-snappy documentation.
Sending the Generated PDF File via Email
The generated file is saved at the location we specified in the code. After generating the PDF file, just send it using WordPress’s built-in wp_mail function. Getting the user’s email, setting the email subject, and content is very simple; it’s also introduced on the official WordPress site, so I won’t say much here.
wp_mail($to, $subject, $message, $headers, [$file]);
Please Pay Attention to File Security
To prevent PDF file leakage, we need to take some security measures, such as randomly generating PDF filenames, setting via Nginx to prohibit users from downloading PDF files, or directly deleting the PDF file after sending the email, etc.
