Web Dev Tuts

/ Stuffs About Website Development /

Menu
  • Home
  • Wp Plugins
  • How To
  • FAQ
    • GIT
    • JQuery
    • PHP
    • WooCommerce
    • WordPress
  • Contact Us
Menu

Create a Dynamic PDF File Based on User’s Input

Posted on June 12, 2016November 28, 2020 by admin

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 -->

</form>

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->SetPrintHeader(false);
$pdf->SetPrintFooter(false);
$pdf->AddPage();
$pdf->Write(0, 'Hello ' . $name . '!');
$pdf->Output($filename, 'F');

Step 3:

form-flow1(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.

echo 'Click <a href="' . $filename . '">here</a> to download the file.';

(b) If you want to directly show the download pop up window, just add the ff. code:

header('Content-disposition: attachment; filename=MY.pdf');
header('Content-type: application/pdf');
readfile($filename);

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”.

 

 

Category: PHP

Leave a Reply Cancel reply

You must be logged in to post a comment.

Recent Posts

  • How to add wp_editor Dynamically
  • How to Hide Certain Pages from Certain Users (WP Dashboard)
  • How to Set Up Gmail SMTP
  • How to Set Up Virtual Host in Localhost & Xampp
  • How to Determine the Current WordPress Version Used
  • AngularJs
  • CSS
  • For Me Only
  • geo location api
  • GIT
  • GoDaddy
  • Hosting
  • How To
  • Javascript
  • JQuery
  • Magento
  • My Notes
  • PHP
  • Private
  • Sass
  • WooCommerce
  • Wordpress
  • Xampp
© 2023 Web Dev Tuts | Powered by Minimalist Blog WordPress Theme