Generate PDF From WordPress Post Without A Plugin – DOMPDF

WordPress Post To PDF Generator
About The Author
Cabe Nolan is the founder of WP Cover where he shares his insight into WordPress, development, & entrepreneurship. Outside of WPCover, Cabe continues to run a successful WordPress development firm, Bold City Design as well as a few high profile websites, Arrivala, Two Way Resume, Dock Skipper, and a successful outdoors brand, DolfinPack.







Generate PDF From WordPress Post Without A Plugin – DOMPDF

A client I’ve been working with for the last five years recently approached me with a new challenge.  They had over 150 posts that they wanted to generate a very custom PDF from the post content and custom fields.  I have some experience with generating a PDF document from HTML on the Two Way Resume platform but this was going to be a more customized result.  Without hesitating, I immediately accepted the challenge and began implementing what I knew and learning what I didn’t.  While this post won’t go into extreme detail I wanted to give fellow WordPress users insight on how to generate a PDF from post content & custom fields without the use of a plugin as it is actually pretty simple.

First, we’re going to leverage the DOMPDF HTML to PDF converter.  You can download a copy of DOMPDF here: https://github.com/dompdf/dompdf.  If you are familiar with Composer, it’s a fairly quick install.  Since most people on WP Cover will probably not be, I would recommend clicking the green Download button in the right corner of the Github page and downloading the ZIP file to your computer.  Once downloaded & extracted, upload the file contents to the root of your active WordPress theme.  This would be located at something like /public_html/wp-content/themes/youractivetheme/dompdf-master

Once the DOMPDF folder has uploaded to your WordPress install we’ll be ready to get started.  Open up the single.php file in your active WordPress theme directory.  At the very top of the file before calling any WordPress functions such as get_header() add the following:

 

<?php
// reference the Dompdf namespace
use Dompdf\Dompdf;
if( 'POST' == $_SERVER['REQUEST_METHOD'] && !empty( $_POST['action'] ) &&  $_POST['action'] == "generate-one-sheet" && check_admin_referer( 'verify_generate_one_sheet', 'nonce_generate_one_sheet' )) { 

$content = '// Add main content';

// instantiate and use the dompdf class
$dompdf = new Dompdf();
$dompdf->loadHtml($content);

// (Optional) Setup the paper size and orientation
$dompdf->set_paper( 'letter' , 'portrait' );

// Render the HTML as PDF
$dompdf->render();

$doctitle = get_the_title() . '- MyWebsite.com';
$dompdf->stream($doctitle);

exit();
}

 
We’ve now created our foundation for the PDF export we’re going to expand on. Next step, we want to create a form somewhere within the single.php file where we can trigger this download. I would recommend putting it somewhere after the_content() function. My example will look something like this:
 

<form class="form-horizontal" id="" role="form" action="" method="post">
	<button type="submit" class="download-details">
	    Download The Details<i class="fa fa-download"></i>
	</button>
	<input type="hidden" name="action" value="generate-one-sheet" />
	<input type="hidden" name="postid" value="<?php echo get_the_ID(); ?>" />
	<?php wp_nonce_field('verify_generate_one_sheet','nonce_generate_one_sheet'); ?>
</form>

 

At this point we’ve installed DOMPDF, created the foundation of how we’re going to create this PDF and then created a from and form handlers to manage the creation. We’re almost there! The last step is getting the correct post content integrated with the PDF generation.

Now let’s go back into the single.php file and find the following line we added earlier:
 

$content = '// Add main content';

 
We are going to replace that line with:
 

//Get post ID from form submission
$my_postid = $_POST['postid'];
//Get the main content from the post
$content_post = get_post($my_postid);
$thecontent = $content_post->post_content;        
$thecontent = apply_filters('the_content', $thecontent);
$content = '
<html>
  <head>
   <style>
	   .pdf-title {
		   text-transform: uppercase;
	   }
   </style>
   
  </head>
  <body>
	  <div class="pdf-title">
		  <h1>' . get_the_title() . '</h1>
	  </div>
	  <div class="pdf-content">
		  ' . $thecontent . '
	  </div>
  </body>
  
</html>
';

 
And there we have it. While this is a fairly basic overview with no styling done to the exported PDF, it should give you an idea of what something like this can be capable of. It’s actually fairly easy to create customized PDF exports of WordPress posts and any custom post type. DOMPDF does support some modern CSS3 styling techniques within its output but it can be a bit of a headache to get the exact look your after. That topic is for another day though…


Comments:

  1. whitedd says:

    how to get this work on custom post type?

    1. Cabe Nolan says:

      You would just need to modify the correct single.php file as it pertains the specific post type. Meaning, single-yourposttype.php

  2. David says:

    I’m doing this tutorial but nothing happens when I click on the form, what can I do, download the latest version of domPDF and I have wordpress in version 4.6.1

  3. Rilana Martinato says:

    I am trying to implement this in a custom page template, where I call custom Post Types via WP query. It creats a Error 500, any thaughts or tips on how to fix this?

  4. Phill says:

    If you download the latest version of Dompdf, the above instructions won’t work anymore. The instructions don’t reference the dompdf files at all. Where you see:

    use Dompdf\Dompdf;

    Make it look like this instead:

    require_once get_template_directory() . ‘/dompdf/autoload.inc.php’;
    use Dompdf\Dompdf;

    Otherwise WordPress has no way of finding that file.

  5. vish says:

    doesnt work, i get PHP Fatal error: Uncaught Error: Class ‘dompdf\Dompdf’ not found

Share Your Thoughts

Leave a Reply

Your email address will not be published.


Related Stuff You Might Like







WordPress News, Tips, & Code Snippets

Join the WP Cover mailing list and get wordpress news, tips, code snippets, security warnings, and more delivered right to your inbox.  We won't flood your inbox, newsletters typically go out every 1-2 weeks unless it involves an important security release.

You have Successfully Subscribed!