April 29, 2020

Password protecting GravityPDF generated PDFs without storing password in database

Password protecting GravityPDF generated PDFs without storing password in database

The Problem

I have recently had the opportunity to work with the plugin GravityPDF. GravityPDF (GFPDF) is a free WordPress plugin providing PDF generation from Gravity Form entries, and a bunch of other features—definitely check it out if you use Gravity Forms.

One of the features that I like about GFPDF is that it offers the option to offer light encryption (128-bit, the maximum supported by the underlying mPDF library) for password-protected PDFs. Unfortunately, as I was evaluating the plugin, it looks like the passwords used to encrypt the PDFs are stored in plain text in the database.

Storing passwords in database is something I try to avoid, so while the feature set of GFPDF was almost exactly what I needed, I needed to find a different method of handling the password.

The Solution

After looking at several options, the simplest seemed to be to take advantage of a filter hook provided by Gravity Froms, gform_replace_merge_tags. GFPDF allows you to use a merge tag in the password setting.

wp-config.php Setup

For simplicity’s sake, lets say I defined the master password for my PDFs in my WordPress installation’s config.php file. We can then use that constant in our filter hook. This file contains all sorts of sensitive information about your WordPress installation, so if it’s not safe there—you might have other problems.

define('GFPDF_SECRET', 'correct horse battery staple');

Do not use the above for a password, obviously.


In the form I am targeting I selected the Advanced tab in the PDF section of Settings.

As you can see, I chose not to use a merge tag, but instead set a “password” that looks kind of like a merge tag, so now all I have to do is replace {pdf_password} with the password I wish to use in the filter hook.

The Filter Hook

add_filter( 'gform_replace_merge_tags', 'gfpdf_custom_password', 10, 7 );
function gfpdf_custom_password( $text, $form, $entry, $url_encode, $esc_html, $nl2br, $format ) {

$custom_merge_tag = '{pdf_password}';

if ( strpos( $text, $custom_merge_tag ) === false ) {
return $text;

$text = str_replace( $custom_merge_tag, GFPDF_SECRET, $text );

return $text;

The function is simple.

  1. Define our custom merge tag.
  2. Check if it’s in our string.
  3. If it is, replace it with the password in the GFPDF_SECRET constant we defined earlier.
  4. Return text for further processing.


It didn’t take long, and it wasn’t overly complicated. Certainly more could be done to make the password more secure, like retrieving the password from an environment variable, but we would also want to do that with the rest of our wp-config file, as well.