Using the pdf library dompdf in your WordPress page to convert some HTML you already have generated to a PDF file will be explained in this article. We will be doing that by creating a WordPress page template. The page template will include the dompdf library and convert an example HTML to a PDF file. The PDF file generated can be opened in a browser or downloaded. We will do that without the requirement of a dompdf WordPress plugin.
First you can download the latest dompdf library from the page given on the link ahead by clicking the green code icon on that page and choosing option Download as Zip. Here is the Link (Opens a New Tab)
I have already tried to use the WordPress existing page templates headers section, but using the WordPress page template’s headers gives the headers already sent error on the line number where the WordPress headers code appears in the page template. So I excluded the WordPress headers and created my own header section in the page template appearing after the PHP code that converts the HTML to PDF file.
The standard theme’s page template in my theme looked like following
<?php /** * The template for displaying all pages. * * This is the template that displays all pages by default. * Please note that this is the WordPress construct of pages * and that other 'pages' on your WordPress site will use a * different template. * * @package dazzling */ get_header(); ?> <div id="primary" class="content-area col-sm-12 col-md-8"> <main id="main" class="site-main" role="main"> <?php while ( have_posts() ) : the_post(); ?> <?php get_template_part( 'content', 'page' ); ?> <?php // If comments are open or we have at least one comment, load up the comment template if ( comments_open() || '0' != get_comments_number() ) : comments_template(); endif; ?> <?php endwhile; // end of the loop. ?> </main><!-- #main --> </div><!-- #primary --> <?php get_sidebar(); ?> <?php get_footer(); ?>
I created a wordpress Child theme for including the dompdf library and proceeding ahead with my work. And removed the header and footer sections. You can blend the page to look like your main theme by using HTML and CSS create a header and footer div with logos and some important menu items later. Those things are not in the scope of this article. We will focus on including the dompdf library and converting HTML to PDF using that.
So the empty child theme’s page template PHP file now looks like as shown below. Note that I have removed the WordPress functions and code. Upload this to your child theme and create a New Page using this Child theme My PDF Page.
<?php /** * Template Name: My PDF Page * * This is the template that displays the pdf generation page. * */
Now we shall add some html to the php page to show the the pdf generation button and including the dompdf library. The new Template file now looks like below. You can replace the code in your existing php file.
<?php /** * Template Name: My PDF Page * * This is the template that displays the pdf generation page. * */ // supressing notices error_reporting(E_ALL & ~E_NOTICE); // Reference the Dompdf namespace //MUST COME AT TOP OF FILE IN PUBLIC SCOPE use Dompdf\Dompdf; ?> <!DOCTYPE html> <html lang="en-US"> <head> <meta charset="UTF-8"> <title>My Page Title</title> <meta name="robots" content="index, follow"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content="Add the page description here" /> <meta name="keywords" content="Add your keywords separated by commas here,keyword2,keyword 3" /> <style> h2, .h2 { font-size: 20px ; color:#ED9121; } h1, .h1 { font-size: 26px ; color:#ED9121; } body{ font-family:Verdana; color:#718096; } body a { color:#00BFFF; background-color: transparent; text-decoration: none; } body a:hover { color:#FF7133; text-decoration: underline; } div.line{ border-bottom: 1px dotted #e4e4e4; } .j-container{ box-sizing:border-box; } .j-main{ width: 45%; margin:auto; padding:10px; text-align:justify; font-size: 1.2em; /*background-color:#FDE7F5;*/ } /* ------------- Media -------------- */ @media screen and (max-width:800px) { h2, .h2 { font-size: 20px ; color:#ED9121; } h1, .h1 { font-size: 26px ; color:#ED9121; } .j-main { width:99.99%; font-size:1.6em; } .j-container{ box-sizing:border-box; padding:0px 10px 0px 10px !important;*/ } .j-main{ box-sizing:border-box; padding-right:10px !important; } }/* end @media screen */ .my_content{ font-size:14px; } </style> </head> <body> <div class="j-container"> <div class="j-main"> <div class="my_content"> <img style="float: left; padding:15px 15px 0px 0px;;" src="logo.png" alt="Site Logo" width="50" height="50px" alt="logo" /><div style="vertical-align:middle;padding-top:2px;"><h1>My Site Name</h1></div><br> <div style="padding-bottom:10px" align="center"><h2>Change This to What this Page does : Generate Pdf</h2></div> <h2>About This Page.</h2> But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure? <br><br><div class="line"></div> <h2>Generate pdf.</h2> <form method="post" id="tt_form"> <div style="padding:17px 0px 17px 0px;"><input type="checkbox" id="browser" name="open_in_browser" checked> <label for="browser">Open PDF in browser.(<font color="#00CD00"><b>Optional</b></font>) (If Unchecked pdf will be downloaded instead. Keep this checked as default specially for Hand Held Mobile Devices.)</label></div><div class="line"></div> <div align="center" style="padding:30px 0px 30px 0px;"><button style="padding:8px;color:blue;" type="submit" id="btn" name="cf-submit" value="" />GENERATE PDF FILE AND WAIT</button><br><span style="color:red;">(It takes <i>some time for pdf to be generated so wait patiently</span></div> </div> <div class="my_content"> <h2>Some more content</h2> But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure? </div> </div> </div> </body> </html> <?php //get_footer(); ?> <?php // BEGIN PHP FUNCTIONS
In the above code line 13 is very important. Here we are including the dompdf library to WordPress.
Extract the Zip File you have downloaded from GitHub to a folder of same name. The extracted folder will be a folder with the dompdf version name like dompdf_0-8-1. Navigate inside this folder and you will locate a folder dompdf.
Using FTP, upload this dompdf folder as it is to your child theme’s directory where your page template file exists.
We are now ready to include further code to handle form submission and generate PDF from HTML in our WordPress theme’s template file and we will now incorporate further code to our template file.
The following Code will handle the form submission when someone clicks the generate PDF file button. This PHP code will come before the HTML begins.
$html = ""; // the variable to hold our html if ( $_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['cf-submit'])) { // $html already has the required html as it is globally accessed // and filled by the get_html() function. $html_to_process = get_html(); stream_pdf_file($html_to_process); // function to write the html to pdf and stream pdf }
The function get_html() in line 7 above will fetch the html to be converted to pdf in the variable $html inline 1, using the php output buffering technique. The function stream_pdf_file($html_to_process) in line 8 will actually use the passed HTML as argument to stream the PDF file. These two functions will be explained in following sections.
Note that, in our form we also have a checkbox, which if ticked will open the PDF in browser, else will create a PDF download from our WordPress website.
The get_html() function.
function get_html(){ // start buffering html, dont send to browser, // note no white space at start of html after php end tag. ob_start(); //========= HTML CODE BEGINS HERE AFTER PHP END TAG ==================== ?><!DOCTYPE html> <html lang="en-US"> <head> <meta charset="UTF-8"> <title>My Page Title</title> <meta name="robots" content="index, follow"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content="Add the page description here" /> <meta name="keywords" content="Add your keywords separated by commas here,keyword2,keyword 3" /> <style> h2, .h2 { font-size: 20px ; color:#ED9121; } h1, .h1 { font-size: 26px ; color:#ED9121; } body{ font-family:Verdana; color:#718096; } body a { color:#00BFFF; background-color: transparent; text-decoration: none; } body a:hover { color:#FF7133; text-decoration: underline; } div.line{ border-bottom: 1px dotted #e4e4e4; } .j-container{ box-sizing:border-box; } .j-main{ width: 45%; margin:auto; padding:10px; text-align:justify; font-size: 1.2em; /*background-color:#FDE7F5;*/ } /* ------------- Media -------------- */ @media screen and (max-width:800px) { h2, .h2 { font-size: 20px ; color:#ED9121; } h1, .h1 { font-size: 26px ; color:#ED9121; } .j-main { width:99.99%; font-size:1.6em; } .j-container{ box-sizing:border-box; padding:0px 10px 0px 10px !important;*/ } .j-main{ box-sizing:border-box; padding-right:10px !important; } }/* end @media screen */ .my_content{ font-size:14px; } </style> </head> <body> <div class="j-container"> <div class="j-main"> <div class="my_content"> <div style="vertical-align:middle;padding-top:2px;"><h1>My Site Name</h1></div><br> <div style="padding-bottom:10px" align="center"><h2>Change This to What this Page does : Generate Pdf</h2></div> <h2>About This Page.</h2> But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure? <br><br><div class="line"></div> </div> </div> </div> </body> </html> <?php //========= HTML CODE BEGINS ENDS BEFORE THE BEGINING PHP TAG ==================== global $html; $html = ob_get_contents(); // get all html in buffer to the $html global variable ob_end_clean(); // clean the buffer return $html; // return html }
The code is well commented, basically ob_start() function in line 6 will not allow php to send the output to the browser, but store in a buffer. After that we paste the full HTML code that is required to be rendered as PDF file.
Important – While pasting the HTML there should be no white space between the beginning of HTML and the closing PHP tag as shown in line 10 above.
The HTML to be converted to pdf ends at line 120 and PHP begins at line 121. The function ob_get_contents() gets the content of the buffer into the global $html variable. Finally we clean the php buffer as it is no longer required in line 126.
Loading HTML from existing HTML file in WordPress directory or a PHP file giving HTML output
to do this replace the code in the if condition
if ( $_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['cf-submit'])) { // $html already has the required html as it is globally accessed // and filled by the get_html() function. $html_to_process = get_html(); stream_pdf_file($html_to_process); // function to write the html to pdf and stream pdf }
with following code
if ( $_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['cf-submit'])) { //enter URL of html file, enter URL as http:// or https:// //file can be php file with HTML output $fileUrl = "http://localhost/_s/scripts/wpArticles/test.php"; //get file content after the script is server-side interpreted $fileContent = file_get_contents( $fileUrl ) ; stream_pdf_file($fileContent); }
The stream_pdf_file() function, takes the $html variable which has the HTML as the argument and processes it to stream the PDF to the browser or as a downloadable file depending on the option selected in the form. The code is as under
function stream_pdf_file($contents){ // Include autoloader require_once 'dompdf/autoload.inc.php'; // Instantiate and use the dompdf class $dompdf = new Dompdf(); $dompdf->set_option('enable_html5_parser', TRUE); $dompdf->loadHtml($contents); // (Optional) Setup the paper size and orientation $dompdf->setPaper('A4', 'Portrait'); // Render the HTML as PDF $dompdf->render(); $outputfile = 'PDFpage.pdf'; // Output the generated PDF to Browser/file //to file - file must not be open remember //$output = $dompdf->output(); //file_put_contents($outputfile, $output); //to browser ob_end_clean(); if ( isset( $_POST["open_in_browser"] )){ $dompdf->stream($outputfile, array("Attachment" => false)); }else{ //$dompdf->stream($outputfile); // this creates pdf download $dompdf->stream($outputfile, array("Attachment" => true)); // this opens pdf in browser if set to false, so setting true //does same thing as stream(($outputfile); in previous line } exit(0); }
In the above code dompdf is loaded into WordPress in line 4. Note that if you have uploaded the dompdf directory in the child theme as earlier explained in this article no path is required to be changed. You can set the orientation to Landscape in line 15.
Here is the Complete code of the Page Template to run Dompdf HTML to PDF conversion in WordPress
<?php /** * Template Name: My PDF Page * * This is the template that displays the pdf generation page. * */ // supressing notices error_reporting(E_ALL & ~E_NOTICE); // Reference the Dompdf namespace //MUST COME AT TOP OF FILE IN PUBLIC SCOPE use Dompdf\Dompdf; $html = ""; // the variable to hold our html if ( $_SERVER["REQUEST_METHOD"] == "POST" && isset($_POST['cf-submit'])) { // $html already has the my_html session variable $html_to_process = get_html(); stream_pdf_file($html_to_process); // function to write the html to pdf and stream pdf // uncomment following section and comment above two lines //if you want html content to be loaded from a html file instead /* //enter URL of html file, enter URL as http:// or https:// //file can be php file with HTML output $fileUrl = "http://localhost/_s/scripts/wpArticles/test.php"; //get file content after the script is server-side interpreted $fileContent = file_get_contents( $fileUrl ) ; stream_pdf_file($fileContent); */ } ?><!DOCTYPE html> <html lang="en-US"> <head> <meta charset="UTF-8"> <title>My Page Title</title> <meta name="robots" content="index, follow"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content="Add the page description here" /> <meta name="keywords" content="Add your keywords separated by commas here,keyword2,keyword 3" /> <style> h2, .h2 { font-size: 20px ; color:#ED9121; } h1, .h1 { font-size: 26px ; color:#ED9121; } body{ font-family:Verdana; color:#718096; } body a { color:#00BFFF; background-color: transparent; text-decoration: none; } body a:hover { color:#FF7133; text-decoration: underline; } div.line{ border-bottom: 1px dotted #e4e4e4; } .j-container{ box-sizing:border-box; } .j-main{ width: 45%; margin:auto; padding:10px; text-align:justify; font-size: 1.2em; /*background-color:#FDE7F5;*/ } /* ------------- Media -------------- */ @media screen and (max-width:800px) { h2, .h2 { font-size: 20px ; color:#ED9121; } h1, .h1 { font-size: 26px ; color:#ED9121; } .j-main { width:99.99%; font-size:1.6em; } .j-container{ box-sizing:border-box; padding:0px 10px 0px 10px !important;*/ } .j-main{ box-sizing:border-box; padding-right:10px !important; } }/* end @media screen */ .my_content{ font-size:14px; } </style> </head> <body> <div class="j-container"> <div class="j-main"> <div class="my_content"> <div style="vertical-align:middle;padding-top:2px;"><h1>My Site Name</h1></div><br> <div style="padding-bottom:10px" align="center"><h2>Change This to What this Page does : Generate Pdf</h2></div> <h2>About This Page.</h2> But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure? <br><br><div class="line"></div> <h2>Generate pdf.</h2> <form method="post" id="tt_form"> <div style="padding:17px 0px 17px 0px;"><input type="checkbox" id="browser" name="open_in_browser" checked> <label for="browser">Open PDF in browser.(<font color="#00CD00"><b>Optional</b></font>) (If Unchecked pdf will be downloaded instead. Keep this checked as default specially for Hand Held Mobile Devices.)</label></div><div class="line"></div> <div align="center" style="padding:30px 0px 30px 0px;"><button style="padding:8px;color:blue;" type="submit" id="btn" name="cf-submit" value="" />GENERATE PDF FILE AND WAIT</button><br><span style="color:red;">(It takes <i>some time</i> for pdf to be generated so wait patiently</span></div> </div> <div class="my_content"> <h2>Some more content</h2> But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure? </div> </div> </div> </body> </html> <?php function stream_pdf_file($contents){ // Include autoloader require_once 'dompdf/autoload.inc.php'; // Instantiate and use the dompdf class $dompdf = new Dompdf(); $dompdf->set_option('enable_html5_parser', TRUE); $dompdf->loadHtml($contents); // (Optional) Setup the paper size and orientation $dompdf->setPaper('A4', 'Portrait'); // Render the HTML as PDF $dompdf->render(); $outputfile = 'PDFpage.pdf'; // Output the generated PDF to Browser/file //to file - file must not be open remember //$output = $dompdf->output(); //file_put_contents($outputfile, $output); //to browser ob_end_clean(); if ( isset( $_POST["open_in_browser"] )){ $dompdf->stream($outputfile, array("Attachment" => false)); }else{ //$dompdf->stream($outputfile); // this creates pdf download $dompdf->stream($outputfile, array("Attachment" => true)); // this opens pdf in browser if set to false, so setting true //does same thing as stream(($outputfile); in previous line } exit(0); } function get_html(){ // start buffering html, dont send to browser, // note no white space at start of html after php end tag. ob_start(); //========= HTML CODE BEGINS HERE AFTER PHP END TAG ==================== ?><!DOCTYPE html> <html lang="en-US"> <head> <meta charset="UTF-8"> <title>My Page Title</title> <meta name="robots" content="index, follow"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content="Add the page description here" /> <meta name="keywords" content="Add your keywords separated by commas here,keyword2,keyword 3" /> <style> h2, .h2 { font-size: 20px ; color:#ED9121; } h1, .h1 { font-size: 26px ; color:#ED9121; } body{ font-family:Verdana; color:#718096; } body a { color:#00BFFF; background-color: transparent; text-decoration: none; } body a:hover { color:#FF7133; text-decoration: underline; } div.line{ border-bottom: 1px dotted #e4e4e4; } .j-container{ box-sizing:border-box; } .j-main{ width: 45%; margin:auto; padding:10px; text-align:justify; font-size: 1.2em; /*background-color:#FDE7F5;*/ } /* ------------- Media -------------- */ @media screen and (max-width:800px) { h2, .h2 { font-size: 20px ; color:#ED9121; } h1, .h1 { font-size: 26px ; color:#ED9121; } .j-main { width:99.99%; font-size:1.6em; } .j-container{ box-sizing:border-box; padding:0px 10px 0px 10px !important;*/ } .j-main{ box-sizing:border-box; padding-right:10px !important; } }/* end @media screen */ .my_content{ font-size:14px; } </style> </head> <body> <div class="j-container"> <div class="j-main"> <div class="my_content"> <div style="vertical-align:middle;padding-top:2px;"><h1>My Site Name</h1></div><br> <div style="padding-bottom:10px" align="center"><h2>Change This to What this Page does : Generate Pdf</h2></div> <h2>About This Page.</h2> But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure? <br><br><div class="line"></div> </div> </div> </div> </body> </html> <?php //========= HTML CODE BEGINS ENDS BEFORE THE BEGINING PHP TAG ==================== global $html; $html = ob_get_contents(); // get all html in buffer to the $html global variable ob_end_clean(); // clean the buffer return $html; // return html }
Do not forget to comment/uncomment lines 22,23 and 31 to 36 in the above code depending upon how you want to load the HTML to be converted to PDF file , from the same PHP file or from an external PHP or HTML file in your wordpress installation.
If you face any problems, please leave a comment.
That is all.
If you liked this article please do leave a reply and share it with friends.
Thanks.