Using knp-snappy in WordPress themes to generate PDF files and send them to clients
In developing a WordPress-based CRM systemtime, there is a need to generate a PDF file based on the information provided by the user, and sent by e-mail to the customer. Have not done friends may think that this is a more troublesome requirements, in fact, we split this requirement to do, it is very simple, first of all, to obtain user information, and then use the user information to generate PDF files, and then finally the generated PDF files sent to customers via Email on it.
knp-snappy is a PHP library that helps us generate PDFs from URLs or HTML files, and relies on the wkhtmltopdfIf you don't have it installed on your operating system, just follow the instructions in the previous URL to install it. After installation, we install it through Composer and then include the autoload files generated by Composer into the theme or plugin.
composer require knplabs/knp-snappyGenerating PDF files with knp-snappy
First, we need to specify the location of the generated PDF file is saved, and then specify the HTML file or string used to generate the URL file. With these two pieces of information, call the corresponding method of knp-snappy can generate PDF files.
use KnpSnappyPdf; } } } } } } } } } } } } }
use WenpriseFacadesView.
// Generated PDF file
$file = WP_CONTENT_DIR . '/pdf/register-' . $client->ID . '.pdf';
// If the file already exists, delete the file and regenerate it
if (file_exists($file)) {
unlink($file);
}
// The HTML file used to generate the PDF file
$html = View::make($view)->with($data);
// Start generating PDF files with knp-snappy
$snappy = new Pdf('/usr/local/bin/wkhtmltopdf');
try {
$snappy->generateFromHtml($html, $file);
} catch (Exception $e) {
}The View class in the above code is a method in our MVC framework, you can replace it with your own function, or you can generate the PDF directly from the URL, for details on how to use it, see knp-snappy 使用文档。
Send the generated PDF file via e-mail
The generated file is saved in the location we specified in the code. Generate PDF files, use WordPress built-in wp_mail function to send can be. Get the user's e-mail, set the title of the mail, the content of the method is very simple, WordPress official also introduced, here will not say more.
wp_mail($to, $subject, $message, $headers, [$file]);请注意文件安全
In order to prevent the leakage of PDF files, we need to take some security measures, such as randomly generated PDF file names, through the Ngnix settings, prohibit users from downloading PDF files, or mail sent directly after the deletion of PDF files and so on.