/    Sign up×
Articles /Pin to ProfileBookmark

How To Let Users Create Dynamic PDFs In WordPress

Whether you want to sell personalized PDF documents on your website, you want to drive traffic to your website by offering some type of PDF that users can customize, or any other creative ideas you can come up with to take advantage of this functionality, there is a great way to do it using a combination of high-quality plugins: Gravity Forms and Gravity PDF. Depending on how creative you want to get with this, combined with your chops as a developer, you can go even farther in creating completely custom templates for the PDFs you offer. In this article, I’m going to show you how to create a custom business card PDF template from a simple form.

Gravity Forms Overview

If you’re not already familiar with Gravity Forms, it is a highly extensible form plugin that is considered to be one of the top in its field. Forms can be easily created, edited, and styled with a drag and drop builder on the back end, along with countless integrations for payments, newsletter signups, and much more. It is a premium plugin, meaning you can’t use it for free, but with pricing plans starting at $59/year, it is worth every penny, in my opinion.

Gravity PDF Overview

Gravity PDF is a certified add-on for Gravity Forms. It provides the capability to take form submissions and convert them into customizable PDFs – like magic! While there are pricing plans to upgrade their offering with templates and other add-ons, the base plugin is free, and that is all we will need since we’re going to be creating a custom template ourselves.

Getting Started

Of course we start by installation and initial setup of both of these plugins. Head over to https://www.gravityforms.com/ and https://wordpress.org/plugins/gravity-forms-pdf-extended/ to download your plugins, and then install them on your WordPress site. Setup instructions for Gravity Forms are here, and for Gravity PDF here. I won’t regurgitate the setup, but both plugins are relatively quick and easy to get ready to go. You’ll have to download/install the core fonts that come with Gravity PDF, but once that’s completed we can move forward.

One of the nice features of Gravity PDF is that you can use your own fonts, so let’s head over to Google Fonts and download the Akshar font family. Extract the file and navigate to the static folder to find the .ttf files. Now, in the WordPress back end, go to Forms > Settings and click on the PDF tab on the left. In the Fonts meta box, click the button labeled Manage. This will open a window to add our new fonts.

Gravity PDF Font Manager

Type “Akshar” into the font name field, then click the plus sign to upload the Regular font and the Bold font. We’ll use the Light version for the regular font, and the Semibold version for the Bold font. Click the blue button labeled Add Font, then close the window. (You can use any .ttf font you want – we’re just using Akshar for our example.) Now that we have our custom font installed, we can start creating the form and the template.

Creating The Form

We’re going to use this template found over on Zazzle to model our business card template, so we need to create the corresponding form fields for the user’s information to be entered.

Business card Template

  1. In the WordPress back end, navigate to Forms > New Form, then give it a name and click the button labeled Create Form.
  2. In the right sidebar, click on Advanced Fields and then drag the File Upload field to the left.
  3. Hover over the newly created File field and click on the settings icon.
  4. Return to the right sidebar, change the Field Label to say “Logo” and enter the various image file extensions (jpg, gif, jpeg, png) in the field labeled Allowed file extensions.
  5. Click on the tab in the right sidebar labeled Add Fields, then drag the Name field to the left and drop it under the Logo field.
  6. Click on the Advanced Fields tab to close it, then drag the Single Line Text field to the left and drop it under the Name field.
  7. Hover over the newly created Single Line Text field and click on the settings icon.
  8. Change the Field Label to read “Title or Company”.
  9. Repeat the process to add an Address field, Phone field, Email field, and two Website fields for Instagram and Facebook URLs, all found in the Advanced Fields section. You can adjust the settings for each as needed based on your locale and use case.
  10. Click the blue button in the top right labeled Save Form to save your work.

Creating The PDF Template

Custom Gravity PDF templates are stored in the /wp-content/uploads/PDF_EXTENDED_TEMPLATES/ directory, while the templates included with the plugin are stored in the /wp-content/plugins/gravity-forms-pdf-extended/src/templates/ directory, so the simplest way to get started is to grab the blank-slate.php template from the latter directory and copy it into the PDF_EXTENDED_TEMPLATES directory. This will be what we start our template with.

  1. Open the template file in your code editor of choice and edit the first few lines as you see fit, changing the Template Name, Version, Description, Author, and Author URI, for example. Other than the template name, these edits are primarily for your own reference. The Group name determines where you will find the template in the plugin settings, but you can leave it set to “Core” if you want.
  2. Now, in the WordPress back end, you can navigate to Forms > Settings > PDF and select your new template in the dropdown under Default Template.
  3. In the dropdown under Default Paper Size, select Custom Paper Size and set the Width to 94mm and the Height to 56mm (standard business card size + 5mm to allow for bleed), then scroll to the bottom and save your settings.
  4. Now navigate to Forms, hover over the name of the form we created, then hover over Settings and click on PDF.
  5. You will see the message “This form doesn’t have any PDFs. Let’s go create one.” Click on it and set a Label and Filename (required), toggle the Show Form Title to not display, and make any other adjustments you’d like, then click the blue button labeled Add PDF.
    *Note: when setting the Filename, you can use Gravity Forms’ built in merge tags to make each filename unique. Just click on the brackets icon at the top right of the filename field and select Name (First), type an underscore, select Name (Last), and then an underscore and your preferred filename. Example: {Name (First):1.3}_{Name (Last):1.6}_bizcard
  6. Now create a new page in WordPress and add the form shortcode to the page using the Add Form button. View the page on the front end, fill out, and then submit the form.
  7. In the back end, navigate to Forms > Entries, then hover over the form entry you just submitted and click on View PDF.

In the new window you will see the PDF with all of the information provided, albeit not very nice looking, which shows us everything we’ve done so far is working! Now that we know we are correctly generating a PDF from a form submission, we have to customize the template to make it look like the business card template we’ve set out to accomplish.

Coding The PDF Template HTML/PHP

We’re going to create our own CSS and HTML for the template instead of modifying what’s in the blank slate. Part of the challenge with this will be that the PDF software used to generate documents, mPDF, has decent legacy HTML and CSS support, but it does have its limitations and quirks, along with the fact that we can’t inspect a PDF using Dev Tools or the like to make our adjustments in the browser. For those of you that have been coding since the early days of web design, this will be a bit of a return to those times, and also not unlike coding an HTML email. For the full documentation on supported HTML and CSS, visit mPDF.

  1. Delete everything in our template after line 33 (where the first PHP section ends.)

In order to grab form field data, we need to utilize PHP and the $form_data associative array – a processed version of the $entry object specific to Gravity PDF. So, for instance, to grab the entry from the Title or Company field, which has an ID of 4, we would use form_data['field'][4]. The ID of each form field can be found while editing the form and clicking on the settings icon for the field, then finding the ID in the right sidebar.

Since we will be accessing several fields from $form_data['field'] we are going to shorten the process by assigning a succinct variable to it.

<?php
$f = $form_data['field']; 

// Now we can access the Title or Company field as follows: 
$company = $f[4];
?>

  1. With that in mind, let’s create the variables for all of our form fields. Insert the following code just before the closing PHP tag in your template. Confirm and adjust any field IDs as necessary when comparing to your own form fields.
<?php
$f = $form_data['field'];

$logo = $f['1_path']; /* This is the format to retrieve the image URL */
$first_name = $f[3]['first']; /* This is the format to retrieve specific subfields within a multiline field */
$last_name = $f[3]['last'];
$company = $f[4];
$street = $f[5]['street'];
$street_two = $f[5]['street2'];
$city = $f[5]['city'];
$state = $f[5]['state'];
$zip = $f[5]['zip'];
$country = $f[5]['country'];
$phone = $f[6];
$email = $f[7];
$ig = $f[8];
$fb = $f[9];
?>
  1. Next we create the HTML for our layout, just below the closing PHP tag in the template. Since this will not actually be a web page, we don’t need to be concerned about using current standards, accessibility, etc. Just straight HTML with classes we can style. Feel free to use your own variations that you may be comfortable with, but keep in mind that we are somewhat restricted to tables and/or floats for the layout.

<!doctype html>
<html <?php language_attributes(); ?>>
    <head>
        <style>
        /* CSS styles will go here */

        </style>
    </head>
    <body>
        <div class="left-col">
            LOGO
            NAME
            COMPANY
        </div>
        <div class="right-col">
            ADDRESS
            PHONE
            EMAIL
            IG
            FB
        </div>
    </body>
</html>


  1. Replace the LOGO placeholder text with the following code. Note that this is a bit more complex for images than the other fields.
<?php
if( $logo ) {
    if ( is_array( $logo ) ) {   
        $allowed_extensions = array( 'gif', 'jpg', 'jpeg', 'png' );

        foreach ( $logo as $path ) { 
            $extension = strtolower( pathinfo( $path, PATHINFO_EXTENSION ) );

            if( in_array( $extension, $allowed_extensions ) && is_file( $path ) ) { /* verify path has an image extension and it exists on the server */
echo '<img class="logo" src="'.$path.'" />';
            }
        }
    }
}
?>
  1. Replace the NAME and COMPANY placeholder text with the following:
<?php 
if( $first_name || $last_name ) echo '<div class="name">'.$first_name.' '.$last_name.'</div>'; 
if( $company ) echo '<div class="company">'.$company.'</div>'; 
?>

Now that our left column is done, let’s review what we’ve done so far.

For each field, we start with a check to make sure it’s not empty, in case we have not made these fields required in the form. Then we proceed with displaying each field value within a div with a CSS class so we can style each one specifically as needed. The logo is a bit more complex because we want to make sure we’re pulling the URL for an image upload and not some other type of file, plus we’re getting the URL from the array that the file upload records when it is submitted.

Now let’s move on to the right column. These fields are pretty straightforward based on the fields we’ve already coded, so for brevity’s sake we’ll replace all of the text placeholders with the following code.

<?php 
if( $street ) echo '<div class="street">'.$street.'</div>'; 
if( $street_two ) echo '<div class="street-two">'.$street_two.'</div>'; 
if( $city || $state ) echo '<div class="city">'.$city.' '.$state.'</div>'; 
if( $zip ) echo '<div class="zip">'.$zip.'</div>'; 
if( $phone ) echo '<div class="phone">'.$phone.'</div>'; 
if( $email ) echo '<div class="email">'.$email.'</div>'; 
if( $ig ) echo '<div class="ig">'.$ig.'</div>';
if( $fb ) echo '<div class="fb">'.$fb.'</div>';
?>

At this point, you can check your work by returning to the WordPress back end, navigating to Forms > Entries, then hovering over the form entry you just submitted and clicking on View PDF. Or you can just refresh the browser if you still have the PDF open. It still won’t be laid out the way we want, but you should be able to see that every field value is being pulled into the PDF.

Styling The PDF Template CSS

In our final step, we’re going to add the CSS styles to finish off the template and make it look exactly the way we want it to look. After each step feel free to reload your PDF to see the changes you’ve made.

  1. Add the following CSS in between the style tags in the head of the template.

body {
    font-size:9px;
    letter-spacing:0.5px;
    line-height:1.1;
    text-transform:uppercase;
}
.left-col {
    border-right:1px solid #000;
    float:left;
    text-align:center;
    width:40%;
}
.right-col {
    float:right;
    width:58%;
} 
  1. We need to make the logo smaller so everything will fit on the page.

img.logo {
    height:auto;
    margin:0 auto 20px;
    max-width:60%;
}
  1. Now we adjust the font size of the first and last names to make that line larger, as well as make it bold. Note that we can’t use a numeric font weight due to the limitations of the PDF plugin, but since we uploaded the semibold version of the font as the bold version in the backend, using ‘bold’ will render it correctly.

.name {
    font-size:12px;
    font-weight:bold;
    margin-bottom:5px;
}

Finally, we need to add the icons to the right column. There are a multitude of ways we could do this, but I’m just going to use the fabulous and free Font Awesome SVG library to accomplish this task.

  1. Go to https://fontawesome.com/icons/ and search for Home or House
  2. Click the button labeled Free in the left menu to filter the icons to the free license, then click on the home icon you’d like to use
  3. Click on the download icon in the upper right of the popup that appears to download the SVG file
    Font Awesome download
  4. Create a new subdirectory in your /wp-content/uploads/PDF_EXTENDED_TEMPLATES/ for images (I named mine ‘img’) and move the downloaded SVG file into it.
  5. Add the following CSS in your custom template. Note the <?= __DIR__; ?> constant that references the current absolute path to the current file.

.right-col div {
    padding:0 0 10px 30px;
}
.street {
    background:url(<?= __DIR__; ?>/img/home.svg) no-repeat 6px top;
    background-size:36px;
}

Refresh your PDF view and voila! You should see your home icon next to your top line in the right hand column.

Now repeat those steps for the remaining lines, with phone, email, Instagram, and Facebook icons for their corresponding lines. The additional CSS should look something like below. I shortened and simplified my icon file names, so adjust them in your code if yours are different.


.phone {
    background:url(<?= __DIR__; ?>/img/phone.svg) no-repeat 6px top;
    background-size:36px;
}
.email {
    background:url(<?= __DIR__; ?>/img/email.svg) no-repeat 6px top;
    background-size:36px;
}
.ig {
    background:url(<?= __DIR__; ?>/img/instagram.svg) no-repeat 6px top;
    background-size:36px;
}
.fb {
    background:url(<?= __DIR__; ?>/img/facebook.svg) no-repeat 6px top;
    background-size:36px;
}

Refresh your PDF view one more time to see your completed work! You may need to make some minor adjustments to your CSS to make it perfect, along with other things you may want to do, like strip the https:// from the social account URLs, but I’ll leave that to you to play around with as you make it your own.

Wrapping Up

While this has been a somewhat long and detailed tutorial, it is a simple example of what can be done using Gravity Forms and Gravity PDF together. Letting your website users generate PDF documents by filling out a form could be used to generate traffic to your website with what you’re offering, provide a service, or a multitude of other ideas you can come up with. I hope this tutorial has been helpful in getting you started on your way with the concept.

CSSHTMLPHPWordPress
×

Success!

Help @bkmacdaddy spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 4.26,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...