How to print PDF in WordPress

How to print PDF in WordPress

Printing PDF from the database content in WordPress is relatively easy with the help of the help of mpdf library, but you will need ssh access to the server to install it via composer. You should create HTML code as for a normal web page and the mpdf library will turn everything in PDF.

Installing  mpdf in your theme

Go ahead and create a folder mpdf inside your theme. Then run the composer command that will get and install the mpdf library:

composer require mpdf/mpdf

This will get the files and install them inside the mpdf folder, so the file structure will now be: /your-theme/mpdf/vendor/

Generating PDF files in wordpress frontend

Next things will be implemented via the functions.php file inside the theme. First we will create an action and a function to check if the browser send a parameter. This way you can generate a PDF file from any post or page in WordPress just by adding a parameter to the URL, for example: https://www.example.com/my-page/?print_id=1 will execute the function view_conferinta() – which will execute the mpdf thing.

add_action('init', 'congres_redirect');

function congres_redirect() {
  if(isset($_GET['print_id'])) {
    view_conferinta();
  }
}

Let’s create the view_conferinta () function.


function view_conferinta() {

}

Inside we will create a variable #output and add the HTML code that will create the PDF file content. That’s right, you should create HTML code as for a normal web page and the mpdf library will turn everything in PDF. You can use some css and you can also add code to get info from the database (note how I bread $output to query the current user id and insert first_name and last_name):


function view_conferinta() {

$output = '<html>
<head><title>Page title</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /></head>
<style>
.printable {
border-collapse: collapse;
border: 1px solid #ddd;
}
.printable td {
border:1px solid #ddd;
padding:5px;
}
</style>
<body>';

$id_rez = wp_get_current_user();

$output .='<div style="">Prenume: '.get_user_meta( $id_rez, 'first_name', true ).'</div>
<div style="">Nume: '.get_user_meta( $id_rez, 'last_name', true ).'</div>';

$output .= '
</body>
</html>';

}

The only thing left to do is to call the mpdf just before the ending }. So add the following code:


include(dirname(__FILE__)."/mpdf/mpdf.php");
$mpdf=new mPDF('c', 'A4-L');
$mpdf->WriteHTML($output);
$mpdf->Output();
exit;

That is all. Enjoy!