Create a Dynamic PDF File Based on User’s Input
When I need to create a pdf using PHP, I prefer to use the TCPDF library, because I find it easy to use and flexible. I the tutorial Create a PDF Using PHP and TCPDF, you will learn how to create a basic pdf file and add the desired content to it. But if you want to create a form, such as an online calculator and you want to generate a pdf containing the information based on the user’s input, you can achieve it easily by using the solution below:
Step 1: Create a form.
<form name=”create-pdf” method=”post” action=”action.php”>
<div><label for=”name”><input type=”text” name=”_name” id=”name” /></div>
<!– other fields here –>
Step 2: Create a php file that will receive the form and create the pdf. The name and the path must be the same with the value of action in Step 1.
$filename = dirname(__FILE__) . ‘my-tcpdf-‘ . time() . ‘.pdf’;
$name = $_POST[‘_name’];
$pdf = new TCPDF();
$pdf->Write(0, ‘Hello ‘ . $name . ‘!’);
(a) If you want to user to click a link after submitting the form in order to download the pdf, add the following codes to your php file.
[code]echo ‘Click <a href=”‘ . $filename . ‘”>here</a> to download the file.’;[/code]
(b) If you want to directly show the download pop up window, just add the ff. code:
header(‘Content-disposition: attachment; filename=MY.pdf’);
In 3.b, you must not echo anything or show html codes or else you will get an error message such as ”Header has been sent”.