9951 explained code solutions for 126 technologies


php-tcpdfHow do I generate a PDF file using TCPDF, PHP and MySQL?


Using TCPDF, PHP and MySQL, you can generate a PDF file with the following steps:

  1. Include the TCPDF library in your project:
require_once('tcpdf_include.php');
  1. Create a new PDF document:
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
  1. Connect to the MySQL database:
$db = new mysqli('host', 'username', 'password', 'database');
  1. Retrieve data from the database:
$sql = "SELECT * FROM table";
$result = $db->query($sql);
  1. Iterate through the result and add content to the PDF:
while ($row = $result->fetch_assoc()) {
  $pdf->Cell(0, 0, $row['field_name'], 0, 1);
}
  1. Output the PDF to the browser:
$pdf->Output('example.pdf', 'I');
  1. Close the database connection:
$db->close();

Helpful links

Edit this code on GitHub