How to dowload pdf using PHP


In this tutorial we will learn how to download pdf using PHP or how to print specific content from a webpage in pdf format.


Now follow below steps to download pdf using PHP.


Step 1- Install Mpdf php Library

$ composer require mpdf/mpdf

Simply Paste the above Command in your Composer. ( If you dont know that what is composer and how to install composer then click here and follow step 1 to step 3  or dowload it from here Dowload Composer . )

Please ensure that the mpdf file is downloaded into your job folder.


OUTPUT-


Step 2- Make a new Index.php file

Step 3-  Load autoload.php file from vendor

<?php

 

require('vendor/autoload.php');

 

?>



Step 4-  Make a variable for content to generate Pdf page

Here you need to create a variable in which all the code are stored, which you want to print into pdf format.

 $html =  " <table border=\"1\" >

    <tr>

        <th>#</th>

        <th>Name</th>

        <th>Age</th>

        <th>City</th>

    </tr>";

$html .=

    <tr>

        <td>1</td>

        <td>Sumit Sarkar</td>

        <td>28</td>

        <td>Mumbai</td>

    </tr>

    <tr>

        <td>2</td>

        <td>Akash Sharma</td>

        <td>28</td>

        <td>Delhi</td>

    </tr>        <tr>

        <td>1</td>

        <td>Nitu Dey</td>

        <td>28</td>

        <td>Kolkata</td>

    </tr>        <tr>

        <td>1</td>

        <td>Sumit</td>

        <td>28</td>

        <td>Mumbai</td>

    </tr>";

$html .= "</table>"; 


Step 5-  Now need to include the mpdf library class

$mpdf = new \Mpdf\Mpdf();

$mpdf->WriteHTML($html);

$file = "test.pdf";

$mpdf->Output($file , 'D');  // direct download the pdf page  when run on server

// $mpdf->Output($file , 'I');  // pdf page open on browser tab

// $mpdf->Output($file , 'F');  // pdf page save on your file

 


Step 6 – Now run the file in your Browser


OUTPUT –

image

 

Now we will see full code which we described above

<?php

require('vendor/autoload.php');

 

$html =  " <table border=\"1\" >

    <tr>

        <th>#</th>

        <th>Name</th>

        <th>Age</th>

        <th>City</th>

    </tr>";

$html .=

    <tr>

        <td>1</td>

        <td>Sumit Sarkar</td>

        <td>28</td>

        <td>Mumbai</td>

    </tr>

    <tr>

        <td>2</td>

        <td>Akash Sharma</td>

        <td>28</td>

        <td>Delhi</td>

    </tr>        <tr>

        <td>1</td>

        <td>Nitu Dey</td>

        <td>28</td>

        <td>Kolkata</td>

    </tr>        <tr>

        <td>1</td>

        <td>Sumit</td>

        <td>28</td>

        <td>Mumbai</td>

    </tr>";

$html .= "</table>";

 

$mpdf = new \Mpdf\Mpdf();

$mpdf->WriteHTML($html);

$file = "test.pdf";

$mpdf->Output($file , 'D');  // direct download the pdf page  when run on server

// $mpdf->Output($file , 'I');  // pdf page open on browser tab

// $mpdf->Output($file , 'F');  // pdf page save on your file

 

?>