To generate a PDF using an HTML form in PHP using the MPDF
library, you can follow these steps:
Step 1: Install the MPDF
library.
Download the MPDF
library from the official website (https://mpdf.github.io/) and extract the files to your PHP project directory.
Step 2: Create an HTML form.
Create an HTML form with the input fields and submit button for the data you want to include in the PDF. For example:
1 2 3 4 5 6 7 8 9 |
<form method="post" action="generate_pdf.php"> <label for="name">Name:</label> <input type="text" name="name" id="name"> <label for="email">Email:</label> <input type="email" name="email" id="email"> <input type="submit" value="Generate PDF"> </form> |
Step 3: Create the PHP script to generate the PDF.
Create a new PHP file (e.g., generate_pdf.php
) and include the MPDF
library files at the beginning of the script.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
require_once __DIR__ . '/mpdf/vendor/autoload.php'; use \Mpdf\Mpdf; // Get form data $name = $_POST['name']; $email = $_POST['email']; // Create new PDF instance $mpdf = new Mpdf(); // Generate PDF content $html = '<h1>PDF Generated from Form</h1>'; $html .= '<p>Name: ' . $name . '</p>'; $html .= '<p>Email: ' . $email . '</p>'; // Add content to PDF $mpdf->WriteHTML($html); // Output PDF $mpdf->Output('generated_pdf.pdf', 'D'); |
In the above code, we first require the autoload.php
file provided by the MPDF
library to autoload the required classes. Then, we retrieve the form data using $_POST
superglobal variables. Next, we create a new instance of the Mpdf
class. We generate the PDF content by concatenating the form data into an HTML string. We use the WriteHTML
method of Mpdf
to add the HTML content to the PDF. Finally, we use the Output
method to output the generated PDF for the user to download (‘D’ parameter).
Make sure to adjust the path to the autoload.php
file based on your project directory structure.
Step 4: Run the PHP script.
Upload the HTML form and the PHP script to your PHP-enabled server. Access the HTML form in a browser and submit it. The PHP script will generate the PDF with the submitted form data, and it will prompt the user to download the PDF file.