PHP PDF Generation using FPDF

by Vincy. Last modified on June 8th, 2021.

In this tutorial, we are going to generate PDF from text file data using 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

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

↑ Back to Top