9951 explained code solutions for 126 technologies


php-tcpdfHow can I generate a PDF from data stored in a MySQL database using TCPDF and PHP?


The following steps can be used to generate a PDF from data stored in a MySQL database using TCPDF and PHP:

  1. Include the TCPDF library in your PHP code:
require_once('tcpdf_include.php');
  1. Connect to the MySQL database:
$host = "localhost";
$username = "username";
$password = "password";
$dbname = "databasename";

$conn = new mysqli($host, $username, $password, $dbname);
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
  1. Create a query to retrieve the data you need for the PDF:
$sql = "SELECT * FROM users";
$result = $conn->query($sql);
  1. Create a new PDF document using the TCPDF library:
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
  1. Add content to the PDF document:
// set document information
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('John Doe');
$pdf->SetTitle('Users Report');
$pdf->SetSubject('TCPDF Tutorial');
$pdf->SetKeywords('TCPDF, PDF, example, test, guide');

// add a page
$pdf->AddPage();

// create some HTML content
$html = '<h1>Users Report</h1>
        <table>
            <tr>
                <th>ID</th>
                <th>Name</th>
                <th>Email</th>
            </tr>';

// output data from database
while($row = $result->fetch_assoc()) {
    $html .= '<tr>
                <td>'.$row['id'].'</td>
                <td>'.$row['name'].'</td>
                <td>'.$row['email'].'</td>
            </tr>';
}

$html .= '</table>';

// output the HTML content
$pdf->writeHTML($html, true, false, true, false, '');
  1. Output the PDF document:
$pdf->Output('example_001.pdf', 'I');
  1. Close the MySQL connection:
$conn->close();

Helpful links

Edit this code on GitHub