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.
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.
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
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();
?>