PHP PDF Generation using FPDF

by Vincy. Last modified on July 15th, 2022.

In this tutorial, we are going to generate PDFs from text file data using the PHP FPDF library. FPDF is unarguably the best server-side PDF generation PHP library. This library has rich features right from adding a PDF page to creating grids and more.

In this example, we are having a text file that contains toys detail as records. We are reading this file’s content, then generate a PDF document and display it in the browser.

View Demo

PHP-FPDF Code for PDF Generation

The following code is used to generate a PDF file based on the text file data and display the PDF on the browser.

It is just a one-file PHP script and has an accompanying text file. You can download the project below.

pdf generation project structure

The download zip file does not have the FPDF package. You need to download FPDF and put inside the project to execute this script.

I have tested this script till FPDF v 1.83. This is a getting started the basic script and is expected to work on all the FPDF versions released till now.

php_pdf

<?php
require('fpdf/fpdf.php');
$pdf = new FPDF();
$pdf->AddPage();
$row=file('toys.txt');
$pdf->SetFont('Arial','B',12);	
foreach($row as $rowValue) {
	$data=explode(';',$rowValue);
	foreach($data as $columnValue)
		$pdf->Cell(90,12,$columnValue,1);
		$pdf->SetFont('Arial','',12);		
		$pdf->Ln();
}
$pdf->Output();
?>

View DemoDownload

Vincy
Written by Vincy, a web developer with 15+ years of experience and a Masters degree in Computer Science. She specializes in building modern, lightweight websites using PHP, JavaScript, React, and related technologies. Phppot helps you in mastering web development through over a decade of publishing quality tutorials.

Leave a Reply

Your email address will not be published. Required fields are marked *

↑ Back to Top

Share this page