Generate PDF in PHP (FPDF Invoice)
In this lesson: Create PDF invoices and reports in PHP using FPDF — tables, fonts, logo and download — complete working example.
Making PDFs in PHP
PDFs are perfect for invoices, receipts, admit cards and reports — documents that must look the same everywhere and be easy to print. PHP does not create PDFs on its own, so we use a small, free library. Two popular choices are FPDF and Dompdf.
Why you need a library
There is no built-in PDF function in PHP, and building the PDF format by hand is very complex. A library handles all that for you. You install one with Composer:
composer require setasign/fpdf
// or
composer require dompdf/dompdf
Then you include Composer's autoloader and use the library's simple methods.
Creating a PDF with FPDF
FPDF lets you add text and shapes at exact positions.
<?php
require "vendor/autoload.php";
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont("Arial", "B", 16);
$pdf->Cell(40, 10, "Invoice #1001");
$pdf->Ln();
$pdf->SetFont("Arial", "", 12);
$pdf->Cell(40, 10, "Total: Rs 2500");
$pdf->Output(); // show in browser
?>
AddPage starts a page, SetFont sets the font, Cell prints a box of text, and Output sends the PDF. It is ideal for precise, structured layouts.
HTML to PDF with Dompdf
If you already have HTML, Dompdf turns it straight into a PDF.
<?php
require "vendor/autoload.php";
use Dompdf\Dompdf;
$dompdf = new Dompdf();
$dompdf->loadHtml("<h1>Invoice #1001</h1><p>Total: Rs 2500</p>");
$dompdf->render();
$dompdf->stream("invoice.pdf");
?>
You write normal HTML and CSS, and Dompdf renders it as a PDF. This is great when you already have an HTML template for the document.
Common uses
- Invoices and receipts for orders and payments.
- Admit cards and certificates for schools and exams.
- Reports like sales summaries or attendance.
- Tickets and passes that users download and print.
Common mistakes
- Output before the PDF. A stray space or echo corrupts the file — output only the PDF.
- Expecting PHP to do it alone. You need a library like FPDF or Dompdf.
- Complex CSS in Dompdf. It supports common CSS, but very advanced layouts may not render perfectly.
- Not installing via Composer. Add the library properly and include the autoloader.
Summary
- PHP needs a library to create PDFs — FPDF or Dompdf.
- FPDF places text and shapes by position (precise control).
- Dompdf converts HTML/CSS into a PDF (familiar approach).
- Output with
Output()(FPDF) orstream()(Dompdf), with no output before. - Great for invoices, certificates, reports and tickets.
Next, pull the data from MySQL, or export it another way with CSV export.
Frequently Asked Questions
Can PHP create PDF files on its own?
What is the difference between FPDF and Dompdf?
How do I output a PDF to the browser?
$pdf->Output(); with Dompdf, call $dompdf->stream(). You can show it inline in the browser or force a download, and there must be no other output before it.