Generating PDF Reports in PHP: Choosing a Library
Creating PDF documents is one of the most in-demand tasks in web development. Invoices, acts, statistical reports, price lists — all of these often need to be generated dynamically on the server side. PHP offers several mature libraries for PDF generation. In this article, we will cover three of the most popular tools: FPDF, TCPDF, and Dompdf, and provide practical code examples.
1. FPDF — Lightweight and Fast Classic
FPDF is a simple library that requires no external dependencies. It is ideal for basic reports: text, tables, simple images. Key features:
- Works without installing additional extensions (except standard GD for images).
- Supports UTF-8 via a separate plugin (tFPDF) or manual font conversion.
- Excellent performance on simple documents.
Example of creating a simple PDF report with a table:
<?phprequire('fpdf.php');
$pdf = new FPDF();$pdf->AddPage();$pdf->SetFont('Arial', 'B', 16);$pdf->Cell(40, 10, 'Sales Report', 0, 1);$pdf->SetFont('Arial', '', 12);
// Table headers$pdf->Cell(40, 10, 'Product', 1);$pdf->Cell(30, 10, 'Quantity', 1);$pdf->Cell(40, 10, 'Price', 1);$pdf->Ln();
// Data$pdf->Cell(40, 10, 'Laptop', 1);$pdf->Cell(30, 10, '5', 1);$pdf->Cell(40, 10, '45000 RUB', 1);$pdf->Ln();$pdf->Cell(40, 10, 'Mouse', 1);$pdf->Cell(30, 10, '10', 1);$pdf->Cell(40, 10, '1200 RUB', 1);
$pdf->Output('D', 'report.pdf');?>2. TCPDF — Powerful Tool for Complex Reports
TCPDF is an extended version of FPDF with support for UTF-8, CSS, HTML tags, QR codes, digital signatures, and much more. Recommended for:
- Documents with Cyrillic and other non-Latin fonts.
- Reports with complex layouts (headers, footers, multi-page tables).
- Generating PDF/A for archiving.
Example of using HTML markup in TCPDF:
<?phprequire_once('tcpdf/tcpdf.php');
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);$pdf->SetCreator('PythonLib');$pdf->SetAuthor('Developer');$pdf->SetTitle('Complex Report');
$pdf->AddPage();$html = '<h2>Monthly Statistics</h2><table border="1" cellpadding="5"><tr><th>Parameter</th><th>Value</th></tr><tr><td>Visitors</td><td>12,450</td></tr><tr><td>Orders</td><td>342</td></tr></table><p>Generated <strong>automatically</strong>.</p>';
$pdf->writeHTML($html, true, false, true, false, '');$pdf->Output('stat.pdf', 'I');?>3. Dompdf — Generation from HTML/CSS
Dompdf is a unique library that renders PDF from plain HTML and CSS. This is an ideal choice if you already have a report layout (e.g., for printing from a browser). It supports:
- CSS 2.1 and partially CSS 3 (float, position, border-radius).
- Embedding images (base64 or by URL).
- Tables, lists, multi-page documents.
Example of converting an HTML template to PDF:
<?phprequire 'vendor/autoload.php';
use Dompdf\\Dompdf;
$dompdf = new Dompdf();$html = '<html><head>