While building a CRM system on top of WordPress, one of the requirements was to generate a PDF file from user-provided information and send that PDF to the client by email. At first glance that sounds complicated, but the workflow is actually simple if we split it into steps: get the data, generate the PDF, then email the generated file.
knp-snappy is a PHP library that can generate PDF files from a URL or from HTML. It depends on wkhtmltopdf, so that binary must be installed on the operating system first. After that, install the PHP library with Composer and include Composer’s autoloader in your theme or plugin.
composer require knplabs/knp-snappy
Generate a PDF file with knp-snappy
First, define where the generated PDF should be stored and prepare the HTML or URL that will be converted into the PDF. Once you have those two pieces of information, you can call the appropriate knp-snappy method.
use KnpSnappyPdf;
use WenpriseFacadesView;
// Generated PDF file path.
$file = WP_CONTENT_DIR . '/pdf/register-' . $client->ID . '.pdf';
// If the file already exists, remove it and regenerate it.
if ( file_exists( $file ) ) {
unlink( $file );
}
// HTML used to generate the PDF.
$html = View::make( $view )->with( $data );
$snappy = new Pdf( '/usr/local/bin/wkhtmltopdf' );
$snappy->generateFromHtml( $html, $file );
The View class in that example comes from our own MVC layer, so you can replace it with your own rendering function. You can also generate a PDF directly from a URL if that better suits the project. For the full range of options, refer to the official knp-snappy documentation.
Send the generated PDF by email
After the file has been generated and stored in the path you defined, you can send it with WordPress’s built-in wp_mail() function. Getting the recipient address, subject, and message body is straightforward, so the attachment step is the important part here.
wp_mail( $to, $subject, $message, $headers, [ $file ] );
Pay attention to file security
Generated PDF files often contain sensitive customer data, so you should not leave them exposed casually. It is worth taking some extra precautions, such as generating random PDF file names, preventing direct download through Nginx rules, or deleting the PDF immediately after it is emailed.
