How to export to a PDF using FPDF with PHP

Home > Search > How-to
  by

FPDF is software written in PHP which allows you to export HTML pages to PDF. Follow these instructions to download and install FPDF. In this tutorial, I will explain how to use FPDF on a Linux Web server.

  1. Download FPDF from http://www.fpdf.org/en/download.php.
  2. Extract the contents of the tar gunzip using the following command. Notice this command moves the extracted folder to the Web server document root.
tar  -xvzf  /path/to/fpdf-version.tgz  -C  /path/to/web/server/root
  1. Remove the origial tar gunzip file.
rm fpdf-version.tgz

Now that FPDF is installed, we can write HTML and PHP that will allow us to create PDF file from a website. First, let's create a HTML page with a textarea.

<form method="post" action="fpdf.php">
  <textarea name="content" id="content"> </textarea>
  <br />
  <input type="submit" value="create pdf">
</form>

Notice the HTML form passed content to fpdf.php. Create a file named fpdf.php with the following markup.

<?php
require('fpdf-version/fpdf.php');

$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>

 

We can also write HTML and PHP that will allow us to export data to a PDF.  Let's say we have a page which is displaying data we have stored in a database. We can use a form to send the data to our page that will create the PDF. Notice in this example we are sending $data1 to export_pdf.php. This assume our page has created a varible named $data1.

<form method="post" action="export_pdf.php">
  <input type="hidden" name="short_summary" value="<?php echo $data1; ?>">
  <input type="Export to PDF">
</form>

The export_pdf.php page will then handle the creation of the PDF.

<?php
require('fpdf-version/fpdf.php');

$data1 = $_POST['data1'];

$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,$data1);
$pdf->Output('example.pdf', 'D');
?>

For more information, visit http://www.fpdf.org.



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




Please enter in the box below so that we can be sure you are a human.




Comments